File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.707: download - view: text, annotated - select for diffs
Wed Jan 15 23:19:30 2025 UTC (5 weeks, 1 day ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Remove some traling white space.

    1: # The LearningOnline Network
    2: # Printout
    3: #
    4: # $Id: lonprintout.pm,v 1.707 2025/01/15 23:19:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: # http://www.lon-capa.org/
   26: #
   27: #
   28: package Apache::lonprintout;
   29: use strict;
   30: use Apache::Constants qw(:common :http);
   31: use Apache::lonxml;
   32: use Apache::lonnet;
   33: use Apache::loncommon;
   34: use Apache::inputtags;
   35: use Apache::grades;
   36: use Apache::edit;
   37: use Apache::File();
   38: use Apache::lonnavmaps;
   39: use Apache::admannotations;
   40: use Apache::lonenc;
   41: use Apache::entities;
   42: use Apache::londefdef;
   43: # use Apache::structurelags;	# for language management.
   44: 
   45: use File::Basename;
   46: 
   47: use HTTP::Response;
   48: use LONCAPA::map();
   49: use Apache::lonlocal;
   50: use Carp;
   51: use LONCAPA;
   52: 
   53: 
   54: my %perm;
   55: my %parmhash;
   56: my $resources_printed;
   57: 
   58: # Global variables that describe errors in ssi calls detected  by ssi_with_retries.
   59: #
   60: 
   61: my $ssi_error;			# True if there was an ssi error.
   62: my $ssi_last_error_resource;	# The resource URI that could not be fetched.
   63: my $ssi_last_error;		# The error text from the server. (e.g. 500 Server timed out).
   64: 
   65: #
   66: #  Our ssi max retry count.
   67: #
   68: 
   69: my $ssi_retry_count = 5;	# Some arbitrary value.
   70: 
   71: 
   72: #  Font size:
   73: 
   74: my $font_size = 'normalsize';	# Default is normalsize...
   75: 
   76: #----------------------------  Helper helpers. -------------------------
   77: 
   78: ##
   79: # Filter function to determine if a resource is a printable sequence.
   80: #
   81: # @param $res -Resource to check.
   82: #
   83: # @return 1 - printable and a resource
   84: #         0 - either notm a sequence or not printable.
   85: #
   86: sub printable_sequence {
   87:     my $res = shift;
   88: 
   89:     # Non-sequences are not listed:
   90: 
   91:     if (!$res->is_sequence()) {
   92: 	return 0;
   93:     }
   94: 
   95:     # Person with pav or pfo can always print:
   96: 
   97:     if ($perm{'pav'} || $perm{'pfo'}) {
   98: 	return 1;
   99:     }
  100: 
  101:     if ($res->is_sequence()) {
  102: 	my $symb = $res->symb();
  103: 	my $navmap   = $res->{NAV_MAP};
  104: 
  105: 	# Find the first resource in the map:
  106: 
  107: 	my $iterator = $navmap->getIterator($res, undef, undef, 1, 1);
  108: 	my $first    = $iterator->next();
  109: 
  110: 	while (1) {
  111: 	    if ($first == $iterator->END_ITERATOR) { last; }
  112: 	    if (ref($first) && ! $first->is_sequence()) {last; }
  113: 	    $first = $iterator->next();
  114: 	}
  115: 
  116: 
  117: 	# Might be an empty map:
  118: 
  119: 	if (!ref($first)) {
  120: 	    return 0;
  121: 	}
  122: 	my $partsref = $first->parts();
  123: 	my @parts    = @$partsref;
  124: 	my ($open, $close) = $navmap->map_printdates($first, $parts[0]);
  125: 	return &printable($open, $close);
  126:     }
  127:     return 0;
  128: }
  129: 
  130: # BZ5209:
  131: #    Create the states needed to run the helper for incomplete problems from
  132: #    the current folder for selected students.
  133: #    This includes:
  134: #    -  A resource selector limited to problems (incompleteness must be
  135: #       calculated on a student per student basis.
  136: #    -  A student selector.
  137: #    -  Tie in to the FORMAT of the print job.
  138: #
  139: # States:
  140: #   CHOOSE_INCOMPLETE_PEOPLE_SEQ      - Resource selection.
  141: #   CHOOSE_STUDENTS_INCOMPLETE        - Student selection.
  142: #   CHOOSE_STUDENTS_INCOMPLETE_FORMAT - Format selection
  143: # Parameters:
  144: #    helper - the helper which already contains info about the current folder we can
  145: #             purloin.
  146: #    map    - the map for which incomplete problems are to be printed
  147: #    nocurrloc - True if printout called from icon/link in Tools in /adm/navmaps
  148: # Return:
  149: #     XML that can be parsed by the helper to drive the state machine.
  150: #
  151: sub create_incomplete_folder_selstud_helper {
  152:     my ($helper, $map, $nocurrloc)  = @_;
  153: 
  154: 
  155:     my $symbFilter = '$res->shown_symb()';
  156:     my $selFilter   = '$res->is_problem()';
  157: 
  158: 
  159:     my $resource_chooser = &generate_resource_chooser('CHOOSE_INCOMPLETE_PEOPLE_SEQ',
  160: 						      'Select problem(s) to print',
  161: 						      'multichoice="1" toponly="1" addstatus="1" closeallpages="1" modallink="1" nocurrloc="'.$nocurrloc.'"',
  162: 						      'RESOURCES',
  163: 						      'CHOOSE_STUDENTS_INCOMPLETE',
  164: 						      $map,
  165: 						      $selFilter,
  166: 						      '',
  167: 						      $symbFilter,
  168: 						      '');
  169: 
  170:     my $student_chooser = &generate_student_chooser('CHOOSE_STUDENTS_INCOMPLETE',
  171: 						 'student_sort',
  172: 						 'STUDENTS',
  173: 						 'CHOOSE_STUDENTS_INCOMPLETE_FORMAT');
  174: 
  175:     my $format_chooser = &generate_format_selector($helper,
  176: 						'Format of the print job',
  177: 						'CHOOSE_STUDENTS_INCOMPLETE_FORMAT'); # end state.
  178: 
  179:     return $resource_chooser . $student_chooser . $format_chooser;
  180: }
  181: 
  182: 
  183: # BZ 5209
  184: #     Create the states needed to run the helper for incomplete problems from
  185: #     the current folder for selected students.
  186: #     This includes:
  187: #     - A resource selector limited to problems.  (incompleteness must be calculated
  188: #       on a student per student basis.
  189: #     - A student selector.
  190: #     - Tie in to format for the print job.
  191: # States:
  192: #    INCOMPLETE_PROBLEMS_COURSE_RESOURCES - Resource selector.
  193: #    INCOMPLETE_PROBLEMS_COURSE_STUDENTS  - Student selector.
  194: #    INCOMPLETE_PROBLEMS_COURSE_FORMAT    - Format selection.
  195: #
  196: # Parameters:
  197: #   helper   - Helper we are creating states for.
  198: # Returns:
  199: #   Text that can be parsed by the helper.
  200: #
  201: 
  202: sub create_incomplete_course_helper {
  203:     my $helper = shift;
  204: 
  205:     my $filter = '$res->is_problem() || $res->contains_problem() || $res->is_sequence() || $res->is_practice())';
  206:     my $symbfilter = '$res->shown_symb()';
  207: 
  208:     my $resource_chooser = &generate_resource_chooser('INCOMPLETE_PROBLEMS_COURSE_RESOURCES',
  209: 						      'Select problem(s) to print',
  210: 						      'multichoice = "1" suppressEmptySequences="0" addstatus="1" closeallpagtes="1" modallink="1"',
  211: 						      'RESOURCES',
  212: 						      'INCOMPLETE_PROBLEMS_COURSE_STUDENTS',
  213: 						      '',
  214: 						      $filter,
  215: 						      '',
  216: 						      $symbfilter,
  217: 						      '');
  218: 
  219:     my $people_chooser  = &generate_student_chooser('INCOMPLETE_PROBLEMS_COURSE_STUDENTS',
  220: 						    'student_sort',
  221: 						    'STUDENTS',
  222: 						    'INCOMPLETE_PROBLEMS_COURSE_FORMAT');
  223: 
  224:     my $format = &generate_format_selector($helper,
  225: 					   'Format of the print job',
  226: 					   'INCOMPLETE_PROBLEMS_COURSE_FORMAT'); # end state.
  227: 
  228:     return $resource_chooser . $people_chooser . $format;
  229: 
  230: 
  231: }
  232: 
  233: # BZ5209
  234: #   Creates the states needed to run the print helper for a student
  235: #   that wants to print his incomplete problems from the current folder.
  236: # Parameters:
  237: #   $helper - helper we are generating states for.
  238: #   $map    - The map for which the student wants incomplete problems.
  239: #   $nocurrloc - True if printout called from icon/link in Tools in /adm/navmaps
  240: # Returns:
  241: #   XML that defines the helper states being created.
  242: #
  243: # States:
  244: #   CHOOSE_INCOMPLETE_SEQ  - Resource selector.
  245: #
  246: sub create_incomplete_folder_helper {
  247:     my ($helper, $map, $nocurrloc) = @_;
  248: 
  249:     my $filter    = '$res->is_problem()';
  250:     $filter      .= ' && $res->resprintable() ';
  251:     $filter      .= ' && $res->is_incomplete() ';
  252: 
  253:     my $symfilter = '$res->shown_symb()';
  254: 
  255:     my $resource_chooser = &generate_resource_chooser('CHOOSE_INCOMPLETE_SEQ',
  256: 						      'Select problem(s) to print',
  257: 						      'multichoice="1", toponly ="1", addstatus="1", closeallpages="1" modallink="1" nocurrloc="'.$nocurrloc.'"',
  258: 						      'RESOURCES',
  259: 						      'PAGESIZE',
  260: 						      $map,
  261: 						      $filter, '',
  262: 						      $symfilter,
  263: 						      '');
  264: 
  265:     return $resource_chooser;
  266: }
  267: 
  268: 
  269: #  Returns the text neded for a student chooser.
  270: #  that text must still be parsed by the helper xml parser.
  271: # Parameters:
  272: #   this_state   - State name of the chooser.
  273: #   sort_choice  - variable to hold the sorting choice.
  274: #   variable     - Name of variable to hold students.
  275: #   next_state   - State after chooser.
  276: 
  277: 
  278: sub generate_student_chooser {
  279:     my ($this_state,
  280: 	$sort_choice,
  281: 	$variable,
  282: 	$next_state) = @_;
  283:     my $result = <<CHOOSE_STUDENTS;
  284:   <state name="$this_state" title="Select Students and Resources">
  285:       <message><b>Select sorting order of printout</b> </message>
  286: 
  287:     <choices variable="$sort_choice">
  288:       <choice computer='0'>Sort by section then student</choice>
  289:       <choice computer='1'>Sort by students across sections.</choice>
  290:     </choices>
  291: 
  292:       <message><br /><hr /><br /> </message>
  293:       <student multichoice='1'
  294:                variable="$variable" 
  295:                nextstate="$next_state" 
  296:                coursepersonnel="1" />
  297:   </state>
  298: 
  299: CHOOSE_STUDENTS
  300: 
  301:   return $result;
  302: }
  303: 
  304: # Generate the text needed for a resource chooser given the top level of
  305: # the sequence/page
  306: #
  307: # Parameters:
  308: #     this_state    - State name of the chooser.
  309: #     prompt_text   - Text to use to prompt user.
  310: #     resource_options - Resource tag options e.g.
  311: #                        "multichoice='1', toponly='1', addstatus='1',
  312: #                         modallink='1'"
  313: #                     that control the selection and appearance of the
  314: #                     resource selector.
  315: #     variable      - Name of the variable to hold the choice
  316: #     next_state    - Name of the next state the helper should transition
  317: #                     to
  318: #     top_url       - Top level URL within which to make the selector.
  319: #                     If empty the top level sequence is shown.
  320: #     filter        - How to filter the resources.
  321: #     value_func    - <valuefunc> function.
  322: #     choice_func   - If not empty generates a <choicefunc> with this function.
  323: #     start_new_option
  324: #                   - Fragment appended after valuefunc.
  325: #
  326: #
  327: sub generate_resource_chooser {
  328:     my ($this_state,
  329: 	$prompt_text,
  330: 	$resource_options,
  331: 	$variable,
  332: 	$next_state,
  333: 	$top_url,
  334: 	$filter,
  335: 	$choice_func,
  336: 	$value_func,
  337: 	$start_new_option)  = @_;
  338: 
  339:     my $result = <<CHOOSE_RESOURCES;
  340: <state name="$this_state" title="$prompt_text">
  341:     <resource variable="$variable" $resource_options
  342:               closeallpages="1">
  343:       <nextstate>$next_state</nextstate>
  344:       <filterfunc>return $filter;</filterfunc>
  345: CHOOSE_RESOURCES
  346:     if ($choice_func ne '') {
  347: 	$result .= "<choicefunc>return $choice_func;</choicefunc>";
  348:     }
  349:     if ($top_url ne '') {
  350: 	$result .=  "<mapurl>$top_url</mapurl>";
  351:     }
  352:     $result .= <<CHOOSE_RESOURCES;
  353:       <valuefunc>return $value_func;</valuefunc>
  354:       $start_new_option
  355:       </resource>
  356:     </state>
  357: CHOOSE_RESOURCES
  358:     return $result;
  359: }
  360: #
  361: #   Generate the helper XML for a code choice helper dialog:
  362: #
  363: # Paramters:
  364: #   $helper       - Reference to the helper.
  365: #   $state        - Name of the state for the chooser.
  366: #   $next_state   - Name fo the state to follow the chooser.
  367: #   $bubble_types - Populates the bubble sheet type dropt down.
  368: #   $code_selections - Provides set of code choices that have been used
  369: #   $saved_codes  - Provides the list of saved codes.
  370: #
  371: # Returns;
  372: #   The Xml of the code chooser.
  373: #
  374: sub generate_code_selector {
  375:     my ($helper,
  376: 	$state,
  377: 	$next_state,
  378: 	$bubble_types,
  379: 	$code_selections,
  380: 	$saved_codes) = @_;	# Unpack the parameters.
  381: 
  382:     my $result = <<CHOOSE_ANON1;
  383:   <state name="$state" title="Specify CODEd Assignments">
  384:     <nextstate>$next_state</nextstate>
  385:     <message><h4>Fill out one of the forms below</h4></message>
  386:     <message><br /><hr /> <br /></message>
  387:     <message><h3>Generate new CODEd Assignments</h3></message>
  388:     <message><table><tr><td><b>Number of CODEd assignments to print:</b></td><td></message>
  389:     <string variable="NUMBER_TO_PRINT_TOTAL" maxlength="5" size="5"  noproceed="1">
  390:        <validator>
  391: 	if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) < 1) &&
  392: 	    !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                &&
  393:             !\$helper->{'VARS'}{'SINGLE_CODE'}                    &&
  394: 	    !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'} ) {
  395: 
  396: 	    return "You need to specify the number of assignments to print";
  397: 	}
  398:         if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) >= 1)  &&
  399:              (\$helper->{'VARS'}{'SINGLE_CODE'} ne '') ) {
  400:             return 'Specifying number of codes to print and a specific code is not compatible';
  401:         }
  402: 	return undef;
  403:        </validator>
  404:     </string>
  405:     <message></td></tr><tr><td></message>
  406:     <message><b>Names to save the CODEs under for later:</b></message>
  407:     <message></td><td></message>
  408:     <string variable="ANON_CODE_STORAGE_NAME" maxlength="50" size="20" />
  409:     <message></td></tr><tr><td></message>
  410:     <message><b>Bubblesheet type:</b></message>
  411:     <message></td><td></message>
  412:     <dropdown variable="CODE_OPTION" multichoice="0" allowempty="0">
  413:     $bubble_types
  414:     </dropdown>
  415:     <message></td></tr><tr><td colspan="2"></td></tr><tr><td></message>
  416:     <message></td></tr><tr><td></table></message>
  417:     <message><br /><hr /><h3>Print a Specific CODE </h3><br /><table></message>
  418:     <message><tr><td><b>Enter a CODE to print:</b></td><td></message>
  419:     <string variable="SINGLE_CODE" size="10">
  420:         <validator>
  421: 	   if(!\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}           &&
  422: 	      !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                 &&
  423: 	      !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
  424: 	      return &Apache::lonprintout::is_code_valid(\$helper->{'VARS'}{'SINGLE_CODE'},
  425: 						      \$helper->{'VARS'}{'CODE_OPTION'});
  426: 	  } elsif (\$helper->{'VARS'}{'SINGLE_CODE'} ne ''){
  427: 	      return 'Specifying a code name is incompatible with specifying number of codes.';
  428: 	   } else {
  429: 	       return undef;	# Other forces control us.
  430: 	   }
  431:         </validator>
  432:     </string>
  433:     <message></td></tr><tr><td></message>
  434:         $code_selections
  435:     <message></td></tr></table></message>
  436:     <message><hr /><h3>Reprint a Set of Saved CODEs</h3><table><tr><td></message>
  437:     <message><b>Select saved CODEs:</b></message>
  438:     <message></td><td></message>
  439:     <dropdown variable="REUSE_OLD_CODES">
  440:         $saved_codes
  441:     </dropdown>
  442:     <message></td></tr></table></message>
  443:   </state>
  444: CHOOSE_ANON1
  445: 
  446:    return $result;
  447: }
  448: 
  449: sub generate_common_choosers {
  450:     my ($r,$helper,$map,$url,$isProblem,$symbFilter,$start_new_option) = @_;
  451: 
  452:     my $randomly_ordered_warning =
  453:         &get_randomly_ordered_warning($helper, $map);
  454: 
  455:     # code for a few states used for printout launched from both
  456:     # /adm/navmaps and from a resource by a privileged user:
  457:     #   - To allow resources to be selected for printing.
  458:     #   - To determine pagination between assignments.
  459:     #   - To determine how many assignments should be bundled into a single PDF.
  460: 
  461:     my $resource_selector= &generate_resource_chooser('SELECT_PROBLEMS',
  462:                                                       'Select resources to print',
  463:                                                       'multichoice="1" addstatus="1" closeallpages="1" modallink="1" suppressNavmap="1"',
  464:                                                       'RESOURCES',
  465:                                                       'PRINT_FORMATTING',
  466:                                                       $map,
  467:                                                       $isProblem, '', $symbFilter,
  468:                                                       $start_new_option);
  469:     $resource_selector .=  &generate_format_selector($helper,
  470:                                                      'How should results be printed?',
  471:                                                      'PRINT_FORMATTING').
  472:                            &generate_resource_chooser('CHOOSE_STUDENTS_PAGE',
  473:                                                       'Select Problem(s) to print',
  474:                                                       "multichoice='1' addstatus='1' closeallpages ='1' modallink='1'",
  475:                                                       'RESOURCES',
  476:                                                       'PRINT_FORMATTING',
  477:                                                       $url,
  478:                                                       $isProblem, '',  $symbFilter,
  479:                                                       $start_new_option);
  480: 
  481: # Generate student choosers.
  482: 
  483:     &Apache::lonxml::xmlparse($r, 'helper',
  484:                               &generate_student_chooser('CHOOSE_TGT_STUDENTS_PAGE',
  485:                                                         'student_sort',
  486:                                                         'STUDENTS',
  487:                                                         'CHOOSE_STUDENTS_PAGE'));
  488:     &Apache::lonxml::xmlparse($r, 'helper',
  489:                               &generate_student_chooser('CHOOSE_STUDENTS',
  490:                                                         'student_sort',
  491:                                                         'STUDENTS',
  492:                                                         'SELECT_PROBLEMS'));
  493:     &Apache::lonxml::xmlparse($r, 'helper', $resource_selector);
  494: 
  495:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  496:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  497:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
  498:     my $namechoice='<choice></choice>';
  499:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
  500:         if ($name =~ /^error: 2 /) { next; }
  501:         if ($name =~ /^type\0/) { next; }
  502:         $namechoice.='<choice computer="'.$name.'">'.$name.'</choice>';
  503:     }
  504: 
  505:     my %code_values;
  506:     my %codes_to_print;
  507:     foreach my $key (@names) {
  508:         %code_values = &Apache::grades::get_codes($key, $cdom, $cnum);
  509:         foreach my $key (keys(%code_values)) {
  510:             $codes_to_print{$key} = 1;
  511:         }
  512:     }
  513: 
  514:     my $code_selection;
  515:     foreach my $code (sort {uc($a) cmp uc($b)} (keys(%codes_to_print))) {
  516:         my $choice  = $code;
  517:         if ($code =~ /^[A-Z]+$/) { # Alpha code
  518:             $choice = &letters_to_num($code);
  519:         }
  520:         push(@{$helper->{DATA}{ALL_CODE_CHOICES}},[$code,$choice]);
  521:     }
  522:     if (%codes_to_print) {
  523:         $code_selection .='
  524:         <message><b>Choose single CODE from list:</b></message>
  525:         <message></td><td></message>
  526:             <dropdown variable="CODE_SELECTED_FROM_LIST" multichoice="0" allowempty="0">
  527:               <choice></choice>
  528:               <exec>
  529:                  push(@{$state->{CHOICES}},@{$helper->{DATA}{ALL_CODE_CHOICES}});
  530:               </exec>
  531:             </dropdown>
  532:         <message></td></tr><tr><td></message>
  533:         '.$/;
  534:     }
  535: 
  536:     my @lines = &Apache::lonnet::get_scantronformat_file();
  537:     my $codechoice='';
  538:     foreach my $line (@lines) {
  539:         next if (($line =~ /^\#/) || ($line eq ''));
  540:         my ($name,$description,$code_type,$code_length)=
  541:             (split(/:/,$line))[0,1,2,4];
  542:         if ($code_length > 0 &&
  543:             $code_type =~/^(letter|number|-1)/) {
  544:             $codechoice.='<choice computer="'.$name.'">'.$description.'</choice>';
  545:         }
  546:     }
  547:     if ($codechoice eq '') {
  548:         $codechoice='<choice computer="default">Default</choice>';
  549:     }
  550:     my $anon1 = &generate_code_selector($helper,
  551:                                         'CHOOSE_ANON1',
  552:                                         'SELECT_PROBLEMS',
  553:                                         $codechoice,
  554:                                         $code_selection,
  555:                                         $namechoice) . $resource_selector;
  556: 
  557:     &Apache::lonxml::xmlparse($r, 'helper',$anon1);
  558: 
  559:     my $anon_page = &generate_code_selector($helper,
  560:                                             'CHOOSE_ANON1_PAGE',
  561:                                             'SELECT_PROBLEMS_PAGE',
  562:                                             $codechoice,
  563:                                             $code_selection,
  564:                                             $namechoice) .
  565:                     &generate_resource_chooser('SELECT_PROBLEMS_PAGE',
  566:                                                'Select Problem(s) to print',
  567:                                                "multichoice='1' addstatus='1' closeallpages ='1' modallink='1'",
  568:                                                'RESOURCES',
  569:                                                'PRINT_FORMATTING',
  570:                                                $url,
  571:                                                $isProblem, '',  $symbFilter,
  572:                                                $start_new_option);
  573:     &Apache::lonxml::xmlparse($r, 'helper', $anon_page);
  574:     return ($randomly_ordered_warning,$codechoice,$code_selection,$namechoice);
  575: }
  576: 
  577: #  Returns the XML for choosing how assignments are to be formatted
  578: #  that text must still be parsed by the helper xml parser.
  579: # Parameters: 3 (required)
  580: 
  581: #   helper       - The helper; $helper->{'VARS'}->{'PRINT_TYPE'} used
  582: #                  to check if splitting PDFs by section can be offered.
  583: #   title        - Title for the current state.
  584: #   this_state   - State name of the chooser.
  585: 
  586: sub generate_format_selector {
  587:     my ($helper,$title,$this_state) = @_;
  588:     my $secpdfoption;
  589:     unless (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_anon')     ||
  590:             ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_anon_page') ||
  591:             ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_anon') ||
  592:             ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'select_sequences_problems_for_anon') ||
  593:             ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'select_sequences_resources_for_anon')) {
  594:         $secpdfoption =  '<choice computer="sections">Each PDF contains exactly one section</choice>';
  595:     }
  596:     return <<RESOURCE_SELECTOR;
  597:     <state name="$this_state" title="$title">
  598:     <message><br /><big><i><b>How should the results be printed?</b></i></big><br /></message>
  599:     <choices variable="EMPTY_PAGES">
  600:       <choice computer='0'>Start each student\'s assignment on a new page/column (add a pagefeed after each assignment)</choice>
  601:       <choice computer='1'>Add one empty page/column after each student\'s assignment</choice>
  602:       <choice computer='2'>Add two empty pages/column after each student\'s assignment</choice>
  603:       <choice computer='3'>Add three empty pages/column after each student\'s assignment</choice>
  604:     </choices>
  605:     <nextstate>PAGESIZE</nextstate>
  606:     <message><hr width='33%' /><b>How do you want assignments split into PDF files? </b></message>
  607:     <choices variable="SPLIT_PDFS">
  608:        <choice computer="all">All assignments in a single PDF file</choice>
  609:        $secpdfoption
  610:        <choice computer="oneper">Each PDF contains exactly one assignment</choice>
  611:        <choice computer="usenumber" relatedvalue="NUMBER_TO_PRINT">
  612:             Specify the number of assignments per PDF:</choice>
  613:     </choices>
  614:     </state>
  615: RESOURCE_SELECTOR
  616: }
  617: 
  618: #-----------------------------------------------------------------------
  619: 
  620: # Computes an open and close date from a list of open/close dates for a resource's
  621: # parts.
  622: #
  623: # @param \@opens - reference to an array of open dates.
  624: # @param \@closes - reference to an array of close dates.
  625: #
  626: # @return ($open, $close)
  627: #
  628: # @note If open/close dates are not defined they will be returned as undef
  629: # @note It is possible for there to be no overlap in which case -1,-1
  630: #       will be returned.
  631: # @note The algorithm used is to take the latest open date and the earliest end date.
  632: #
  633: sub compute_open_window {
  634:     my ($opensref, $closesref) = @_;
  635: 
  636:     my @opens   = @$opensref;
  637:     my @closes  = @$closesref;
  638: 
  639:     # latest open date:
  640:     my $latest_open;
  641: 
  642:     foreach my $open (@opens) {
  643: 	if (!defined($latest_open) || ($open > $latest_open)) {
  644: 	    $latest_open = $open;
  645: 	}
  646:     }
  647:     # Earliest close:
  648: 
  649:     my $earliest_close;
  650:     foreach my $close (@closes) {
  651: 	if (!defined($earliest_close) || ($close < $earliest_close)) {
  652: 	    $earliest_close = $close;
  653: 	}
  654:     }
  655: 
  656:     # If no overlap...both are -1 as promised.
  657: 
  658:     if (($earliest_close ne '') && ($latest_open ne '')
  659: 	 && ($earliest_close < $latest_open)) {
  660: 	$latest_open  = -1;
  661: 	$earliest_close = -1;
  662:     }
  663: 
  664:     return ($latest_open, $earliest_close);
  665: 
  666: }
  667: 
  668: ##
  669: #  Determines if 'now' is within the set of printable dates.
  670: #
  671: #  @param $open_date - Starting date/timestamp.
  672: #  @param $close_date - Ending date/timestamp.
  673: #
  674: #  @return 0 - Not open.
  675: #  @return 1 - open.
  676: #
  677: sub printable {
  678:     my ($open_date, $close_date) = @_;
  679: 
  680: 
  681:     my $now = time();
  682: 
  683:     # Have to do a bit of fancy footwork around undefined open/close dates:
  684: 
  685:     if ($open_date && ($open_date > $now)) {
  686: 	return 0;
  687:     }
  688: 
  689:     if ($close_date && ($close_date < $now)) {
  690: 	return 0;
  691:     }
  692: 
  693:     return 1;
  694: 
  695: }
  696: 
  697: ##
  698: # Returns the innermost print start/print end dates for a resource.
  699: # This is done by looking at the start/end dates for its parts and choosing
  700: # the intersection of those dates.
  701: #
  702: # @param res - lonnvamaps::resource object that represents the resource.
  703: #
  704: # @return (opendate, closedate)
  705: #
  706: # @note If open/close dates are not defined they will be returned as undef
  707: # @note It is possible for there to be no overlap in which case -1,-1
  708: #       will be returned.
  709: # @note The algorithm used is to take the latest open date and the earliest end date.
  710: #       For consistency with &printable() in lonnavmaps.pm determination of start
  711: #       date for printing checks printstartdate param first, then, if not set,
  712: #       opendate param, then, if not set, contentopen param.
  713: 
  714: sub get_print_dates {
  715:     my $res = shift;
  716:     my $partsref = $res->parts();
  717:     my @parts;
  718:     if (ref($partsref) eq 'ARRAY') {
  719:         @parts   = @{$partsref};
  720:     }
  721:     my $open_date;
  722:     my $close_date;
  723:     my @open_dates;
  724:     my @close_dates;
  725: 
  726: 
  727:     if (@parts) {
  728: 	foreach my $part (@parts) {
  729: 	    my $partopen  = $res->parmval('printstartdate', $part);
  730: 	    my $partclose = $res->parmval('printenddate',  $part);
  731:             if (!$partopen) {
  732:                 $partopen = $res->parmval('opendate',$part);
  733:             }
  734:             if (!$partopen) {
  735:                 $partopen = $res->parmval('contentopen',$part);
  736:             }
  737:             if ($partopen) {
  738:                 push(@open_dates, $partopen);
  739:             }
  740:             if ($partclose) {
  741:                 push(@close_dates, $partclose);
  742:             }
  743: 	    push(@open_dates, $partopen);
  744: 	    push(@close_dates, $partclose);
  745: 	}
  746:     }
  747: 
  748:     ($open_date, $close_date)  = &compute_open_window(\@open_dates, \@close_dates);
  749: 
  750:     return ($open_date, $close_date);
  751: }
  752: 
  753: ##
  754: # Get the dates for which a course says a resource can be printed.  This is like
  755: # get_print_dates but namvaps::course_print_dates are gotten...and not converted
  756: # to times either.
  757: #
  758: # @param $res - Reference to a resource hash from lonnavmaps::resource.
  759: #
  760: # @return (opendate, closedate)
  761: #
  762: sub course_print_dates {
  763:     my $res = shift;
  764:     my $partsref = $res->parts();
  765:     my @parts    = @$partsref;
  766:     my $open_date;
  767:     my $close_date;
  768:     my @open_dates;
  769:     my @close_dates;
  770:     my $navmap = $res->{NAV_MAP}; # Slightly OO dirty.
  771: 
  772:     # Don't bother looping over undefined or empty parts array;
  773: 
  774:     if (@parts) {
  775: 	foreach my $part (@parts) {
  776: 	    my ($partopen, $partclose) = $navmap->course_printdates($res, $part);
  777: 	    push(@open_dates, $partopen);
  778: 	    push(@close_dates, $partclose);
  779: 	}
  780: 	($open_date, $close_date) = &compute_open_window(\@open_dates, \@close_dates);
  781:     }
  782:     return ($open_date, $close_date);
  783: }
  784: ##
  785: # Same as above but for the enclosing map:
  786: #
  787: sub map_print_dates {
  788:     my $res = shift;
  789:     my $partsref = $res->parts();
  790:     my @parts    = @$partsref;
  791:     my $open_date;
  792:     my $close_date;
  793:     my @open_dates;
  794:     my @close_dates;
  795:     my $navmap = $res->{NAV_MAP}; # slightly OO dirty.
  796: 
  797: 
  798:     # Don't bother looping over undefined or empty parts array;
  799: 
  800:     if (@parts) {
  801: 	foreach my $part (@parts) {
  802: 	    my ($partopen, $partclose) = $navmap->map_printdates($res, $part);
  803: 	    push(@open_dates, $partopen);
  804: 	    push(@close_dates, $partclose);
  805: 	}
  806: 	($open_date, $close_date) = &compute_open_window(\@open_dates, \@close_dates);
  807:     }
  808:     return ($open_date, $close_date);
  809: }
  810: 
  811: # Determine if a resource is incomplete given the map:
  812: # Parameters:
  813: #   $username - Name of user for whom we are checking.
  814: #   $domain   - Domain of user we are checking.
  815: #   $section  - Section for user for whom we are checking.
  816: #   $map - map name.
  817: # Returns:
  818: #     0 - map is not incomplete.
  819: #     1 - map is incomplete.
  820: #
  821: sub incomplete {
  822:     my ($username, $domain, $section, $map) = @_;
  823: 
  824: 
  825:     my $navmap = Apache::lonnavmaps::navmap->new($username, $domain, $section);
  826: 
  827: 
  828:     if (defined($navmap)) {
  829: 	my $res = $navmap->getResourceByUrl($map);
  830: 	my $result = $res->is_incomplete();
  831: 	return $result;
  832:     } else {
  833: 	return 1;
  834:     }
  835: }
  836: #
  837: #  When printing for students, the resources and order of the
  838: #  resources may need to be altered if there are folders with
  839: #  random selectiopn or random ordering (or both) enabled.
  840: #  This sub computes the set of resources to print for a student
  841: #  modified both by random ordering and selection and filtered
  842: #  to only those that are in the original set selected to be printed.
  843: #
  844: # Parameters:
  845: #   $map - The URL of the folder being printed.
  846: #          Used to determine which startResource and finishResource
  847: #          to use when using the navmap's getIterator method.
  848: #   $seq   - The original set of resources to print.
  849: #            (really an array of resource names (array of symb's).
  850: #   $who   - Student/domain for whome the sequence will be generated.
  851: #   $code  - CODE being printed when printing Problems/Resources
  852: #            from folder for CODEd assignments
  853: #   $nohidemap - If true, parameter in map for hiddenresource will be
  854: #                ignored.  The user calling the routine should have
  855: #                both the pav and vgr privileges if this is set to true).
  856: #
  857: # Implicit inputs:
  858: #   $
  859: # Returns:
  860: #   reference to an array of resources that can be passed to
  861: #   print_resources.
  862: #
  863: sub master_seq_to_person_seq {
  864:     my ($map, $seq, $who, $code, $nohidemap) = @_;
  865: 
  866: 
  867:     my ($username, $userdomain, $usersection) = split(/:/, $who);
  868: 
  869:     # Toss the sequence up into a hash so that we have O(1) lookup time.
  870:     # on the items that come out of the user's list of resources.
  871:     #
  872: 
  873:     my %seq_hash = map {$_  => 1} @$seq;
  874:     my @output_seq;
  875: 
  876:     my $unhidden;
  877:     if ($nohidemap) {
  878:         $unhidden = &Apache::lonnet::clutter($map);
  879:     }
  880: 
  881:     my $navmap           = Apache::lonnavmaps::navmap->new($username, $userdomain,
  882:                                                            $usersection, $code, $unhidden);
  883:     my ($start,$finish);
  884: 
  885:     if ($map) {
  886:         my $mapres = $navmap->getResourceByUrl($map);
  887:         if ($mapres->is_map()) {
  888:             $start = $mapres->map_start();
  889:             $finish = $mapres->map_finish();
  890:         }
  891:     }
  892:     unless ($start && $finish) {
  893:         $start = $navmap->firstResource();
  894:         $finish = $navmap->finishResource();
  895:     }
  896: 
  897:     my $iterator         = $navmap->getIterator($start,$finish,{},1);
  898: 
  899:     #  Iterate on the resource..select the items that are randomly selected
  900:     #  and that are in the seq_hash.  Presumably the iterator will take care
  901:     #  of the random ordering part of the deal.
  902:     #
  903:     my $curres;
  904:     while ($curres = $iterator->next()) {
  905: 	#
  906: 	#  Only process resources..that are not removed by randomout...
  907: 	#  and are selected for printint as well.
  908: 	#
  909:         if (ref($curres) && ! $curres->randomout()) {
  910:             my $currsymb = $curres->symb();
  911:             if (exists($seq_hash{$currsymb})) {
  912:                 push(@output_seq, $currsymb);
  913: 	    }
  914: 	}
  915:     }
  916: 
  917:     return \@output_seq;		# for now.
  918: 
  919: }
  920: 
  921: 
  922: # Fetch the contents of a resource, uninterpreted.
  923: # This is used here to fetch a latex file to be included
  924: # verbatim into the printout<
  925: # NOTE: Ask Guy if there is a lonnet function similar to this?
  926: #
  927: # Parameters:
  928: #   URL of the file
  929: #
  930: sub fetch_raw_resource {
  931:     my ($url) = @_;
  932: 
  933:     my $filename  = &Apache::lonnet::filelocation("", $url);
  934:     my $contents  = &Apache::lonnet::getfile($filename);
  935: 
  936:     if ($contents == -1) {
  937: 	return "File open failed for $filename";      # This will bomb the print.
  938:     }
  939:     return $contents;
  940: 
  941: 
  942: }
  943: 
  944: #  Fetch the annotations associated with a URL and
  945: #  put a centered 'annotations:' title.
  946: #  This is all suppressed if the annotations are empty.
  947: #
  948: sub annotate {
  949:     my ($symb) = @_;
  950: 
  951:     my $annotation_text = &Apache::loncommon::get_annotation($symb, 1);
  952: 
  953: 
  954:     my $result = "";
  955: 
  956:     if (length($annotation_text) > 0) {
  957: 	$result .= '\\hspace*{\\fill} \\\\[\\baselineskip] \textbf{Annotations:} \\\\ ';
  958: 	$result .= "\n";
  959: 	$result .= &Apache::lonxml::latex_special_symbols($annotation_text,"");	# Escape latex.
  960: 	$result .= "\n\n";
  961:     }
  962:     return $result;
  963: }
  964: 
  965: #
  966: #   Set a global document font size:
  967: #   This is done by replacing \begin{document}
  968: #   with \begin{document}{\some-font-directive
  969: #   and \end{document} with
  970: #   }\end{document
  971: #
  972: sub set_font_size {
  973: 
  974:     my ($text) = @_;
  975: 
  976:     # There appear to be cases where the font directive is empty.. in which
  977:     # case the first substitution would insert a spurious \ oh happy day.
  978:     # as this has been the cause of much mystery and hair pulling _sigh_
  979: 
  980:     if ($font_size ne '') {
  981: 
  982: 	$text =~ s/\\begin\{document}/\\begin{document}{\\$font_size/;
  983:         $text =~ s/\\end\{document}/}\\end{document}/;
  984: 
  985:     }
  986:     return $text;
  987: 
  988: 
  989: }
  990: 
  991: # include_pdf - PDF files are included into the
  992: # output as follows:
  993: #  - The PDF, if necessary, is replicated.
  994: #  - The PDF is added to the list of files to convert to postscript (along with the images).
  995: #  - The LaTeX is added to include the final converted postscript in the file as an included
  996: #    job.  The assumption is that the includepsheader.ps header will be included.
  997: #
  998: # Parameters:
  999: #   pdf_uri   - URI of the PDF file to include.
 1000: #
 1001: # Returns:
 1002: #  The LaTeX to include.
 1003: #
 1004: # Assumptions:
 1005: #    The uri is actually a PDF file
 1006: #    The postscript will have the includepsheader.ps included.
 1007: #
 1008: #
 1009: sub include_pdf {
 1010:     my ($pdf_uri) = @_;
 1011: 
 1012:     # Where is the file? If not local we'll need to repcopy it:'
 1013: 
 1014:     my $file = &Apache::lonnet::filelocation('', $pdf_uri);
 1015:     if (! -e $file) {
 1016: 	&Apache::lonnet::repcopy($file);
 1017: 	$file = &Apache::lonnet::filelocation('',$pdf_uri);
 1018:     }
 1019: 
 1020:     #  The file is now replicated locally ... or it did not exist in the first place
 1021:     # (unlikely).  If it did exist, add the pdf to the set of files/images that
 1022:     # need to be converted for this print job:
 1023: 
 1024:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1025:     $file =~ s{(.*)/res/}{$londocroot/res/};
 1026: 
 1027:     open(FILE,">>","$Apache::lonnet::perlvar{'lonPrtDir'}/$env{'user.name'}_$env{'user.domain'}_printout.dat");
 1028:     print FILE ("$file\n");
 1029:     close (FILE);
 1030: 
 1031:     # Construct the special to put out.  To do this we need to get the
 1032:     # resulting filename after conversion.  The file will have the same name
 1033:     # but will be in the user's spool directory with converted images.
 1034: 
 1035:     my $dirname = "/home/httpd/prtspool/$env{'user.name'}/";
 1036:     my ( $base, $path,  $ext) = &fileparse($file, '.pdf');
 1037: #    my $destname = $dirname.'/'.$base.'.eps'; # Not really an eps but easier in printout.pl
 1038:     $base =~ s/ /\_/g;
 1039: 
 1040: 
 1041:     my $output = &print_latex_header();
 1042:     $output    .= '\special{ps: _begin_job_ ('
 1043: 	.$base.'.pdf.eps'.
 1044: 	')run _end_job_}';
 1045: 
 1046:     return $output;
 1047: 
 1048: 
 1049: }
 1050: ##
 1051: #  Collect the various \select_language{language_name}
 1052: #  latex tags to build a \usepackage[lang-list]{babel} which will
 1053: #  appear just prior to the \begin{document} at the front of the concatenated
 1054: #  set of resources:
 1055: # @param doc - The string of latex to search/replace.
 1056: # @return string
 1057: # @retval - the modified document stringt.
 1058: #
 1059: sub collect_languages {
 1060:     my $doc = shift;
 1061:     my %languages;
 1062:     while ($doc =~ /\\selectlanguage\{(\w+)}/mg) {
 1063: 	$languages{$1} = 1;	# allows us to request each language exactly once.
 1064:     }
 1065:     my @lang_list = (keys(%languages)); # List of unique languages
 1066:     if (scalar @lang_list) {
 1067: 	my $babel_header = '\usepackage[' . join(',', @lang_list) .']{babel}'. "\n";
 1068: 	$doc =~ s/\\begin\{document}/$babel_header\\begin{document}/;
 1069:     }
 1070:     return $doc;
 1071: }
 1072: #-------------------------------------------------------------------
 1073: 
 1074: #
 1075: #   ssi_with_retries- Does the server side include of a resource.
 1076: #                      if the ssi call returns an error we'll retry it up to
 1077: #                      the number of times requested by the caller.
 1078: #                      If we still have a proble, no text is appended to the
 1079: #                      output and we set some global variables.
 1080: #                      to indicate to the caller an SSI error occurred.
 1081: #                      All of this is supposed to deal with the issues described
 1082: #                      in LonCAPA BZ 5631 see:
 1083: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
 1084: #                      by informing the user that this happened.
 1085: #
 1086: # Parameters:
 1087: #   resource   - The resource to include.  This is passed directly, without
 1088: #                interpretation to lonnet::ssi.
 1089: #   form       - The form hash parameters that guide the interpretation of the resource
 1090: #
 1091: #   retries    - Number of retries allowed before giving up completely.
 1092: # Returns:
 1093: #   On success, returns the rendered resource identified by the resource parameter.
 1094: # Side Effects:
 1095: #   The following global variables can be set:
 1096: #    ssi_error                - If an unrecoverable error occurred this becomes true.
 1097: #                               It is up to the caller to initialize this to false
 1098: #                               if desired.
 1099: #    ssi_last_error_resource  - If an unrecoverable error occurred, this is the value
 1100: #                               of the resource that could not be rendered by the ssi
 1101: #                               call.
 1102: #    ssi_last_error           - The error string fetched from the ssi response
 1103: #                               in the event of an error.
 1104: #
 1105: sub ssi_with_retries {
 1106:     my ($resource, $retries, %form) = @_;
 1107: 
 1108:     my $target = $form{'grade_target'};
 1109:     my $aom    = $form{'answer_output_mode'};
 1110: 
 1111: 
 1112: 
 1113:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
 1114:     if (!$response->is_success) {
 1115: 	$ssi_error               = 1;
 1116: 	$ssi_last_error_resource = $resource;
 1117: 	$ssi_last_error          = $response->code . " " . $response->message;
 1118:         $content='\section*{!!! An error occurred !!!}';	
 1119:     }
 1120: 
 1121:     return $content;
 1122: 
 1123: }
 1124: 
 1125: sub get_student_view_with_retries {
 1126:     my ($curresline,$retries,$username,$userdomain,$courseid,$target,$moreenv)=@_;
 1127: 
 1128:     my ($content, $response) = &Apache::loncommon::get_student_view_with_retries($curresline,$retries,$username,$userdomain,$courseid,$target,$moreenv);
 1129:     if (!$response->is_success) {
 1130:         $ssi_error               = 1;
 1131:         $ssi_last_error_resource = $curresline.' for user '.$username.':'.$userdomain;
 1132:         $ssi_last_error          = $response->code . " " . $response->message;
 1133:         $content='\section*{!!! An error occurred !!!}';
 1134:     }
 1135:     return $content;
 1136: 
 1137: }
 1138: 
 1139: #
 1140: #   printf_style_subst  item format_string repl
 1141: #
 1142: # Does printf style substitution for a format string that
 1143: # can have %[n]item in it.. wherever, %[n]item occurs,
 1144: # rep is substituted in format_string.  Note that
 1145: # [n] is an optional integer length.  If provided,
 1146: # repl is truncated to at most [n] characters prior to
 1147: # substitution.
 1148: #
 1149: sub printf_style_subst {
 1150:     my ($item, $format_string, $repl) = @_;
 1151:     my $result = "";
 1152:     while ($format_string =~ /(%)(\d*)\Q$item\E/g ) {
 1153: 	my $fmt = $1;
 1154: 	my $size = $2;
 1155: 	my $subst = $repl;
 1156: 	if ($size ne "") {
 1157: 	    $subst = substr($subst, 0, $size);
 1158: 
 1159: 	    #  Here's a nice edge case ... suppose the end of the
 1160: 	    #  substring is a \.  In that case may have just
 1161: 	    #  chopped off a TeX escape... in that case, we append
 1162: 	    #   " " for the trailing character, and let the field
 1163: 	    #  spill over a bit (sigh).
 1164: 	    #  We don't just chop off the last character in order to deal
 1165: 	    #  with one last pathology, and that would be if substr had
 1166: 	    #  trimmed us to e.g. \\\
 1167: 
 1168: 
 1169: 	    if ($subst =~ /\\$/) {
 1170: 		$subst .= " ";
 1171: 	    }
 1172: 	}
 1173: 	my $item_pos = pos($format_string);
 1174: 	$result .= substr($format_string, 0, $item_pos - length($size) -2) . $subst;
 1175:         $format_string = substr($format_string, pos($format_string));
 1176:     }
 1177: 
 1178:     # Put the residual format string into the result:
 1179: 
 1180:     $result .= $format_string;
 1181: 
 1182:     return $result;
 1183: }
 1184: 
 1185: 
 1186: # Format a header according to a format.
 1187: #
 1188: 
 1189: # Substitutions:
 1190: #     %a    - Assignment name.
 1191: #     %c    - Course name.
 1192: #     %n    - Student name.
 1193: #     %s    - The section if it is supplied.
 1194: #
 1195: sub format_page_header {
 1196:     my ($width, $format, $assignment, $course, $student, $section) = @_;
 1197: 
 1198: 
 1199: 
 1200:     $width = &recalcto_mm($width); # Get width in mm.
 1201:     my $chars_per_line = int($width/1.6);   # Character/textline.
 1202: 
 1203:     #  Default format?
 1204: 
 1205:     if ($format eq '') {
 1206: 	# For the default format, we may need to truncate
 1207: 	# elements..  To do this we need to get the page width.
 1208: 	# we assume that each character is about 2mm in width.
 1209: 	# (correct for the header text size??).  We ignore
 1210: 	# any formatting (e.g. boldfacing in this).
 1211: 	#
 1212: 	# - Allow the student/course to be one line.
 1213: 	#   but only truncate the course.
 1214: 	# - Allow the assignment to be 2 lines (wrapped).
 1215: 	#
 1216: 
 1217: 	
 1218: 
 1219: 	my $name_length    = int($chars_per_line *3 /4);
 1220: 	my $sec_length     = int($chars_per_line / 5);
 1221: 
 1222: 	$format  = "%$name_length".'n';
 1223: 
 1224: 	if ($section) {
 1225: 	    $format .=  ' - Sec: '."%$sec_length".'s';
 1226: 	}
 1227: 	$format .= '\\hfill\\thepage';
 1228: 
 1229: 	$format .= '\\\\%c \\\\ %a';
 1230: 
 1231: 
 1232:     }
 1233:     # An open question is how to handle long user formatted page headers...
 1234:     # A possible future is to support e.g. %na so that the user can control
 1235:     # the truncation of the elements that can appear in the header.
 1236:     #
 1237:     $format =  &printf_style_subst("a", $format, $assignment);
 1238:     $format =  &printf_style_subst("c", $format, $course);
 1239:     $format =  &printf_style_subst("n", $format, $student);
 1240:     $format =  &printf_style_subst("s", $format, $section);
 1241: 
 1242: 
 1243:     # If the user put %'s in the format string, they  must be escaped
 1244:     # to \% else LaTeX will think they are comments and terminate
 1245:     # the line.. which is bad!!!
 1246: 
 1247:     # If the user has role author, $course and $assignment are empty so
 1248:     # there is '\\ \\ ' in the page header. That's cause a error in LaTeX
 1249:     if($format =~ /\\\\\s\\\\\s/) {
 1250:         #TODO find sensible caption for page header
 1251:         my $testPrintout = '\\\\'.&mt('Authoring Space').' \\\\'.&mt('Test-Printout ');
 1252:         $format =~ s/\\\\\s\\\\\s/$testPrintout/;
 1253:     }
 1254:     #
 1255:     #  We're going to trust LaTeX to break lines appropriately, but
 1256:     #  we'll truncate anything that's more than 3 lines worth of
 1257:     # text.  This is also assuming (which will probably end badly)
 1258:     # nobody's going to embed LaTeX control sequences in the title
 1259:     # header or rather that those control sequences won't get broken
 1260:     # by the stuff below.
 1261:     #
 1262:     my $total_length = 3*$chars_per_line;
 1263:     if (length($format) > $total_length) {
 1264: 	$format = substr($format, 0, $total_length);
 1265:     }
 1266: 
 1267: 
 1268:     return $format;
 1269: 
 1270: }
 1271: 
 1272: #
 1273: #   Convert a numeric code to letters
 1274: #
 1275: sub num_to_letters {
 1276:     my ($num) = @_;
 1277:     my @nums= split('',$num);
 1278:     my @num_to_let=('A'..'Z');
 1279:     my $word;
 1280:     foreach my $digit (@nums) { $word.=$num_to_let[$digit]; }
 1281:     return $word;
 1282: }
 1283: #   Convert a letter code to numeric.
 1284: #
 1285: sub letters_to_num {
 1286:     my ($letters) = @_;
 1287:     my @letters = split('', uc($letters));
 1288:    my %substitution;
 1289:     my $digit = 0;
 1290:     foreach my $letter ('A'..'J') {
 1291: 	$substitution{$letter} = $digit;
 1292: 	$digit++;
 1293:     }
 1294:     #  The substitution is done as below to preserve leading
 1295:     #  zeroes which are needed to keep the code size exact
 1296:     #
 1297:     my $result ="";
 1298:     foreach my $letter (@letters) {
 1299: 	$result.=$substitution{$letter};
 1300:     }
 1301:     return $result;
 1302: }
 1303: 
 1304: #  Determine if a code is a valid numeric code.  Valid
 1305: #  numeric codes must be comprised entirely of digits and
 1306: #  have a correct number of digits.
 1307: #
 1308: #  Parameters:
 1309: #     value      - proposed code value.
 1310: #     num_digits - Number of digits required.
 1311: #
 1312: sub is_valid_numeric_code {
 1313:     my ($value, $num_digits) = @_;
 1314:     #   Remove leading/trailing whitespace;
 1315:     $value =~ s/^\s*//g;
 1316:     $value =~ s/\s*$//g;
 1317: 
 1318:     #  All digits?
 1319:     if ($value !~ /^[0-9]+$/) {
 1320: 	return "Numeric code $value has invalid characters - must only be digits";
 1321:     }
 1322:     if (length($value) != $num_digits) {
 1323: 	return "Numeric code $value incorrect number of digits (correct = $num_digits)";
 1324:     }
 1325:     return undef;
 1326: }
 1327: #   Determines if a code is a valid alhpa code.  Alpha codes
 1328: #   are ciphers that map  [A-J,a-j] -> 0..9 0..9.
 1329: #   They also have a correct digit count.
 1330: # Parameters:
 1331: #     value          - Proposed code value.
 1332: #     num_letters    - correct number of letters.
 1333: # Note:
 1334: #    leading and trailing whitespace are ignored.
 1335: #
 1336: sub is_valid_alpha_code {
 1337:     my ($value, $num_letters) = @_;
 1338: 
 1339:      # strip leading and trailing spaces.
 1340: 
 1341:     $value =~ s/^\s*//g;
 1342:     $value =~ s/\s*$//g;
 1343: 
 1344:     #  All alphas in the right range?
 1345:     if ($value !~ /^[A-J,a-j]+$/) {
 1346: 	return "Invalid letter code $value must only contain A-J";
 1347:     }
 1348:     if (length($value) != $num_letters) {
 1349: 	return "Letter code $value has incorrect number of letters (correct = $num_letters)";
 1350:     }
 1351:     return undef;
 1352: }
 1353: 
 1354: #   Determine if a code entered by the user in a helper is valid.
 1355: #   valid depends on the code type and the type of code selected.
 1356: #   The type of code selected can either be numeric or
 1357: #   Alphabetic.  If alphabetic, the code, in fact is a simple
 1358: #   substitution cipher for the actual numeric code: 0->A, 1->B ...
 1359: #   We'll be nice and be case insensitive for alpha codes.
 1360: # Parameters:
 1361: #    code_value    - the value of the code the user typed in.
 1362: #    code_option   - The code type selected from the set in the scantron format
 1363: #                    table.
 1364: # Returns:
 1365: #    undef         - The code is valid.
 1366: #    other         - An error message indicating what's wrong.
 1367: #
 1368: sub is_code_valid {
 1369:     my ($code_value, $code_option) = @_;
 1370:     my ($code_type, $code_length) = ('letter', 6);	# defaults.
 1371:     my @lines = &Apache::lonnet::get_scantronformat_file();
 1372:     foreach my $line (@lines) {
 1373:         next if (($line =~ /^\#/) || ($line eq ''));
 1374: 	my ($name, $type, $length) = (split(/:/, $line))[0,2,4];
 1375: 	if($name eq $code_option) {
 1376: 	    $code_length = $length;
 1377: 	    if($type eq 'number') {
 1378: 		$code_type = 'number';
 1379: 	    }
 1380: 	}
 1381:     }
 1382:     my $valid;
 1383:     if ($code_type eq 'number') {
 1384: 	return &is_valid_numeric_code($code_value, $code_length);
 1385:     } else {
 1386: 	return &is_valid_alpha_code($code_value, $code_length);
 1387:     }
 1388: 
 1389: }
 1390: #
 1391: # Compare two students by section (Used to sort by section).
 1392: #
 1393: #  Implicit inputs,
 1394: #    $a - The first one
 1395: #    $b - The second one.
 1396: #
 1397: #  Returns:
 1398: #     a-section cmp b-section
 1399: #
 1400: sub compare_sections {
 1401:     my ($u1, $d1, $s1, $n1, $stat1) = split(/:/, $a);
 1402:     my ($u2, $d2, $s2, $n2, $stat2) = split(/:/, $b);
 1403: 
 1404:     return $s1 cmp $s2;
 1405: }
 1406: 
 1407: #   Compare two students by name.  The students are in the form
 1408: #   returned by the helper:
 1409: #      user:domain:section:last,   first:status
 1410: #   This is a helper function for the perl sort built-in  therefore:
 1411: # Implicit Inputs:
 1412: #    $a     - The first element to compare (global)
 1413: #    $b     - The second element to compare (global)
 1414: # Returns:
 1415: #   -1   - $a < $b
 1416: #    0   - $a == $b
 1417: #   +1   - $a > $b
 1418: #   Note that the initial comparison is done on the last names with the
 1419: #   first names only used to break the tie.
 1420: #
 1421: #
 1422: sub compare_names {
 1423:     #  First split the names up into the primary fields.
 1424: 
 1425:     my ($u1, $d1, $s1, $n1, $stat1) = split(/:/, $a);
 1426:     my ($u2, $d2, $s2, $n2, $stat2) = split(/:/, $b);
 1427: 
 1428:     # Now split the last name and first name of each n:
 1429:     #
 1430: 
 1431:     my ($l1,$f1) = split(/,/, $n1);
 1432:     my ($l2,$f2) = split(/,/, $n2);
 1433: 
 1434:     # We don't bother to remove the leading/trailing whitespace from the
 1435:     # firstname, unless the last names compare identical.
 1436: 
 1437:     if($l1 lt $l2) {
 1438: 	return -1;
 1439:     }
 1440:     if($l1 gt $l2) {
 1441: 	return  1;
 1442:     }
 1443: 
 1444:     # Break the tie on the first name, but there are leading (possibly trailing
 1445:     # whitespaces to get rid of first)
 1446:     #
 1447:     $f1 =~ s/^\s+//;		# Remove leading...
 1448:     $f1 =~ s/\s+$//;		# Trailing spaces from first 1...
 1449: 
 1450:     $f2 =~ s/^\s+//;
 1451:     $f2 =~ s/\s+$//;		# And the same for first 2...
 1452: 
 1453:     if($f1 lt $f2) {
 1454: 	return -1;
 1455:     }
 1456:     if($f1 gt $f2) {
 1457: 	return 1;
 1458:     }
 1459: 
 1460:     #  Must be the same name.
 1461: 
 1462:     return 0;
 1463: }
 1464: 
 1465: sub latex_header_footer_remove {
 1466:     my $text = shift;
 1467:     $text =~ s/\\end\{document}//;
 1468:     $text =~ s/\\documentclass([^&]*)\\begin\{document}//;
 1469:     return $text;
 1470: }
 1471: #
 1472: #  If necessary, encapsulate text inside
 1473: #  a minipage env.
 1474: #  necessity is determined by the problem_split param.
 1475: #
 1476: sub encapsulate_minipage {
 1477:     my ($text,$problem_split) = @_;
 1478:     if (!($problem_split =~ /yes/i)) {
 1479: 	$text = '\begin{minipage}{\textwidth}'.$text.'\end{minipage}';
 1480:     }
 1481:     return $text;
 1482: }
 1483: #
 1484: #  The NUMBER_TO_PRINT and SPLIT_PDFS
 1485: #  variables interact, this sub looks at these two parameters
 1486: #  and comes up with a final value for NUMBER_TO_PRINT which can be:
 1487: #     all     - if SPLIT_PDFS eq 'all'.
 1488: #     1       - if SPLIT_PDFS eq 'oneper'
 1489: #     section - if SPLIT_PDFS eq 'sections'
 1490: #     <unchanged> - if SPLIT_PDFS eq 'usenumber'
 1491: #
 1492: sub adjust_number_to_print {
 1493:     my $helper = shift;
 1494: 
 1495:     my $split_pdf = $helper->{'VARS'}->{'SPLIT_PDFS'};
 1496: 
 1497:     if ($split_pdf eq 'all') {
 1498: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 'all';
 1499:     } elsif ($split_pdf eq 'oneper') {
 1500: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 1;
 1501:     } elsif ($split_pdf eq 'sections') {
 1502: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 'section';
 1503:     } elsif ($split_pdf eq 'usenumber') {
 1504: 	#  Unmodified.
 1505:     } else {
 1506: 	# Error!!!!
 1507: 	
 1508: 	croak "bad SPLIT_PDFS: $split_pdf in lonprintout::adjust_number_to_print";
 1509: 
 1510:     }
 1511: }
 1512: 
 1513: 
 1514: sub character_chart {
 1515:     my $result = shift;
 1516:     return  &Apache::entities::replace_entities($result);
 1517: }
 1518: 
 1519: sub old_character_chart {
 1520:     my $result = shift;	
 1521:     $result =~ s/&\#0?0?(7|9);//g;
 1522:     $result =~ s/&\#0?(10|13);//g;
 1523:     $result =~ s/&\#0?32;/ /g;
 1524:     $result =~ s/&\#0?33;/!/g;
 1525:     $result =~ s/&(\#0?34|quot);/\"/g;
 1526:     $result =~ s/&\#0?35;/\\\#/g;
 1527:     $result =~ s/&\#0?36;/\\\$/g;
 1528:     $result =~ s/&\#0?37;/\\%/g;
 1529:     $result =~ s/&(\#0?38|amp);/\\&/g;
 1530:     $result =~ s/&\#(0?39|146);/\'/g;
 1531:     $result =~ s/&\#0?40;/(/g;
 1532:     $result =~ s/&\#0?41;/)/g;
 1533:     $result =~ s/&\#0?42;/\*/g;
 1534:     $result =~ s/&\#0?43;/\+/g;
 1535:     $result =~ s/&\#(0?44|130);/,/g;
 1536:     $result =~ s/&\#0?45;/-/g;
 1537:     $result =~ s/&\#0?46;/\./g;
 1538:     $result =~ s/&\#0?47;/\//g;
 1539:     $result =~ s/&\#0?48;/0/g;
 1540:     $result =~ s/&\#0?49;/1/g;
 1541:     $result =~ s/&\#0?50;/2/g;
 1542:     $result =~ s/&\#0?51;/3/g;
 1543:     $result =~ s/&\#0?52;/4/g;
 1544:     $result =~ s/&\#0?53;/5/g;
 1545:     $result =~ s/&\#0?54;/6/g;
 1546:     $result =~ s/&\#0?55;/7/g;
 1547:     $result =~ s/&\#0?56;/8/g;
 1548:     $result =~ s/&\#0?57;/9/g;
 1549:     $result =~ s/&\#0?58;/:/g;
 1550:     $result =~ s/&\#0?59;/;/g;
 1551:     $result =~ s/&(\#0?60|lt|\#139);/\$<\$/g;
 1552:     $result =~ s/&\#0?61;/\\ensuremath\{=\}/g;
 1553:     $result =~ s/&(\#0?62|gt|\#155);/\\ensuremath\{>\}/g;
 1554:     $result =~ s/&\#0?63;/\?/g;
 1555:     $result =~ s/&\#0?65;/A/g;
 1556:     $result =~ s/&\#0?66;/B/g;
 1557:     $result =~ s/&\#0?67;/C/g;
 1558:     $result =~ s/&\#0?68;/D/g;
 1559:     $result =~ s/&\#0?69;/E/g;
 1560:     $result =~ s/&\#0?70;/F/g;
 1561:     $result =~ s/&\#0?71;/G/g;
 1562:     $result =~ s/&\#0?72;/H/g;
 1563:     $result =~ s/&\#0?73;/I/g;
 1564:     $result =~ s/&\#0?74;/J/g;
 1565:     $result =~ s/&\#0?75;/K/g;
 1566:     $result =~ s/&\#0?76;/L/g;
 1567:     $result =~ s/&\#0?77;/M/g;
 1568:     $result =~ s/&\#0?78;/N/g;
 1569:     $result =~ s/&\#0?79;/O/g;
 1570:     $result =~ s/&\#0?80;/P/g;
 1571:     $result =~ s/&\#0?81;/Q/g;
 1572:     $result =~ s/&\#0?82;/R/g;
 1573:     $result =~ s/&\#0?83;/S/g;
 1574:     $result =~ s/&\#0?84;/T/g;
 1575:     $result =~ s/&\#0?85;/U/g;
 1576:     $result =~ s/&\#0?86;/V/g;
 1577:     $result =~ s/&\#0?87;/W/g;
 1578:     $result =~ s/&\#0?88;/X/g;
 1579:     $result =~ s/&\#0?89;/Y/g;
 1580:     $result =~ s/&\#0?90;/Z/g;
 1581:     $result =~ s/&\#0?91;/[/g;
 1582:     $result =~ s/&\#0?92;/\\ensuremath\{\\setminus\}/g;
 1583:     $result =~ s/&\#0?93;/]/g;
 1584:     $result =~ s/&\#(0?94|136);/\\ensuremath\{\\wedge\}/g;
 1585:     $result =~ s/&\#(0?95|138|154);/\\underline{\\makebox[2mm]{\\strut}}/g;
 1586:     $result =~ s/&\#(0?96|145);/\`/g;
 1587:     $result =~ s/&\#0?97;/a/g;
 1588:     $result =~ s/&\#0?98;/b/g;
 1589:     $result =~ s/&\#0?99;/c/g;
 1590:     $result =~ s/&\#100;/d/g;
 1591:     $result =~ s/&\#101;/e/g;
 1592:     $result =~ s/&\#102;/f/g;
 1593:     $result =~ s/&\#103;/g/g;
 1594:     $result =~ s/&\#104;/h/g;
 1595:     $result =~ s/&\#105;/i/g;
 1596:     $result =~ s/&\#106;/j/g;
 1597:     $result =~ s/&\#107;/k/g;
 1598:     $result =~ s/&\#108;/l/g;
 1599:     $result =~ s/&\#109;/m/g;
 1600:     $result =~ s/&\#110;/n/g;
 1601:     $result =~ s/&\#111;/o/g;
 1602:     $result =~ s/&\#112;/p/g;
 1603:     $result =~ s/&\#113;/q/g;
 1604:     $result =~ s/&\#114;/r/g;
 1605:     $result =~ s/&\#115;/s/g;
 1606:     $result =~ s/&\#116;/t/g;
 1607:     $result =~ s/&\#117;/u/g;
 1608:     $result =~ s/&\#118;/v/g;
 1609:     $result =~ s/&\#119;/w/g;
 1610:     $result =~ s/&\#120;/x/g;
 1611:     $result =~ s/&\#121;/y/g;
 1612:     $result =~ s/&\#122;/z/g;
 1613:     $result =~ s/&\#123;/\\{/g;
 1614:     $result =~ s/&\#124;/\|/g;
 1615:     $result =~ s/&\#125;/\\}/g;
 1616:     $result =~ s/&\#126;/\~/g;
 1617:     $result =~ s/&\#131;/\\textflorin /g;
 1618:     $result =~ s/&\#132;/\"/g;
 1619:     $result =~ s/&\#133;/\\ensuremath\{\\ldots\}/g;
 1620:     $result =~ s/&\#134;/\\ensuremath\{\\dagger\}/g;
 1621:     $result =~ s/&\#135;/\\ensuremath\{\\ddagger\}/g;
 1622:     $result =~ s/&\#137;/\\textperthousand /g;
 1623:     $result =~ s/&\#140;/{\\OE}/g;
 1624:     $result =~ s/&\#147;/\`\`/g;
 1625:     $result =~ s/&\#148;/\'\'/g;
 1626:     $result =~ s/&\#149;/\\ensuremath\{\\bullet\}/g;
 1627:     $result =~ s/&(\#150|\#8211);/--/g;
 1628:     $result =~ s/&\#151;/---/g;
 1629:     $result =~ s/&\#152;/\\ensuremath\{\\sim\}/g;
 1630:     $result =~ s/&\#153;/\\texttrademark /g;
 1631:     $result =~ s/&\#156;/\\oe/g;
 1632:     $result =~ s/&\#159;/\\\"Y/g;
 1633:     $result =~ s/&(\#160|nbsp);/~/g;
 1634:     $result =~ s/&(\#161|iexcl);/!\`/g;
 1635:     $result =~ s/&(\#162|cent);/\\textcent /g;
 1636:     $result =~ s/&(\#163|pound);/\\pounds /g;
 1637:     $result =~ s/&(\#164|curren);/\\textcurrency /g;
 1638:     $result =~ s/&(\#165|yen);/\\textyen /g;
 1639:     $result =~ s/&(\#166|brvbar);/\\textbrokenbar /g;
 1640:     $result =~ s/&(\#167|sect);/\\textsection /g;
 1641:     $result =~ s/&(\#168|uml);/\\"\{\} /g;
 1642:     $result =~ s/&(\#169|copy);/\\copyright /g;
 1643:     $result =~ s/&(\#170|ordf);/\\textordfeminine /g;
 1644:     $result =~ s/&(\#172|not);/\\ensuremath\{\\neg\}/g;
 1645:     $result =~ s/&(\#173|shy);/ - /g;
 1646:     $result =~ s/&(\#174|reg);/\\textregistered /g;
 1647:     $result =~ s/&(\#175|macr);/\\ensuremath\{^{-}\}/g;
 1648:     $result =~ s/&(\#176|deg);/\\ensuremath\{^{\\circ}\}/g;
 1649:     $result =~ s/&(\#177|plusmn);/\\ensuremath\{\\pm\}/g;
 1650:     $result =~ s/&(\#178|sup2);/\\ensuremath\{^2\}/g;
 1651:     $result =~ s/&(\#179|sup3);/\\ensuremath\{^3\}/g;
 1652:     $result =~ s/&(\#180|acute);/\\'\{\} /g;
 1653:     $result =~ s/&(\#181|micro);/\\ensuremath\{\\mu\}/g;
 1654:     $result =~ s/&(\#182|para);/\\P/g;
 1655:     $result =~ s/&(\#183|middot);/\\ensuremath\{\\cdot\}/g;
 1656:     $result =~ s/&(\#184|cedil);/\\c{\\strut}/g;
 1657:     $result =~ s/&(\#185|sup1);/\\ensuremath\{^1\}/g;
 1658:     $result =~ s/&(\#186|ordm);/\\textordmasculine /g;
 1659:     $result =~ s/&(\#188|frac14);/\\textonequarter /g;
 1660:     $result =~ s/&(\#189|frac12);/\\textonehalf /g;
 1661:     $result =~ s/&(\#190|frac34);/\\textthreequarters /g;
 1662:     $result =~ s/&(\#191|iquest);/?\`/g;
 1663:     $result =~ s/&(\#192|Agrave);/\\\`{A}/g;
 1664:     $result =~ s/&(\#193|Aacute);/\\\'{A}/g;
 1665:     $result =~ s/&(\#194|Acirc);/\\^{A}/g;
 1666:     $result =~ s/&(\#195|Atilde);/\\~{A}/g;
 1667:     $result =~ s/&(\#196|Auml);/\\\"{A}/g;
 1668:     $result =~ s/&(\#197|Aring);/{\\AA}/g;
 1669:     $result =~ s/&(\#198|AElig);/{\\AE}/g;
 1670:     $result =~ s/&(\#199|Ccedil);/\\c{c}/g;
 1671:     $result =~ s/&(\#200|Egrave);/\\\`{E}/g;
 1672:     $result =~ s/&(\#201|Eacute);/\\\'{E}/g;
 1673:     $result =~ s/&(\#202|Ecirc);/\\^{E}/g;
 1674:     $result =~ s/&(\#203|Euml);/\\\"{E}/g;
 1675:     $result =~ s/&(\#204|Igrave);/\\\`{I}/g;
 1676:     $result =~ s/&(\#205|Iacute);/\\\'{I}/g;
 1677:     $result =~ s/&(\#206|Icirc);/\\^{I}/g;
 1678:     $result =~ s/&(\#207|Iuml);/\\\"{I}/g;
 1679:     $result =~ s/&(\#209|Ntilde);/\\~{N}/g;
 1680:     $result =~ s/&(\#210|Ograve);/\\\`{O}/g;
 1681:     $result =~ s/&(\#211|Oacute);/\\\'{O}/g;
 1682:     $result =~ s/&(\#212|Ocirc);/\\^{O}/g;
 1683:     $result =~ s/&(\#213|Otilde);/\\~{O}/g;
 1684:     $result =~ s/&(\#214|Ouml);/\\\"{O}/g;
 1685:     $result =~ s/&(\#215|times);/\\ensuremath\{\\times\}/g;
 1686:     $result =~ s/&(\#216|Oslash);/{\\O}/g;
 1687:     $result =~ s/&(\#217|Ugrave);/\\\`{U}/g;
 1688:     $result =~ s/&(\#218|Uacute);/\\\'{U}/g;
 1689:     $result =~ s/&(\#219|Ucirc);/\\^{U}/g;
 1690:     $result =~ s/&(\#220|Uuml);/\\\"{U}/g;
 1691:     $result =~ s/&(\#221|Yacute);/\\\'{Y}/g;
 1692:     $result =~ s/&(\#223|szlig);/{\\ss}/g;
 1693:     $result =~ s/&(\#224|agrave);/\\\`{a}/g;
 1694:     $result =~ s/&(\#225|aacute);/\\\'{a}/g;
 1695:     $result =~ s/&(\#226|acirc);/\\^{a}/g;
 1696:     $result =~ s/&(\#227|atilde);/\\~{a}/g;
 1697:     $result =~ s/&(\#228|auml);/\\\"{a}/g;
 1698:     $result =~ s/&(\#229|aring);/{\\aa}/g;
 1699:     $result =~ s/&(\#230|aelig);/{\\ae}/g;
 1700:     $result =~ s/&(\#231|ccedil);/\\c{c}/g;
 1701:     $result =~ s/&(\#232|egrave);/\\\`{e}/g;
 1702:     $result =~ s/&(\#233|eacute);/\\\'{e}/g;
 1703:     $result =~ s/&(\#234|ecirc);/\\^{e}/g;
 1704:     $result =~ s/&(\#235|euml);/\\\"{e}/g;
 1705:     $result =~ s/&(\#236|igrave);/\\\`{i}/g;
 1706:     $result =~ s/&(\#237|iacute);/\\\'{i}/g;
 1707:     $result =~ s/&(\#238|icirc);/\\^{i}/g;
 1708:     $result =~ s/&(\#239|iuml);/\\\"{i}/g;
 1709:     $result =~ s/&(\#240|eth);/\\ensuremath\{\\partial\}/g;
 1710:     $result =~ s/&(\#241|ntilde);/\\~{n}/g;
 1711:     $result =~ s/&(\#242|ograve);/\\\`{o}/g;
 1712:     $result =~ s/&(\#243|oacute);/\\\'{o}/g;
 1713:     $result =~ s/&(\#244|ocirc);/\\^{o}/g;
 1714:     $result =~ s/&(\#245|otilde);/\\~{o}/g;
 1715:     $result =~ s/&(\#246|ouml);/\\\"{o}/g;
 1716:     $result =~ s/&(\#247|divide);/\\ensuremath\{\\div\}/g;
 1717:     $result =~ s/&(\#248|oslash);/{\\o}/g;
 1718:     $result =~ s/&(\#249|ugrave);/\\\`{u}/g;
 1719:     $result =~ s/&(\#250|uacute);/\\\'{u}/g;
 1720:     $result =~ s/&(\#251|ucirc);/\\^{u}/g;
 1721:     $result =~ s/&(\#252|uuml);/\\\"{u}/g;
 1722:     $result =~ s/&(\#253|yacute);/\\\'{y}/g;
 1723:     $result =~ s/&(\#255|yuml);/\\\"{y}/g;
 1724:     $result =~ s/&\#295;/\\ensuremath\{\\hbar\}/g;
 1725:     $result =~ s/&\#952;/\\ensuremath\{\\theta\}/g;
 1726: #Greek Alphabet
 1727:     $result =~ s/&(alpha|\#945);/\\ensuremath\{\\alpha\}/g;
 1728:     $result =~ s/&(beta|\#946);/\\ensuremath\{\\beta\}/g;
 1729:     $result =~ s/&(gamma|\#947);/\\ensuremath\{\\gamma\}/g;
 1730:     $result =~ s/&(delta|\#948);/\\ensuremath\{\\delta\}/g;
 1731:     $result =~ s/&(epsilon|\#949);/\\ensuremath\{\\epsilon\}/g;
 1732:     $result =~ s/&(zeta|\#950);/\\ensuremath\{\\zeta\}/g;
 1733:     $result =~ s/&(eta|\#951);/\\ensuremath\{\\eta\}/g;
 1734:     $result =~ s/&(theta|\#952);/\\ensuremath\{\\theta\}/g;
 1735:     $result =~ s/&(iota|\#953);/\\ensuremath\{\\iota\}/g;
 1736:     $result =~ s/&(kappa|\#954);/\\ensuremath\{\\kappa\}/g;
 1737:     $result =~ s/&(lambda|\#955);/\\ensuremath\{\\lambda\}/g;
 1738:     $result =~ s/&(mu|\#956);/\\ensuremath\{\\mu\}/g;
 1739:     $result =~ s/&(nu|\#957);/\\ensuremath\{\\nu\}/g;
 1740:     $result =~ s/&(xi|\#958);/\\ensuremath\{\\xi\}/g;
 1741:     $result =~ s/&(omicron|\#959);/o/g;
 1742:     $result =~ s/&(pi|\#960);/\\ensuremath\{\\pi\}/g;
 1743:     $result =~ s/&(rho|\#961);/\\ensuremath\{\\rho\}/g;
 1744:     $result =~ s/&(sigma|\#963);/\\ensuremath\{\\sigma\}/g;
 1745:     $result =~ s/&(tau|\#964);/\\ensuremath\{\\tau\}/g;
 1746:     $result =~ s/&(upsilon|\#965);/\\ensuremath\{\\upsilon\}/g;
 1747:     $result =~ s/&(phi|\#966);/\\ensuremath\{\\phi\}/g;
 1748:     $result =~ s/&(chi|\#967);/\\ensuremath\{\\chi\}/g;
 1749:     $result =~ s/&(psi|\#968);/\\ensuremath\{\\psi\}/g;
 1750:     $result =~ s/&(omega|\#969);/\\ensuremath\{\\omega\}/g;
 1751:     $result =~ s/&(thetasym|\#977);/\\ensuremath\{\\vartheta\}/g;
 1752:     $result =~ s/&(piv|\#982);/\\ensuremath\{\\varpi\}/g;
 1753:     $result =~ s/&(Alpha|\#913);/A/g;
 1754:     $result =~ s/&(Beta|\#914);/B/g;
 1755:     $result =~ s/&(Gamma|\#915);/\\ensuremath\{\\Gamma\}/g;
 1756:     $result =~ s/&(Delta|\#916);/\\ensuremath\{\\Delta\}/g;
 1757:     $result =~ s/&(Epsilon|\#917);/E/g;
 1758:     $result =~ s/&(Zeta|\#918);/Z/g;
 1759:     $result =~ s/&(Eta|\#919);/H/g;
 1760:     $result =~ s/&(Theta|\#920);/\\ensuremath\{\\Theta\}/g;
 1761:     $result =~ s/&(Iota|\#921);/I/g;
 1762:     $result =~ s/&(Kappa|\#922);/K/g;
 1763:     $result =~ s/&(Lambda|\#923);/\\ensuremath\{\\Lambda\}/g;
 1764:     $result =~ s/&(Mu|\#924);/M/g;
 1765:     $result =~ s/&(Nu|\#925);/N/g;
 1766:     $result =~ s/&(Xi|\#926);/\\ensuremath\{\\Xi\}/g;
 1767:     $result =~ s/&(Omicron|\#927);/O/g;
 1768:     $result =~ s/&(Pi|\#928);/\\ensuremath\{\\Pi\}/g;
 1769:     $result =~ s/&(Rho|\#929);/P/g;
 1770:     $result =~ s/&(Sigma|\#931);/\\ensuremath\{\\Sigma\}/g;
 1771:     $result =~ s/&(Tau|\#932);/T/g;
 1772:     $result =~ s/&(Upsilon|\#933);/\\ensuremath\{\\Upsilon\}/g;
 1773:     $result =~ s/&(Phi|\#934);/\\ensuremath\{\\Phi\}/g;
 1774:     $result =~ s/&(Chi|\#935);/X/g;
 1775:     $result =~ s/&(Psi|\#936);/\\ensuremath\{\\Psi\}/g;
 1776:     $result =~ s/&(Omega|\#937);/\\ensuremath\{\\Omega\}/g;
 1777: #Arrows (extended HTML 4.01)
 1778:     $result =~ s/&(larr|\#8592);/\\ensuremath\{\\leftarrow\}/g;
 1779:     $result =~ s/&(uarr|\#8593);/\\ensuremath\{\\uparrow\}/g;
 1780:     $result =~ s/&(rarr|\#8594);/\\ensuremath\{\\rightarrow\}/g;
 1781:     $result =~ s/&(darr|\#8595);/\\ensuremath\{\\downarrow\}/g;
 1782:     $result =~ s/&(harr|\#8596);/\\ensuremath\{\\leftrightarrow\}/g;
 1783:     $result =~ s/&(lArr|\#8656);/\\ensuremath\{\\Leftarrow\}/g;
 1784:     $result =~ s/&(uArr|\#8657);/\\ensuremath\{\\Uparrow\}/g;
 1785:     $result =~ s/&(rArr|\#8658);/\\ensuremath\{\\Rightarrow\}/g;
 1786:     $result =~ s/&(dArr|\#8659);/\\ensuremath\{\\Downarrow\}/g;
 1787:     $result =~ s/&(hArr|\#8660);/\\ensuremath\{\\Leftrightarrow\}/g;
 1788: #Mathematical Operators (extended HTML 4.01)
 1789:     $result =~ s/&(forall|\#8704);/\\ensuremath\{\\forall\}/g;
 1790:     $result =~ s/&(part|\#8706);/\\ensuremath\{\\partial\}/g;
 1791:     $result =~ s/&(exist|\#8707);/\\ensuremath\{\\exists\}/g;
 1792:     $result =~ s/&(empty|\#8709);/\\ensuremath\{\\emptyset\}/g;
 1793:     $result =~ s/&(nabla|\#8711);/\\ensuremath\{\\nabla\}/g;
 1794:     $result =~ s/&(isin|\#8712);/\\ensuremath\{\\in\}/g;
 1795:     $result =~ s/&(notin|\#8713);/\\ensuremath\{\\notin\}/g;
 1796:     $result =~ s/&(ni|\#8715);/\\ensuremath\{\\ni\}/g;
 1797:     $result =~ s/&(prod|\#8719);/\\ensuremath\{\\prod\}/g;
 1798:     $result =~ s/&(sum|\#8721);/\\ensuremath\{\\sum\}/g;
 1799:     $result =~ s/&(minus|\#8722);/\\ensuremath\{-\}/g;
 1800:     $result =~ s/–/\\ensuremath\{-\}/g;
 1801:     $result =~ s/&(lowast|\#8727);/\\ensuremath\{*\}/g;
 1802:     $result =~ s/&(radic|\#8730);/\\ensuremath\{\\surd\}/g;
 1803:     $result =~ s/&(prop|\#8733);/\\ensuremath\{\\propto\}/g;
 1804:     $result =~ s/&(infin|\#8734);/\\ensuremath\{\\infty\}/g;
 1805:     $result =~ s/&(ang|\#8736);/\\ensuremath\{\\angle\}/g;
 1806:     $result =~ s/&(and|\#8743);/\\ensuremath\{\\wedge\}/g;
 1807:     $result =~ s/&(or|\#8744);/\\ensuremath\{\\vee\}/g;
 1808:     $result =~ s/&(cap|\#8745);/\\ensuremath\{\\cap\}/g;
 1809:     $result =~ s/&(cup|\#8746);/\\ensuremath\{\\cup\}/g;
 1810:     $result =~ s/&(int|\#8747);/\\ensuremath\{\\int\}/g;
 1811:     $result =~ s/&(sim|\#8764);/\\ensuremath\{\\sim\}/g;
 1812:     $result =~ s/&(cong|\#8773);/\\ensuremath\{\\cong\}/g;
 1813:     $result =~ s/&(asymp|\#8776);/\\ensuremath\{\\approx\}/g;
 1814:     $result =~ s/&(ne|\#8800);/\\ensuremath\{\\not=\}/g;
 1815:     $result =~ s/&(equiv|\#8801);/\\ensuremath\{\\equiv\}/g;
 1816:     $result =~ s/&(le|\#8804);/\\ensuremath\{\\leq\}/g;
 1817:     $result =~ s/&(ge|\#8805);/\\ensuremath\{\\geq\}/g;
 1818:     $result =~ s/&(sub|\#8834);/\\ensuremath\{\\subset\}/g;
 1819:     $result =~ s/&(sup|\#8835);/\\ensuremath\{\\supset\}/g;
 1820:     $result =~ s/&(nsub|\#8836);/\\ensuremath\{\\not\\subset\}/g;
 1821:     $result =~ s/&(sube|\#8838);/\\ensuremath\{\\subseteq\}/g;
 1822:     $result =~ s/&(supe|\#8839);/\\ensuremath\{\\supseteq\}/g;
 1823:     $result =~ s/&(oplus|\#8853);/\\ensuremath\{\\oplus\}/g;
 1824:     $result =~ s/&(otimes|\#8855);/\\ensuremath\{\\otimes\}/g;
 1825:     $result =~ s/&(perp|\#8869);/\\ensuremath\{\\perp\}/g;
 1826:     $result =~ s/&(sdot|\#8901);/\\ensuremath\{\\cdot\}/g;
 1827: #Geometric Shapes (extended HTML 4.01)
 1828:     $result =~ s/&(loz|\#9674);/\\ensuremath\{\\Diamond\}/g;
 1829: #Miscellaneous Symbols (extended HTML 4.01)
 1830:     $result =~ s/&(spades|\#9824);/\\ensuremath\{\\spadesuit\}/g;
 1831:     $result =~ s/&(clubs|\#9827);/\\ensuremath\{\\clubsuit\}/g;
 1832:     $result =~ s/&(hearts|\#9829);/\\ensuremath\{\\heartsuit\}/g;
 1833:     $result =~ s/&(diams|\#9830);/\\ensuremath\{\\diamondsuit\}/g;
 1834: #   Chemically useful 'things' contributed by Hon Kie (bug 4652).
 1835: 
 1836:     $result =~ s/&\#8636;/\\ensuremath\{\\leftharpoonup\}/g;
 1837:     $result =~ s/&\#8637;/\\ensuremath\{\\leftharpoondown\}/g;
 1838:     $result =~ s/&\#8640;/\\ensuremath\{\\rightharpoonup\}/g;
 1839:     $result =~ s/&\#8641;/\\ensuremath\{\\rightharpoondown\}/g;
 1840:     $result =~ s/&\#8652;/\\ensuremath\{\\rightleftharpoons\}/g;
 1841:     $result =~ s/&\#8605;/\\ensuremath\{\\leadsto\}/g;
 1842:     $result =~ s/&\#8617;/\\ensuremath\{\\hookleftarrow\}/g;
 1843:     $result =~ s/&\#8618;/\\ensuremath\{\\hookrightarrow\}/g;
 1844:     $result =~ s/&\#8614;/\\ensuremath\{\\mapsto\}/g;
 1845:     $result =~ s/&\#8599;/\\ensuremath\{\\nearrow\}/g;
 1846:     $result =~ s/&\#8600;/\\ensuremath\{\\searrow\}/g;
 1847:     $result =~ s/&\#8601;/\\ensuremath\{\\swarrow\}/g;
 1848:     $result =~ s/&\#8598;/\\ensuremath\{\\nwarrow\}/g;
 1849: 
 1850:     # Left/right quotations:
 1851: 
 1852:     $result =~ s/&(ldquo|#8220);/\`\`/g;
 1853:     $result =~ s/&(rdquo|#8221);/\'\'/g;
 1854: 
 1855: 
 1856: 
 1857:     return $result;
 1858: }
 1859: 
 1860: 
 1861:                   #width, height, oddsidemargin, evensidemargin, topmargin
 1862: my %page_formats=
 1863:     ('letter' => {
 1864: 	 'book' => {
 1865: 	     '1' => [ '7.1 in','9.7 in', '-0.57 in','-0.57 in','-0.5 in'],
 1866: 	     '2' => ['3.66 in','9.8 in', '-0.57 in','-0.57 in','-0.5 in']
 1867: 	 },
 1868: 	 'album' => {
 1869: 	     '1' => [ '8.8 in', '6.8 in','-0.55 in',  '-0.55 in','-0.5 in'],
 1870: 	     '2' => [ '4.8 in', '6.7 in','-0.5 in', '-1.0 in','3.0 in']
 1871: 	 },
 1872:      },
 1873:      'legal' => {
 1874: 	 'book' => {
 1875: 	     '1' => ['7.1 in','13 in',,'-0.57 in','-0.57 in','-0.5 in'],
 1876: 	     '2' => ['3.66 in','13 in','-0.57 in','-0.57 in','-0.5 in']
 1877: 	 },
 1878: 	 'album' => {
 1879: 	     '1' => ['12 in','7.1 in',,'-0.57 in','-0.57 in','-0.5 in'],
 1880:              '2' => ['5.7 in','7.1 in','-1 in','-1 in','5 in']
 1881:           },
 1882:      },
 1883:      'tabloid' => {
 1884: 	 'book' => {
 1885: 	     '1' => ['9.8 in','16 in','-0.57 in','-0.57 in','-0.5 in'],
 1886: 	     '2' => ['4.9 in','16 in','-0.57 in','-0.57 in','-0.5 in']
 1887: 	 },
 1888: 	 'album' => {
 1889: 	     '1' => ['16 in','9.8 in','-0.57 in','-0.57 in','-0.5 in'],
 1890: 	     '2' => ['16 in','4.9 in','-0.57 in','-0.57 in','-0.5 in']
 1891:           },
 1892:      },
 1893:      'executive' => {
 1894: 	 'book' => {
 1895: 	     '1' => ['6.8 in','9 in','-0.57 in','-0.57 in','1.2 in'],
 1896: 	     '2' => ['3.1 in','9 in','-0.57 in','-0.57 in','1.2 in']
 1897: 	 },
 1898: 	 'album' => {
 1899: 	     '1' => [],
 1900: 	     '2' => []
 1901:           },
 1902:      },
 1903:      'a2' => {
 1904: 	 'book' => {
 1905: 	     '1' => [],
 1906: 	     '2' => []
 1907: 	 },
 1908: 	 'album' => {
 1909: 	     '1' => [],
 1910: 	     '2' => []
 1911:           },
 1912:      },
 1913:      'a3' => {
 1914: 	 'book' => {
 1915: 	     '1' => [],
 1916: 	     '2' => []
 1917: 	 },
 1918: 	 'album' => {
 1919: 	     '1' => [],
 1920: 	     '2' => []
 1921:           },
 1922:      },
 1923:      'a4' => {
 1924: 	 'book' => {
 1925: 	     '1' => ['17.6 cm','27.2 cm','-1.397 cm','-2.11 cm','-1.27 cm'],
 1926: 	     '2' => [ '9.1 cm','27.2 cm','-1.397 cm','-2.11 cm','-1.27 cm']
 1927: 	 },
 1928: 	 'album' => {
 1929: 	     '1' => ['24.0 cm','18.0 cm','-1.0 cm','-1.0 cm','-1.25 cm'],
 1930: 	     '2' => ['11.5 cm','18.0 cm','-0.7 cm','-1.7 cm','-1.25 cm']
 1931: 	 },
 1932:      },
 1933:      'a5' => {
 1934: 	 'book' => {
 1935: 	     '1' => [],
 1936: 	     '2' => []
 1937: 	 },
 1938: 	 'album' => {
 1939: 	     '1' => [],
 1940: 	     '2' => []
 1941:           },
 1942:      },
 1943:      'a6' => {
 1944: 	 'book' => {
 1945: 	     '1' => [],
 1946: 	     '2' => []
 1947: 	 },
 1948: 	 'album' => {
 1949: 	     '1' => [],
 1950: 	     '2' => []
 1951:           },
 1952:      },
 1953:      );
 1954: 
 1955: sub page_format {
 1956: #
 1957: #Supported paper format: "Letter [8 1/2x11 in]",      "Legal [8 1/2x14 in]",
 1958: #                        "Ledger/Tabloid [11x17 in]", "Executive [7 1/2x10 in]",
 1959: #                        "A2 [420x594 mm]",           "A3 [297x420 mm]",
 1960: #                        "A4 [210x297 mm]",           "A5 [148x210 mm]",
 1961: #                        "A6 [105x148 mm]"
 1962: #
 1963:     my ($papersize,$layout,$numberofcolumns) = @_;
 1964:     return @{$page_formats{$papersize}->{$layout}->{$numberofcolumns}};
 1965: }
 1966: 
 1967: 
 1968: sub get_name {
 1969:     my ($uname,$udom)=@_;
 1970:     if (!defined($uname)) { $uname=$env{'user.name'}; }
 1971:     if (!defined($udom)) { $udom=$env{'user.domain'}; }
 1972:     my $plainname=&Apache::loncommon::plainname($uname,$udom);
 1973:     if ($plainname=~/^\s*$/) { $plainname=$uname.'@'.$udom; }
 1974:    $plainname=&Apache::lonxml::latex_special_symbols($plainname,'header');
 1975:     return $plainname;
 1976: }
 1977: 
 1978: sub get_course {
 1979:     my $courseidinfo;
 1980:     if (defined($env{'request.course.id'})) {
 1981: 	$courseidinfo = &Apache::lonxml::latex_special_symbols(&unescape($env{'course.'.$env{'request.course.id'}.'.description'}),'header');
 1982: 	my $sec = $env{'request.course.sec'};
 1983: 
 1984:     }
 1985:     return $courseidinfo;
 1986: }
 1987: 
 1988: sub page_format_transformation {
 1989:     my ($papersize,$layout,$numberofcolumns,$choice,$text,$assignment,$tableofcontents,
 1990:         $indexlist,$selectionmade,$mostrecent) = @_;
 1991:     my ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin);
 1992: 
 1993:     if ($selectionmade eq '4') {
 1994: 	if ($choice eq 'all_problems') {
 1995:             $assignment=&mt('Problems from the Whole Course');
 1996: 	} else {
 1997:             $assignment=&mt('Resources from the Whole Course');
 1998: 	}
 1999:     } else {
 2000: 	$assignment=&Apache::lonxml::latex_special_symbols($assignment,'header');
 2001:     }
 2002:     ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin) = &page_format($papersize,$layout,$numberofcolumns,$topmargin);
 2003: 
 2004:     my $name;
 2005:     if ($mostrecent ne '') {
 2006:         $name = $mostrecent;
 2007:     } else {
 2008:         $name = &get_name();
 2009:     }
 2010:     my $courseidinfo = &get_course();
 2011:     my $header_text  = $parmhash{'print_header_format'};
 2012:     $header_text     = &format_page_header($textwidth, $header_text, $assignment,
 2013: 					   $courseidinfo, $name);
 2014:     my $topmargintoinsert = '';
 2015:     if ($topmargin ne '0') {$topmargintoinsert='\setlength{\topmargin}{'.$topmargin.'}';}
 2016:     my $fancypagestatement='';
 2017:     if ($numberofcolumns eq '2') {
 2018: 	$fancypagestatement="\\fancyhead{}\\fancyhead[LO]{$header_text}";
 2019: 	if ($parmhash{'print_header_format'} eq '') {
 2020: 	    $fancypagestatement .= "\\fancyhead[RE]{\\thepage \\\\[\\baselineskip]}";
 2021: 	}
 2022:     } else {
 2023: 	$fancypagestatement="\\rhead{}\\chead{}\\lhead{$header_text}";
 2024:     }
 2025:     $fancypagestatement .= "\\fancyfoot{}";
 2026:     my ($paperwidth,$paperheight);
 2027:     if ($layout eq 'album') {
 2028: 	    $text =~ s/\\begin\{document}/\\setlength{\\oddsidemargin}{$oddoffset}\\setlength{\\evensidemargin}{$evenoffset}$topmargintoinsert\n\\setlength{\\textwidth}{$textwidth}\\setlength{\\textheight}{$textheight}\\setlength{\\textfloatsep}{8pt plus 2\.0pt minus 4\.0pt}\n\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\usepackage{fancyhdr}\\addtolength{\\headheight}{\\baselineskip}\n\\pagestyle{fancy}$fancypagestatement\\usepackage{booktabs}\\begin{document}\\voffset=-0\.8 cm\\setcounter{page}{1}\n /;
 2029:         if ($papersize eq 'a4') {
 2030:             $paperwidth = '29.7cm';
 2031:             $paperheight = '21.0cm';
 2032:         } elsif ($numberofcolumns eq '1') {
 2033:             if ($papersize eq 'letter') {
 2034:                 $paperwidth = '11.0in';
 2035:                 $paperheight = '8.5in';
 2036:             } elsif ($papersize eq 'legal') {
 2037:                 $paperwidth = '14.0in';
 2038:                 $paperheight = '8.5in';
 2039:             }
 2040:         }
 2041:     } elsif ($layout eq 'book') {
 2042: 	if ($choice ne 'All class print') {
 2043: 	    $text =~ s/\\begin\{document}/\\textheight $textheight\\oddsidemargin = $evenoffset\\evensidemargin = $evenoffset $topmargintoinsert\n\\textwidth= $textwidth\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\n\\renewcommand{\\ref}{\\keephidden\}\\usepackage{fancyhdr}\\addtolength{\\headheight}{\\baselineskip}\\pagestyle{fancy}$fancypagestatement\\usepackage{booktabs}\\begin{document}\n\\voffset=-0\.8 cm\\setcounter{page}{1}\n/;
 2044: 	} else {
 2045: 	    $text =~ s/\\pagestyle\{fancy}\\rhead\{}\\chead\{}\s*\\begin\{document}/\\textheight = $textheight\\oddsidemargin = $evenoffset\n\\evensidemargin = $evenoffset $topmargintoinsert\\textwidth= $textwidth\\newlength{\\minipagewidth}\n\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\renewcommand{\\ref}{\\keephidden\}\\pagestyle{fancy}\\rhead{}\\chead{}\\usepackage{booktabs}\\begin{document}\\voffset=-0\.8cm\n\\setcounter{page}{1}  \\vskip 5 mm\n /;
 2046: 	}
 2047:         if ($papersize eq 'a4') {
 2048:             $paperwidth = '21.0cm';
 2049:             $paperheight = '29.7cm';
 2050:         } elsif ($papersize eq 'letter') {
 2051:             $paperwidth = '8.5in';
 2052:             $paperheight = '11.0in';
 2053:          } elsif ($papersize eq 'legal') {
 2054:             $paperwidth = '8.5in';
 2055:             $paperheight = '14.0in';
 2056:         }
 2057:     }
 2058:     if ($paperwidth ne '' && $paperheight ne '') {
 2059:         my $papersize_text;
 2060:         if ($perm{'pav'}) {
 2061:             $papersize_text = '\\special{papersize='.$paperwidth.','.$paperheight.'}';
 2062:         } else {
 2063:             $papersize_text = '\special{papersize='.$paperwidth.','.$paperheight.'}';
 2064:         }
 2065:         $text =~ s/(\\begin\{document})/$1$papersize_text/;
 2066:     }
 2067:     if ($tableofcontents eq 'yes') {$text=~s/(\\setcounter\{page\}\{1\})/$1 \\tableofcontents\\newpage /;}
 2068:     if ($indexlist eq 'yes') {
 2069: 	$text=~s/(\\begin\{document})/\\makeindex $1/;
 2070: 	$text=~s/(\\end\{document})/\\strut\\\\\\strut\\printindex $1/;
 2071:     }
 2072:     return $text;
 2073: }
 2074: 
 2075: 
 2076: sub page_cleanup {
 2077:     my $result = shift;	
 2078: 
 2079:     $result =~ m/\\end\{document}(\d*)$/;
 2080:     my $number_of_columns = $1;
 2081:     my $insert = '{';
 2082:     for (my $id=1;$id<=$number_of_columns;$id++) { $insert .='l'; }
 2083:     $insert .= '}';
 2084:     $result =~ s/(\\begin\{longtable})INSERTTHEHEADOFLONGTABLE\\endfirsthead\\endhead/$1$insert/g;
 2085:     $result =~ s/&\s*REMOVETHEHEADOFLONGTABLE\\\\/\\\\/g;
 2086:     return $result,$number_of_columns;
 2087: }
 2088: 
 2089: 
 2090: sub details_for_menu {
 2091:     my ($helper)=@_;
 2092:     my $postdata=$env{'form.postdata'};
 2093:     if (!$postdata) { $postdata=$helper->{VARS}{'postdata'}; }
 2094:     my $name_of_resource = &Apache::lonnet::gettitle($postdata);
 2095:     my $symbolic = &Apache::lonnet::symbread($postdata);
 2096:     return if ( $symbolic eq '');
 2097: 
 2098:     my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symbolic);
 2099:     $map=&Apache::lonnet::clutter($map);
 2100:     my $name_of_sequence = &Apache::lonnet::gettitle($map);
 2101:     if ($name_of_sequence =~ /^\s*$/) {
 2102: 	$map =~ m|([^/]+)$|;
 2103: 	$name_of_sequence = $1;
 2104:     }
 2105:     my $name_of_map = &Apache::lonnet::gettitle($env{'request.course.uri'});
 2106:     if ($name_of_map =~ /^\s*$/) {
 2107: 	$env{'request.course.uri'} =~ m|([^/]+)$|;
 2108: 	$name_of_map = $1;
 2109:     }
 2110:     return ($name_of_resource,$name_of_sequence,$name_of_map);
 2111: }
 2112: 
 2113: sub copyright_line {
 2114:     return '\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\vspace*{-2 mm}\newline\noindent{\tiny Printed from LON-CAPA\copyright MSU{\hfill} Licensed under GNU General Public License } ';
 2115: }
 2116: my $end_of_student = "\n".'\special{ps:ENDOFSTUDENTSTAMP}'."\n";
 2117: 
 2118: sub latex_corrections {
 2119:     my ($number_of_columns,$result,$selectionmade,$answer_mode) = @_;
 2120: #    $result =~ s/\\includegraphics\{/\\includegraphics\[width=\\minipagewidth\]{/g;
 2121:     my $copyright = &copyright_line();
 2122:     if ($selectionmade eq '1' || $answer_mode eq 'only') {
 2123: 	$result =~ s/(\\end\{document})/\\strut\\vskip 0 mm $copyright $end_of_student $1/;
 2124:     } else {
 2125: 	$result =~ s/(\\end\{document})/\\strut\\vspace\*{-4 mm}\\newline $copyright $end_of_student $1/;
 2126:     }
 2127:     $result =~ s/\$number_of_columns/$number_of_columns/g;
 2128:     $result =~ s/(\\end\{longtable}\s*)(\\strut\\newline\\noindent\\makebox\[\\textwidth\/$number_of_columns\]\[b\]\{\\hrulefill})/$2$1/g;
 2129:     $result =~ s/(\\end\{longtable}\s*)\\strut\\newline/$1/g;
 2130: #-- LaTeX corrections
 2131:     my $first_comment = index($result,'<!--',0);
 2132:     while ($first_comment != -1) {
 2133: 	my $end_comment = index($result,'-->',$first_comment);
 2134: 	substr($result,$first_comment,$end_comment-$first_comment+3) = '';
 2135: 	$first_comment = index($result,'<!--',$first_comment);
 2136:     }
 2137:     $result =~ s/^\s+$//gm; #remove empty lines
 2138:     #removes more than one empty space
 2139:     $result =~ s|(\s\s+)|($1=~/[\n\r]/)?"\n":" "|ge;
 2140:     $result =~ s/\\\\\s*\\vskip/\\vskip/gm;
 2141:     $result =~ s/\\\\\s*\\noindent\s*(\\\\)+/\\\\\\noindent /g;
 2142:     $result =~ s/{\\par }\s*\\\\/\\\\/gm;
 2143:     $result =~ s/\\\\\s+\[/ \[/g;
 2144:     #conversion of html characters to LaTeX equivalents
 2145:     if ($result =~ m/&(\w+|#\d+);/) {
 2146: 	$result = &character_chart($result);
 2147:     }
 2148:     $result =~ s/(\\end\{tabular})\s*\\vskip 0 mm/$1/g;
 2149:     $result =~ s/(\\begin\{enumerate})\s*\\noindent/$1/g;
 2150:     return $result;
 2151: }
 2152: 
 2153: 
 2154: sub index_table {
 2155:     my $currentURL = shift;
 2156:     my $insex_string='';
 2157:     $currentURL=~s/\.([^\/+])$/\.$1\.meta/;
 2158:     $insex_string=&Apache::lonnet::metadata($currentURL,'keywords');
 2159:     return $insex_string;
 2160: }
 2161: 
 2162: 
 2163: sub IndexCreation {
 2164:     my ($texversion,$currentURL)=@_;
 2165:     my @key_words=split(/,/,&index_table($currentURL));
 2166:     my $chunk='';
 2167:     my $st=index $texversion,'\addcontentsline{toc}{subsection}{';
 2168:     if ($st>0) {
 2169: 	for (my $i=0;$i<3;$i++) {$st=(index $texversion,'}',$st+1);}
 2170: 	$chunk=substr($texversion,0,$st+1);
 2171: 	substr($texversion,0,$st+1)=' ';
 2172:     }
 2173:     foreach my $key_word (@key_words) {
 2174: 	if ($key_word=~/\S+/) {
 2175: 	    $texversion=~s/\b($key_word)\b/$1 \\index{$key_word} /i;
 2176: 	}
 2177:     }			
 2178:     if ($st>0) {substr($texversion,0,1)=$chunk;}
 2179:     return $texversion;
 2180: }
 2181: 
 2182: sub print_latex_header {
 2183:     my $mode=shift;
 2184: 
 2185:     return &Apache::londefdef::latex_header($mode);
 2186: }
 2187: 
 2188: sub path_to_problem {
 2189:     my ($urlp,$colwidth)=@_;
 2190:     $urlp=&Apache::lonnet::clutter($urlp);
 2191: 
 2192:     my $newurlp = '';
 2193:     $colwidth=~s/\s*mm\s*$//;
 2194: #characters average about 2 mm in width
 2195:     if (length($urlp)*2 > $colwidth) {
 2196: 	my @elements = split('/',$urlp);
 2197: 	my $curlength=0;
 2198: 	foreach my $element (@elements) {
 2199: 	    if ($element eq '') { next; }
 2200: 	    if ($curlength+(length($element)*2) > $colwidth) {
 2201: 		$newurlp .=  '|\vskip -1 mm \verb|';
 2202: 		$curlength=length($element)*2;
 2203: 	    } else {
 2204: 		$curlength+=length($element)*2;
 2205: 	    }
 2206: 	    $newurlp.='/'.$element;
 2207: 	}
 2208:     } else {
 2209: 	$newurlp=$urlp;
 2210:     }
 2211:     return '{\small\noindent\verb|'.$newurlp.'|\vskip 0 mm}';
 2212: }
 2213: 
 2214: sub recalcto_mm {
 2215:     my $textwidth=shift;
 2216:     my $LaTeXwidth;
 2217:     if ($textwidth=~/(-?\d+\.?\d*)\s*cm/) {
 2218: 	$LaTeXwidth = $1*10;
 2219:     } elsif ($textwidth=~/(-?\d+\.?\d*)\s*mm/) {
 2220: 	$LaTeXwidth = $1;
 2221:     } elsif ($textwidth=~/(-?\d+\.?\d*)\s*in/) {
 2222: 	$LaTeXwidth = $1*25.4;
 2223:     }
 2224:     $LaTeXwidth.=' mm';
 2225:     return $LaTeXwidth;
 2226: }
 2227: 
 2228: sub get_textwidth {
 2229:     my ($helper,$LaTeXwidth)=@_;
 2230:     my $textwidth=$LaTeXwidth;
 2231:     if ($helper->{'VARS'}->{'pagesize.width'}=~/\d+/ &&
 2232: 	$helper->{'VARS'}->{'pagesize.widthunit'}=~/\w+/) {
 2233: 	$textwidth=&recalcto_mm($helper->{'VARS'}->{'pagesize.width'}.' '.
 2234: 				$helper->{'VARS'}->{'pagesize.widthunit'});
 2235:     }
 2236:     return $textwidth;
 2237: }
 2238: 
 2239: 
 2240: sub unsupported {
 2241:     my ($currentURL,$mode,$symb)=@_;
 2242:     my $cleanURL=&Apache::lonenc::check_decrypt($currentURL);
 2243:     my $shown = $currentURL;
 2244:     if (($cleanURL ne $currentURL) || ($symb =~ m{/^enc/})) {
 2245:         $shown = &mt('URL not shown (encrypted)');
 2246:     }
 2247:     if ($mode ne '') {$mode='\\'.$mode}
 2248:     my $result = &print_latex_header($mode);
 2249:     if ($cleanURL=~m|^(/adm/wrapper)?/ext/|) {
 2250:         $cleanURL=~s|^(/adm/wrapper)?/ext/|http://|;
 2251:         $cleanURL=~s|^http://https://|https://|;
 2252:         if ($shown eq $currentURL) {
 2253:             $shown = &Apache::lonxml::latex_special_symbols($cleanURL);
 2254:         }
 2255:         my $title=&Apache::lonnet::gettitle($symb);
 2256:         $title = &Apache::lonxml::latex_special_symbols($title);
 2257:         $result.=' \strut \\\\ \textit{'.$title.'} \strut \\\\ '.$shown.' ';
 2258:     } else {
 2259:         if ($shown eq $currentURL) {
 2260: 	    $result.=&Apache::lonxml::latex_special_symbols($currentURL);
 2261:         } else {
 2262:             $result.=$shown;
 2263:         }
 2264:     }
 2265:     $result.= '\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill} \end{document}';
 2266:     return $result;
 2267: }
 2268: 
 2269: #
 2270: #  Map from helper layout style to the book/album:
 2271: #
 2272: sub map_laystyle {
 2273:     my ($laystyle) = @_;
 2274:     if ($laystyle eq 'L') {
 2275: 	$laystyle='album';
 2276:     } else {
 2277: 	$laystyle='book';
 2278:     }
 2279:     return $laystyle;
 2280: }
 2281: 
 2282: sub print_page_in_course {
 2283:     my ($helper, $rparmhash, $currentURL, $resources) = @_;
 2284: 
 2285:     my %parmhash       = %$rparmhash;
 2286:     my @page_resources = @$resources;
 2287:     my $mode = $helper->{'VARS'}->{'LATEX_TYPE'};
 2288:     my $symb = $helper->{'VARS'}->{'symb'};
 2289: 
 2290: 
 2291:     my $format_from_helper = $helper->{'VARS'}->{'FORMAT'};
 2292: 
 2293: 
 2294:     my @temporary_array=split /\|/,$format_from_helper;
 2295:     my ($laystyle,$numberofcolumns,$papersize,$pdfFormFields)=@temporary_array;
 2296:     $laystyle = &map_laystyle($laystyle);
 2297:     my ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$laystyle,
 2298: 								      $numberofcolumns);
 2299:     my $LaTeXwidth=&recalcto_mm($textwidth);
 2300: 
 2301:     if ($mode ne '') {$mode='\\'.$mode}
 2302:     my $result   =    &print_latex_header($mode);
 2303: 
 2304:     my $title=&Apache::lonnet::gettitle($currentURL);
 2305:     $title = &Apache::lonxml::latex_special_symbols($title);
 2306:     $result .= '\noindent\textit{'.$title.'}\\\\';
 2307: 
 2308:     if ($helper->{'VARS'}->{'style_file'}=~/\w/) {
 2309: 	&Apache::lonnet::appenv({'construct.style' =>
 2310: 				$helper->{'VARS'}->{'style_file'}});
 2311:     } elsif ($env{'construct.style'}) {
 2312: 	&Apache::lonnet::delenv('construct.style');
 2313:     }
 2314: 
 2315:     # First is the overall page description.  This is then followed by the
 2316:     # components of the page. Each of which must be printed independently.
 2317:     my $the_page = shift(@page_resources);
 2318: 
 2319: 
 2320:     foreach my $resource (@page_resources) {
 2321: 	my $resource_src   = $resource->src(); # Essentially the URL of the resource.
 2322:         my $current_url = $resource->link();
 2323: 
 2324: 	# Recurse if a .page:
 2325: 
 2326: 	if ($resource_src =~ /.page$/i) {
 2327: 	    my $navmap         = Apache::lonnavmaps::navmap->new();
 2328: 	    my @page_resources = $navmap->retrieveResources($resource_src);
 2329: 	    $result           .= &print_page_in_course($helper, $rparmhash,
 2330: 						       $resource_src, \@page_resources);
 2331:         } elsif ($resource->ext()) {
 2332:             $result.=&latex_header_footer_remove(&unsupported($current_url,$mode,$resource->symb));
 2333: 	} elsif ($resource_src =~ /\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm)$/)  {
 2334:             # these resources go through the XML transformer:
 2335:             $result .= &Apache::lonxml::latex_special_symbols($resource->title()) . '\\\\';
 2336: 
 2337: 	    my $urlp = &Apache::lonnet::clutter($resource_src);
 2338: 
 2339: 	    my %form;
 2340: 	    my %moreenv;
 2341: 
 2342: 	    &Apache::lonxml::remember_problem_counter();
 2343: 	    $moreenv{'request.filename'}=$urlp;
 2344: 	    if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {$form{'problemtype'}='exam';}
 2345: 
 2346: 	    $form{'grade_target'}  = 'tex';
 2347: 	    $form{'textwidth'}    = &get_textwidth($helper, $LaTeXwidth);
 2348: 	    $form{'pdfFormFields'} = $pdfFormFields; #
 2349: 	    $form{'showallfoils'} = $helper->{'VARS'}->{'showallfoils'};
 2350: 
 2351: 	    $form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2352: 	    $form{'suppress_tries'}=$parmhash{'suppress_tries'};
 2353: 	    $form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2354: 	    $form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 2355: 	    $form{'print_annotations'}=$helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 2356: 	    if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') ||
 2357: 		($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes')) {
 2358: 		$form{'problem_split'}='yes';
 2359: 	    }
 2360: 	    my $rndseed = time;
 2361: 	    if ($helper->{'VARS'}->{'curseed'}) {
 2362: 		$rndseed=$helper->{'VARS'}->{'curseed'};
 2363: 	    }
 2364: 	    $form{'rndseed'}=$rndseed;
 2365: 	    &Apache::lonnet::appenv(\%moreenv);
 2366: 
 2367: 	    &Apache::lonxml::clear_problem_counter();
 2368: 
 2369: 	    my $texversion = &ssi_with_retries($urlp, $ssi_retry_count, %form);
 2370: 
 2371: 
 2372: 	    # current document with answers.. no need to encap in minipage
 2373: 	    #  since there's only one answer.
 2374: 
 2375: 	    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2376: 	       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2377: 		my %answerform = %form;
 2378: 
 2379: 
 2380: 		$answerform{'problem_split'}=$parmhash{'problem_stream_switch'};
 2381: 		$answerform{'grade_target'}='answer';
 2382: 		$answerform{'answer_output_mode'}='tex';
 2383: 		$answerform{'rndseed'}=$rndseed;
 2384:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {
 2385: 		    $answerform{'problemtype'}='exam';
 2386: 		}
 2387: 		$resources_printed .= $urlp.':';
 2388: 		my $answer=&ssi_with_retries($urlp,$ssi_retry_count, %answerform);
 2389: 
 2390: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2391: 		    $texversion=~s/(\\keephidden\{ENDOFPROBLEM})/$answer$1/;
 2392: 		} else {
 2393: 		    $texversion= &print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2394: 		    if ($helper->{'VARS'}->{'construction'} ne '1') {
 2395: 			my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 2396: 			$title = &Apache::lonxml::latex_special_symbols($title);
 2397: 			$texversion.='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2398: 			$texversion.=&path_to_problem($urlp,$LaTeXwidth);
 2399: 		    } else {
 2400: 			$texversion.='\vskip 0 mm \noindent\textbf{'.
 2401:                         &mt("Printing from Authoring Space: No Title").'}\vskip 0 mm ';
 2402: 			$texversion.=&path_to_problem($urlp,$LaTeXwidth);
 2403: 		    }
 2404: 		    $texversion.='\vskip 1 mm '.$answer.'\end{document}';
 2405: 		}
 2406: 	    }
 2407: 	    # Print annotations.
 2408: 
 2409: 
 2410: 	    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2411: 		my $annotation .= &annotate($currentURL);
 2412: 		$texversion =~ s/(\\keephidden\{ENDOFPROBLEM})/$annotation$1/;
 2413: 	    }
 2414: 
 2415: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 2416: 		$texversion=&IndexCreation($texversion,$currentURL);
 2417: 	    }
 2418: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 2419: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$currentURL| \\strut\\\\\\strut /;
 2420: 
 2421: 	    }
 2422: 	    $texversion = &latex_header_footer_remove($texversion);
 2423: 
 2424: 	    # the first remaining line is a comment from londefdef the second
 2425: 	    # line  seems to be an extraneous \vskip 1mm \\\\ :
 2426:             # (imperfect removal from header_footer_remove?
 2427: 
 2428: 	    $texversion =~ s/\\vskip 1mm \\\\\\\\//;
 2429: 
 2430: 	    $result .= $texversion;
 2431: 	    if ($currentURL=~m/\.page\s*$/) {
 2432: 		($result,$numberofcolumns) = &page_cleanup($result);
 2433: 	    }
 2434: 	}
 2435:     }
 2436: 
 2437:     $result.= '\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill} \end{document}';
 2438:     return $result;
 2439: }
 2440: 
 2441: 
 2442: #
 2443: # List of recently generated print files
 2444: #
 2445: sub recently_generated {
 2446:     my ($prtspool) = @_;
 2447:     my $output;
 2448:     my $zip_result;
 2449:     my $pdf_result;
 2450:     opendir(DIR,$prtspool);
 2451: 
 2452:     my @files =
 2453: 	grep(/^$env{'user.name'}_$env{'user.domain'}_printout_(\d+)_.*\.(pdf|zip)$/,readdir(DIR));
 2454:     closedir(DIR);
 2455: 
 2456:     @files = sort {
 2457: 	my ($actime) = (stat($prtspool.'/'.$a))[10];
 2458: 	my ($bctime) = (stat($prtspool.'/'.$b))[10];
 2459: 	return $bctime <=> $actime;
 2460:     } (@files);
 2461: 
 2462:     foreach my $filename (@files) {
 2463: 	my ($ext) = ($filename =~ m/(pdf|zip)$/);
 2464: 	my ($cdev,$cino,$cmode,$cnlink,
 2465: 	    $cuid,$cgid,$crdev,$csize,
 2466: 	    $catime,$cmtime,$cctime,
 2467: 	    $cblksize,$cblocks)=stat($prtspool.'/'.$filename);
 2468:         my $ext_text = 'pdf' ? &mt('PDF File'):&mt('Zip File');
 2469: 	my $result=&Apache::loncommon::start_data_table_row()
 2470:                   .'<td>'
 2471:                   .'<a href="/prtspool/'.$filename.'">'.$ext_text.'</a>'
 2472:                   .'</td>'
 2473:                   .'<td>'.&Apache::lonlocal::locallocaltime($cctime).'</td>'
 2474:                   .'<td align="right">'.$csize.'</td>'
 2475:                   .&Apache::loncommon::end_data_table_row();
 2476: 	if ($ext eq 'pdf') { $pdf_result .= $result; }
 2477: 	if ($ext eq 'zip') { $zip_result .= $result; }
 2478:     }
 2479:     if ($zip_result || $pdf_result) {
 2480:         $output ='<hr />';
 2481:     }
 2482:     if ($zip_result) {
 2483: 	$output .='<h3>'.&mt('Recently generated printout zip files')."</h3>\n"
 2484:                   .&Apache::loncommon::start_data_table()
 2485:                   .&Apache::loncommon::start_data_table_header_row()
 2486:                   .'<th>'.&mt('Download').'</th>'
 2487:                   .'<th>'.&mt('Creation Date').'</th>'
 2488:                   .'<th>'.&mt('File Size (Bytes)').'</th>'
 2489:                   .&Apache::loncommon::end_data_table_header_row()
 2490:                   .$zip_result
 2491:                   .&Apache::loncommon::end_data_table();
 2492:     }
 2493:     if ($pdf_result) {
 2494: 	$output .='<h3>'.&mt('Recently generated printouts')."</h3>\n"
 2495:                   .&Apache::loncommon::start_data_table()
 2496:                   .&Apache::loncommon::start_data_table_header_row()
 2497:                   .'<th>'.&mt('Download').'</th>'
 2498:                   .'<th>'.&mt('Creation Date').'</th>'
 2499:                   .'<th>'.&mt('File Size (Bytes)').'</th>'
 2500:                   .&Apache::loncommon::end_data_table_header_row()
 2501:                   .$pdf_result
 2502:                   .&Apache::loncommon::end_data_table();
 2503:     }
 2504:     return $output;
 2505: }
 2506: 
 2507: #
 2508: #   Retrieve the hash of page breaks.
 2509: #
 2510: #  Inputs:
 2511: #    helper   - reference to helper object.
 2512: #  Outputs
 2513: #    A reference to a page break hash.
 2514: #
 2515: #
 2516: # use Data::Dumper;
 2517: # sub dump_helper_vars {
 2518: #    my ($helper) = @_;
 2519: #    my $helpervars = Dumper($helper->{'VARS'});
 2520: #    &Apache::lonnet::logthis("Dump of helper vars:\n $helpervars");
 2521: #}
 2522: 
 2523: sub get_page_breaks  {
 2524:     my ($helper) = @_;
 2525:     my %page_breaks;
 2526: 
 2527:     foreach my $break (split /\|\|\|/, $helper->{'VARS'}->{'FINISHPAGE'}) {
 2528: 	$page_breaks{$break} = 1;
 2529:     }
 2530:     return %page_breaks;
 2531: }
 2532: #
 2533: #   Returns text to insert for any extra vskip prior to the resource.
 2534: #   Parameters:
 2535: #     helper   - Reference to the helper object driving the printout.
 2536: #     resource - Identifies the resource about to be printed.
 2537: #
 2538: #   This is done as follows:
 2539: #    POSSIBLE_RESOURCES has the list of possible resources.
 2540: #    EXTRASPACE         has the list of extra space values.
 2541: #    EXTRASPACE_UNITS   is the set of resources for which the units are
 2542: #                       mm. All others are 'in'.
 2543: #
 2544: #    The resource is found in the POSSIBLE_RESOURCES to get the index
 2545: #    of the EXTRASPACE value.
 2546: #
 2547: #   In order to speed this up for lengthy printouts, the first time,
 2548: #   POSSIBLE_RESOURCES is turned into a look up hash and
 2549: #   EXTRASPACE is turned into an array.
 2550: #
 2551: 
 2552: 
 2553: my %possible_resources;
 2554: my %extraspace_mm;
 2555: my @extraspace;
 2556: my $skips_loaded       = 0;
 2557: 
 2558: #  Function to load the skips hash and array
 2559: 
 2560: sub load_skips {
 2561: 
 2562:     my ($helper)  = @_;
 2563: 
 2564:     # If this is the first time, unwrap the resources and extra spaces:
 2565: 
 2566:     if (!$skips_loaded) {
 2567: 	@extraspace = (split(/\|\|\|/, $helper->{'VARS'}->{'EXTRASPACE'}));
 2568: 	my @resource_list = (split(/\|\|\|/, $helper->{'VARS'}->{'POSSIBLE_RESOURCES'}));
 2569: 	my $i = 0;
 2570: 	foreach my $resource (@resource_list) {
 2571: 	    $possible_resources{$resource} = $i;
 2572: 	    $i++;
 2573: 	}
 2574: 	foreach my $mm_resource (split(/\|\|\|/, $helper->{'VARS'}->{'EXTRASPACE_UNITS'})) {
 2575: 	    $extraspace_mm{$mm_resource} = 1;
 2576: 	}
 2577: 	$skips_loaded = 1;
 2578:     }
 2579: }
 2580: 
 2581: sub get_extra_vspaces {
 2582:     my ($helper, $resource) = @_;
 2583: 
 2584:     &load_skips($helper);
 2585: 
 2586:     #  Lookup the resource in the possible resources hash.. that is the index
 2587:     # into the extraspace array that gives us either an empty string or
 2588:     # the number of mm to skip:
 2589: 
 2590:     my $index = $possible_resources{$resource};
 2591:     my $skip  = $extraspace[$index];
 2592: 
 2593:     my $result = '';
 2594:     if ($skip ne '') {
 2595: 	my $units = 'in';
 2596: 	if (defined($extraspace_mm{$resource})) {
 2597: 	    $units = 'mm';
 2598: 	}
 2599: 	$result = '\vskip '.$skip.' '.$units;
 2600:     }
 2601: 
 2602: 	
 2603:     return $result;
 2604: 
 2605: 
 2606: }
 2607: 
 2608: #
 2609: #  The resource chooser part of the helper needs more than just
 2610: #  the value of the extraspaces var to recover the value into a text
 2611: #  field option.  This sub produces the required format for the saved var:
 2612: #  specifically
 2613: #    ||| separated fields of the form resourcename=value
 2614: #
 2615: #  Parameters:
 2616: #    $helper     - Refers to the helper we are configuring
 2617: #  Implicit input:
 2618: #     $helper->{'VARS'}->{'EXTRASPACE'}  - the spaces helper var has the text field
 2619: #                                          value.
 2620: #     $helper->{'VARS'}->{'EXTRASPACE_UNITS'} - units for the skips (checkboxes).
 2621: #     $helper->{'VARS'}->{'POSSIBLE_RESOURCES'}  - has the list of resources. |||
 2622: #                                          separated of course.
 2623: #  Implicit outputs:
 2624: #     $env{'form.extraspace'}
 2625: #     $env{'form.extraspace_units'}
 2626: #
 2627: sub set_form_extraspace {
 2628:     my ($helper) = @_;
 2629: 
 2630:     # the most convenient way to do this is to drive from the skips arrays/hash.
 2631:     # may not be the fastest, but this is once per print request so it's not so
 2632:     # speed critical:
 2633: 
 2634:     &load_skips($helper);
 2635: 
 2636:     my $result = '';
 2637: 
 2638:     foreach my $resource (keys(%possible_resources)) {
 2639: 	my $vskip = $extraspace[$possible_resources{$resource}];
 2640: 	$result  .= $resource .'=' . $vskip . '|||';
 2641:     }
 2642: 
 2643:     $env{'form.extraspace'}  = $result;
 2644:     $env{'form.extraspace_units'} = $helper->{'VARS'}->{'EXTRASPACE_UNITS'};
 2645:     return $result;
 2646: 
 2647: }
 2648: 
 2649: #  Output a sequence (recursively if neeed)
 2650: #  from construction space.
 2651: # Parameters:
 2652: #    url     = URL of the sequence to print.
 2653: #    helper  - Reference to the helper hash.
 2654: #    form    - Copy of the format hash.
 2655: #    LaTeXWidth
 2656: # Returns:
 2657: #   Text to add to the printout.
 2658: #   NOTE if the first element of the outermost sequence
 2659: #   is itself a sequence, the outermost caller may need to
 2660: #   prefix the latex with the page headers stuff.
 2661: #
 2662: sub print_construction_sequence {
 2663:     my ($currentURL, $helper, %form, $LaTeXwidth) = @_;
 2664: 
 2665:     my $result;
 2666:     my $rndseed=time;
 2667:     if ($helper->{'VARS'}->{'curseed'}) {
 2668: 	$rndseed=$helper->{'VARS'}->{'curseed'};
 2669:     }
 2670:     my $errtext=&LONCAPA::map::mapread(&Apache::lonnet::filelocation('',$currentURL));
 2671: 
 2672:     #
 2673:     #  These make this all support recursing for subsequences.
 2674:     #
 2675:     my @order    = @LONCAPA::map::order;
 2676:     my @resources = @LONCAPA::map::resources;
 2677: 
 2678:     for (my $member=0;$member<=$#order;$member++) {
 2679: 	$resources[$order[$member]]=~/^([^:]*):([^:]*):/;
 2680: 	my $urlp=$2;
 2681: 	if ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm)$/) {
 2682: 	    my $texversion='';
 2683: 	    if ($helper->{'VARS'}->{'ANSWER_TYPE'} ne 'only') {
 2684: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2685: 		$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 2686: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2687: 		$form{'rndseed'}=$rndseed;
 2688: 		$resources_printed .=$urlp.':';
 2689: 		$texversion=&ssi_with_retries($urlp, $ssi_retry_count, %form);
 2690: 	    }
 2691: 	    if((($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2692: 		($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) &&
 2693: 	       ($urlp=~/$LONCAPA::assess_page_re/)) {
 2694: 		#  Don't permanently modify %$form...
 2695: 		my %answerform = %form;
 2696: 		$answerform{'grade_target'}='answer';
 2697: 		$answerform{'answer_output_mode'}='tex';
 2698: 		$answerform{'rndseed'}=$rndseed;
 2699: 		$answerform{'problem_split'}=$parmhash{'problem_stream_switch'};
 2700: 		if ($urlp=~/\/res\//) {$env{'request.state'}='published';}
 2701: 		$resources_printed .= $urlp.':';
 2702: 		my $answer=&ssi_with_retries($urlp, $ssi_retry_count, %answerform);
 2703: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2704: 		    $texversion=~s/(\\keephidden\{ENDOFPROBLEM})/$answer$1/;
 2705: 		} else {
 2706: 		    # If necessary, encapsulate answer in minipage:
 2707: 
 2708: 		    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2709: 		    my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 2710: 		    $title = &Apache::lonxml::latex_special_symbols($title);
 2711: 		    my $body ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2712: 		    $body.=&path_to_problem($urlp,$LaTeXwidth);
 2713: 		    $body.='\vskip 1 mm '.$answer.'\end{document}';
 2714: 		    $body = &encapsulate_minipage($body,$answerform{'problem_split'});
 2715: 		    $texversion.=$body;
 2716: 		}
 2717: 	    }
 2718: 	    $texversion = &latex_header_footer_remove($texversion);
 2719: 
 2720: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 2721: 		$texversion=&IndexCreation($texversion,$urlp);
 2722: 	    }
 2723: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 2724: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
 2725: 	    }
 2726: 	    $result.=$texversion;
 2727: 
 2728: 	} elsif ($urlp=~/\.(sequence|page)$/) {
 2729: 
 2730: 	    # header:
 2731: 
 2732: 	    $result.='\strut\newline\noindent Sequence/page '.$urlp.'\strut\newline\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\newline\noindent ';
 2733: 
 2734: 	    # IF sequence, recurse:
 2735: 
 2736: 	    if ($urlp =~ /\.sequence$/) {
 2737: 		$result .= &print_construction_sequence($urlp,
 2738: 							$helper, %form,
 2739: 							$LaTeXwidth);
 2740: 	    }
 2741: 	}
 2742: 	elsif ($urlp =~ /\.pdf$/i) {
 2743: 	    my $texversion;
 2744: 	    if ($member != 0) {
 2745: 		$texversion .= '\cleardoublepage';
 2746: 	    }
 2747: 
 2748: 	    $texversion .= &include_pdf($urlp);
 2749: 	    $texversion = &latex_header_footer_remove($texversion);
 2750: 	    if ($member != $#order) {
 2751: 		$texversion .= '\\ \cleardoublepage';
 2752: 	    }
 2753: 
 2754: 	    $result .= $texversion;
 2755: 	}
 2756:     }
 2757:     if ($helper->{VARS}->{'construction'} eq '1') {$result=~s/(\\begin\{document})/$1 \\fbox\{RANDOM SEED IS $rndseed\} /;}
 2758:     return $result;
 2759: }
 2760: 
 2761: #
 2762: #  Top level for generating print output.
 2763: #
 2764: #  May call print_resources if multiple resources will be printed.
 2765: #
 2766: #  The main driver is $selectionmade which reflects the type of print out
 2767: #  requested:
 2768: #   Value    Print type:
 2769: #   1        Print resource that's being looked at.
 2770: #   2        Print problems in a map or in a page.
 2771: #   3        Print pages in a map or resources in a page.
 2772: #   4        Print all problems  or all resources.
 2773: #   5        Print problems for seleted students.
 2774: #   6        Print selected problems from a folder.
 2775: #   7        Print print selected resources from some scope.
 2776: #   8        Print resources for selected students.
 2777: #   9        Print for anonymous CODEs
 2778: #
 2779: #BZ 5209
 2780: #   2        map_incomplete_problems_seq Print incomplete problems from the current
 2781: #            folder in student context.
 2782: #   5      map_incomplete_problems_people_seq Print incomplete problems from the
 2783: #            current folder in privileged context.
 2784: #    5      incomplete_problems_selpeople_course Print incomplete problems for
 2785: #            selected people from the entire course.
 2786: #
 2787: #   Item 101 has much the same processing as 8,
 2788: #
 2789: #  Differences:  Item 101, 102 require per-student filtering of the resource
 2790: #  set so that only the incomplete resources are printed.
 2791: #  For item 100, filtering was done at the helper level.
 2792: 
 2793: sub output_data {
 2794: 
 2795:     my ($r,$helper,$rparmhash) = @_;
 2796:     my %parmhash = %$rparmhash;
 2797:     $ssi_error = 0;		# This will be set nonzero by failing ssi's.
 2798:     $resources_printed = '';
 2799:     $font_size = $helper->{'VARS'}->{'fontsize'};
 2800:     my $print_type = $helper->{'VARS'}->{'PRINT_TYPE'}; # Allows textual simplification.
 2801:     my $do_postprocessing = 1;
 2802:     my $js = <<ENDPART;
 2803: <script type="text/javascript">
 2804:     var editbrowser;
 2805:     function openbrowser(formname,elementname,only,omit) {
 2806:         var url = '/res/?';
 2807:         if (editbrowser == null) {
 2808:             url += 'launch=1&';
 2809:         }
 2810:         url += 'catalogmode=interactive&';
 2811:         url += 'mode=parmset&';
 2812:         url += 'form=' + formname + '&';
 2813:         if (only != null) {
 2814:             url += 'only=' + only + '&';
 2815:         }
 2816:         if (omit != null) {
 2817:             url += 'omit=' + omit + '&';
 2818:         }
 2819:         url += 'element=' + elementname + '';
 2820:         var title = 'Browser';
 2821:         var options = 'scrollbars=1,resizable=1,menubar=0';
 2822:         options += ',width=700,height=600';
 2823:         editbrowser = open(url,title,options,'1');
 2824:         editbrowser.focus();
 2825:     }
 2826: </script>
 2827: ENDPART
 2828: 
 2829: 
 2830:     # Breadcrumbs
 2831:     #FIXME: Choose better/different breadcrumbs?!? Links?
 2832:     my $brcrum = [{'href' => '',
 2833:                    'text' => 'Helper'}, #FIXME: Different origin possible than print out helper?
 2834:                   {'href' => '',
 2835:                    'text' => 'Preparing Printout'}];
 2836: 
 2837:     my $start_page  = &Apache::loncommon::start_page('Preparing Printout',
 2838:                                                      $js,
 2839:                                                      {'bread_crumbs' => $brcrum,});
 2840:     my $msg = &mt('Please stand by while processing your print request, this may take some time ...');
 2841: 
 2842:     $r->print($start_page."\n<p>\n$msg\n</p>\n");
 2843: 
 2844:     # fetch the pagebreaks and store them in the course environment
 2845:     # The page breaks will be pulled into the hash %page_breaks which is
 2846:     # indexed by symb and contains 1's for each break.
 2847: 
 2848:     $env{'form.pagebreaks'}  = $helper->{'VARS'}->{'FINISHPAGE'};
 2849:     &set_form_extraspace($helper);
 2850:     $env{'form.lastprinttype'} = $print_type;
 2851:     &Apache::loncommon::store_course_settings('print',
 2852: 					      {'pagebreaks'    => 'scalar',
 2853: 					       'extraspace'    => 'scalar',
 2854: 					       'extraspace_units' => 'scalar',
 2855: 					       'lastprinttype' => 'scalar'});
 2856:     my %page_breaks  = &get_page_breaks($helper);
 2857: 
 2858:     my $format_from_helper = $helper->{'VARS'}->{'FORMAT'};
 2859:     my ($result,$selectionmade) = ('','');
 2860:     my $number_of_columns = 1; #used only for pages to determine the width of the cell
 2861:     my @temporary_array=split /\|/,$format_from_helper;
 2862:     my ($laystyle,$numberofcolumns,$papersize,$pdfFormFields)=@temporary_array;
 2863: 
 2864:     $laystyle = &map_laystyle($laystyle);
 2865:     my ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$laystyle,$numberofcolumns);
 2866:     my $assignment =  $env{'form.assignment'};
 2867:     my $LaTeXwidth=&recalcto_mm($textwidth);
 2868:     my @print_array=();
 2869:     my @student_names=();
 2870:     my $lastprinted;
 2871: 
 2872:     #  Common settings for the %form hash:
 2873:     # In some cases these settings get overridden by specific cases, but the
 2874:     # settings are common enough to make it worthwhile factoring them out
 2875:     # here.
 2876:     #
 2877:     my %form;
 2878:     $form{'grade_target'} = 'tex';
 2879:     $form{'textwidth'}    = &get_textwidth($helper, $LaTeXwidth);
 2880:     $form{'pdfFormFields'} = $pdfFormFields;
 2881: 
 2882:     # If form.showallfoils is set, then request all foils be shown:
 2883:     # privilege will be enforced both by not allowing the
 2884:     # check box selecting this option to be presnt unless it's ok,
 2885:     # and by lonresponse's priv. check.
 2886:     # The if is here because lonresponse.pm only cares that
 2887:     # showallfoils is defined, not what the value is.
 2888: 
 2889:     if ($helper->{'VARS'}->{'showallfoils'} eq "1") {
 2890: 	$form{'showallfoils'} = $helper->{'VARS'}->{'showallfoils'};
 2891:     }
 2892: 
 2893:     if ($helper->{'VARS'}->{'style_file'}=~/\w/) {
 2894: 	&Apache::lonnet::appenv({'construct.style' =>
 2895: 				$helper->{'VARS'}->{'style_file'}});
 2896:     } elsif ($env{'construct.style'}) {
 2897: 	&Apache::lonnet::delenv('construct.style');
 2898:     }
 2899: 
 2900:     if ($print_type eq 'current_document') {
 2901:       #-- single document - problem, page, html, xml, ...
 2902: 	my ($currentURL,$cleanURL);
 2903: 
 2904: 	if ($helper->{'VARS'}->{'construction'} ne '1') {
 2905:             #prints published resource
 2906: 	    $currentURL=$helper->{'VARS'}->{'postdata'};
 2907: 	    $cleanURL=&Apache::lonenc::check_decrypt($currentURL);
 2908: 	} else {
 2909: 
 2910:             #prints resource from the construction space
 2911: 	    $currentURL=$helper->{'VARS'}->{'filename'};
 2912: 	    $cleanURL=$currentURL;
 2913: 	}
 2914: 	$selectionmade = 1;
 2915: 
 2916: 	if ($cleanURL!~m|^/adm/|
 2917: 	    && $cleanURL=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm)$/) {
 2918: 	    my $rndseed=time;
 2919: 	    my $texversion='';
 2920: 	    if ($helper->{'VARS'}->{'ANSWER_TYPE'} ne 'only') {
 2921: 		my %moreenv;
 2922: 		$moreenv{'request.filename'}=$cleanURL;
 2923:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {$form{'problemtype'}='exam';}
 2924: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2925: 		$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 2926: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2927: 		$form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 2928: 		$form{'print_annotations'}=$helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 2929: 		if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') ||
 2930: 		    ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes')) {
 2931: 		    $form{'problem_split'}='yes';
 2932: 		}
 2933: 		if ($helper->{'VARS'}->{'curseed'}) {
 2934: 		    $rndseed=$helper->{'VARS'}->{'curseed'};
 2935: 		}
 2936: 		$form{'rndseed'}=$rndseed;
 2937: 		&Apache::lonnet::appenv(\%moreenv);
 2938: 
 2939: 		&Apache::lonxml::clear_problem_counter();
 2940: 
 2941: 		$resources_printed .= $currentURL.':';
 2942: 		$texversion.=&ssi_with_retries($currentURL,$ssi_retry_count, %form);
 2943: 
 2944: 		#  Add annotations if required:
 2945: 
 2946: 		&Apache::lonxml::clear_problem_counter();
 2947: 
 2948: 		&Apache::lonnet::delenv('request.filename');
 2949: 	    }
 2950: 	    # current document with answers.. no need to encap in minipage
 2951: 	    #  since there's only one answer.
 2952: 
 2953: 	    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2954: 	       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2955: 
 2956: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2957: 		$form{'grade_target'}='answer';
 2958: 		$form{'answer_output_mode'}='tex';
 2959: 		$form{'rndseed'}=$rndseed;
 2960:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {
 2961: 		    $form{'problemtype'}='exam';
 2962: 		}
 2963: 		$resources_printed .= $currentURL.':';
 2964: 		my $answer=&ssi_with_retries($currentURL,$ssi_retry_count, %form);
 2965: 		
 2966: 
 2967: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2968: 		    $texversion=~s/(\\keephidden\{ENDOFPROBLEM})/$answer$1/;
 2969: 		} else {
 2970: 		    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2971: 		    if ($helper->{'VARS'}->{'construction'} ne '1') {
 2972: 			my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 2973: 			$title = &Apache::lonxml::latex_special_symbols($title);
 2974: 			$texversion.='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2975: 			$texversion.=&path_to_problem($cleanURL,$LaTeXwidth);
 2976: 		    } else {
 2977: 			$texversion.='\vskip 0 mm \noindent\textbf{'.
 2978:                         &mt("Printing from Authoring Space: No Title").'}\vskip 0 mm ';
 2979: 
 2980: 			$texversion.=&path_to_problem($cleanURL,$LaTeXwidth);
 2981: 		    }
 2982: 		    $texversion.='\vskip 1 mm '.$answer.'\end{document}';
 2983: 		}
 2984: 
 2985: 
 2986: 		
 2987: 
 2988: 
 2989: 	    }
 2990: 	    # Print annotations.
 2991: 
 2992: 
 2993: 	    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2994: 		my $annotation .= &annotate($currentURL);
 2995: 		$texversion =~ s/(\\keephidden\{ENDOFPROBLEM})/$annotation$1/;
 2996: 	    }
 2997: 
 2998: 
 2999: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 3000: 		$texversion=&IndexCreation($texversion,$currentURL);
 3001: 	    }
 3002: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 3003: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$currentURL| \\strut\\\\\\strut /;
 3004: 
 3005: 	    }
 3006: 	    $result .= $texversion;
 3007: 	    if ($currentURL=~m/\.page\s*$/) {
 3008: 		($result,$number_of_columns) = &page_cleanup($result);
 3009: 	    }
 3010:         } elsif ($cleanURL!~m|^/adm/|
 3011: 		 && $currentURL=~/\.(sequence|page)$/ && $helper->{'VARS'}->{'construction'} eq '1') {
 3012: 	    $result .= &print_construction_sequence($currentURL, $helper, %form,
 3013: 						    $LaTeXwidth);
 3014: 	    $result .= '\end{document}';
 3015: 	    if (!($result =~ /\\begin\{document\}/)) {
 3016: 		$result = &print_latex_header() . $result;
 3017: 	    }
 3018: 	    # End construction space sequence.
 3019: 	} elsif ($cleanURL=~/\/(smppg|syllabus|aboutme|bulletinboard|ext\.tool)$/) {
 3020: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 3021: 		if ($currentURL=~/\/syllabus$/) {$currentURL=~s/\/res//;}
 3022:                 if ($currentURL=~/\/ext\.tool$/) {$currentURL=~s/^\/adm\/wrapper//;}
 3023: 		$resources_printed .= $currentURL.':';
 3024: 		my $texversion = &ssi_with_retries($currentURL, $ssi_retry_count, %form);
 3025: 		if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 3026: 		    my $annotation = &annotate($currentURL);
 3027: 		    $texversion    =~ s/(\\end\{document})/$annotation$1/;
 3028: 		}
 3029: 		$result .= $texversion;
 3030: 	} elsif ($cleanURL =~/\.tex$/) {
 3031: 	    # For this sort of print of a single LaTeX file,
 3032: 	    # We can just print the LaTeX file as it is uninterpreted in any way:
 3033: 	    #
 3034: 
 3035: 	    $result = &fetch_raw_resource($currentURL);
 3036: 	    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 3037: 		my $annotation = &annotate($currentURL);
 3038: 		$result =~ s/(\\end\{document})/$annotation$1/;
 3039: 	    }
 3040: 
 3041: 	    $do_postprocessing = 0; # Don't massage the result.
 3042: 
 3043: 	} elsif ($cleanURL =~ /\.pdf$/i) {
 3044: 	    $result .= &include_pdf($cleanURL);
 3045: 	    $result .= '\end{document}';
 3046: 	} elsif ($cleanURL =~ /\.page$/i) { #  Print page in non construction space contexts.
 3047: 
 3048: 	    # Determine the set of resources in the map of the page:
 3049: 
 3050: 	    my $navmap         =  Apache::lonnavmaps::navmap->new();
 3051: 	    my @page_resources =  $navmap->retrieveResources($cleanURL);
 3052: 	    $result           .=  &print_page_in_course($helper, $rparmhash,
 3053: 							$cleanURL, \@page_resources);
 3054: 
 3055: 
 3056: 	} else {
 3057: 	    $result.=&unsupported($currentURL,$helper->{'VARS'}->{'LATEX_TYPE'},
 3058: 				  $helper->{'VARS'}->{'symb'});
 3059: 	}
 3060:     } elsif (($print_type eq 'map_problems')          or
 3061: 	     ($print_type eq 'map_problems_in_page')  or
 3062: 	     ($print_type eq 'map_resources_in_page') or
 3063:              ($print_type eq 'map_problems_pages')    or
 3064:              ($print_type eq 'all_problems')          or
 3065: 	     ($print_type eq 'all_resources')         or # BUGBUG
 3066: 	     ($print_type eq 'select_sequences')      or
 3067: 	     ($print_type eq 'map_incomplete_problems_seq')
 3068: 	     ) {
 3069: 
 3070:         #-- produce an output string
 3071: 	if (($print_type eq 'map_problems')                or
 3072: 	    ($print_type eq 'map_incomplete_problems_seq') or
 3073: 	    ($print_type eq 'map_problems_in_page') ) {
 3074: 	    $selectionmade = 2;
 3075: 	} elsif (($print_type eq 'map_problems_pages') or
 3076: 		 ($print_type eq 'map_resources_in_page'))
 3077: 	{
 3078: 	    $selectionmade = 3;
 3079: 	} elsif (($print_type eq 'all_problems')
 3080: 		 ) {
 3081: 	    $selectionmade = 4;
 3082: 	} elsif ($print_type eq 'all_resources') {  #BUGBUG
 3083: 	    $selectionmade = 4;
 3084: 	} elsif ($print_type eq 'select_sequences') {
 3085: 	    $selectionmade = 7;
 3086: 	}
 3087: 
 3088: 	$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 3089: 	$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 3090: 	$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 3091: 	$form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 3092: 	$form{'print_annotations'} = $helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 3093: 	if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes')   ||
 3094: 	    ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') ) {
 3095: 	    $form{'problem_split'}='yes';
 3096: 	}
 3097: 	my $flag_latex_header_remove = 'NO';
 3098: 	my $flag_page_in_sequence = 'NO';
 3099: 	my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 3100: 	my $prevassignment='';
 3101: 
 3102: 	&Apache::lonxml::clear_problem_counter();
 3103: 
 3104: 	for (my $i=0;$i<=$#master_seq;$i++) {
 3105: 
 3106: 	    &Apache::lonenc::reset_enc();
 3107: 
 3108: 	    # Note due to document structure, not allowed to put \newpage
 3109: 	    # prior to the first resource
 3110: 
 3111: 	    if (defined $page_breaks{$master_seq[$i]}) {
 3112: 		if($i != 0) {
 3113: 		    $result.="\\newpage\n";
 3114: 		}
 3115: 	    }
 3116: 	    $result .= &get_extra_vspaces($helper, $master_seq[$i]);
 3117: 	    my ($sequence,$middle_thingy,$urlp)=&Apache::lonnet::decode_symb($master_seq[$i]);
 3118: 	    $urlp=&Apache::lonnet::clutter($urlp);
 3119: 	    $form{'symb'}=$master_seq[$i];
 3120: 
 3121: 	    my $assignment=&Apache::lonxml::latex_special_symbols(&Apache::lonnet::gettitle($sequence),'header'); #title of the assignment which contains this problem
 3122: 
 3123: 	    if ($selectionmade==7) {$helper->{VARS}->{'assignment'}=$assignment;}
 3124: 	    if ($i==0) {$prevassignment=$assignment;}
 3125: 	    my $texversion='';
 3126: 	    if ($urlp!~m|^/adm/|
 3127: 		&& $urlp=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 3128:                 my $extension = $1;
 3129: 		$resources_printed .= $urlp.':';
 3130: 		&Apache::lonxml::remember_problem_counter();
 3131: 		if ($flag_latex_header_remove eq 'NO') {
 3132: 		    $texversion.=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});  # RF
 3133:                     unless (($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only') ||
 3134:                             (($i==0) &&
 3135:                              (($urlp=~/\.page$/) ||
 3136:                               ($print_type eq 'map_problems_in_page') ||
 3137:                               (($print_type eq 'map_resources_in_page') && ($extension !~ /^x?html?$/))))) {
 3138:                         $flag_latex_header_remove = 'YES';
 3139:                     }
 3140: 		}
 3141: 		$texversion.=&ssi_with_retries($urlp, $ssi_retry_count, %form);
 3142: 		if ($urlp=~/\.page$/) {
 3143: 		    ($texversion,my $number_of_columns_page) = &page_cleanup($texversion);
 3144: 		    if ($number_of_columns_page > $number_of_columns) {$number_of_columns=$number_of_columns_page;}
 3145: 		    $texversion =~ s/\\end\{document}\d*/\\end{document}/;
 3146: 		    $flag_page_in_sequence = 'YES';
 3147: 		}
 3148: 
 3149: 		if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 3150: 		   ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 3151: 		    #  Don't permanently pervert the %form hash
 3152: 		    my %answerform = %form;
 3153: 		    $answerform{'grade_target'}='answer';
 3154: 		    $answerform{'answer_output_mode'}='tex';
 3155: 		    $resources_printed .= $urlp.':';
 3156: 
 3157: 		    &Apache::lonxml::restore_problem_counter();
 3158: 		    my $answer=&ssi_with_retries($urlp, $ssi_retry_count, %answerform);
 3159:                     if ($urlp =~ /\.page$/) {
 3160:                         $answer =~ s/\\end\{document}(\d*)$//;
 3161:                     }
 3162: 		    if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 3163:                         if ($urlp =~ /\.page$/) {
 3164:                             my @probs = split(/\\keephidden\{ENDOFPROBLEM}/,$texversion);
 3165:                             my $lastprob = pop(@probs);
 3166:                             $texversion = join('\keephidden{ENDOFPROBLEM}',@probs).
 3167:                             $answer.'\keephidden{ENDOFPROBLEM}'.$lastprob;
 3168:                         } else {
 3169:                             $texversion=~s/(\\keephidden\{ENDOFPROBLEM})/$answer$1/;
 3170:                         }
 3171: 		    } else {
 3172: 			if ($urlp=~/$LONCAPA::assess_page_re/) {
 3173: 			    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 3174: #			    $texversion =~ s/\\begin\{document}//; # FIXME
 3175: 			    my $title = &Apache::lonnet::gettitle($master_seq[$i]);
 3176: 			    $title = &Apache::lonxml::latex_special_symbols($title);
 3177: 			    my $body ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 3178: 			    $body   .= &path_to_problem ($urlp,$LaTeXwidth);
 3179: 			    $body   .='\vskip 1 mm '.$answer;
 3180: 			    $body    = &encapsulate_minipage($body,$answerform{'problem_split'});
 3181: 			    $texversion .= $body;
 3182: 			} else {
 3183: 			    $texversion='';
 3184: 			}
 3185: 		    }
 3186: 
 3187: 		}
 3188: 		if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 3189: 		    my $annotation .= &annotate($urlp);
 3190: 		    $texversion =~ s/(\\keephidden\{ENDOFPROBLEM})/$annotation$1/;
 3191: 		}
 3192: 
 3193: 		if ($flag_latex_header_remove ne 'NO') {
 3194: 		    $texversion = &latex_header_footer_remove($texversion);
 3195: 		} else {
 3196: 		    $texversion =~ s/\\end\{document}//;
 3197: 		}
 3198: 		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 3199: 		    $texversion=&IndexCreation($texversion,$urlp);
 3200: 		}
 3201: 		if (($selectionmade == 4) and ($assignment ne $prevassignment)) {
 3202: 		    my $name = &get_name();
 3203: 		    my $courseidinfo = &get_course();
 3204: 		    $prevassignment=$assignment;
 3205: 		    my $header_text = $parmhash{'print_header_format'};
 3206: 		    $header_text    = &format_page_header($textwidth, $header_text,
 3207: 							  $assignment,
 3208: 							  $courseidinfo,
 3209: 							  $name);
 3210: 		    if ($numberofcolumns eq '1') {
 3211: 			$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\lhead{'.$header_text.'}} \vskip 5 mm ';
 3212: 		    } else {
 3213: 			$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\fancyhead[LO]{'.$header_text.'}} \vskip 5 mm ';
 3214: 		    }			
 3215: 		}
 3216: 		$result .= $texversion;
 3217: 		$flag_latex_header_remove = 'YES';
 3218: 	    } elsif ($urlp=~/\/(smppg|syllabus|aboutme|bulletinboard|ext\.tool)$/) {
 3219: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 3220: 		if ($urlp=~/\/syllabus$/) {$urlp=~s/\/res//;}
 3221:                 if ($urlp=~/\/ext\.tool$/) {$urlp=~s/^\/adm\/wrapper//;}
 3222: 		$resources_printed .= $urlp.':';
 3223: 		my $texversion = &ssi_with_retries($urlp, $ssi_retry_count, %form);
 3224: 		if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 3225: 		    my $annotation = &annotate($urlp);
 3226: 		    $texversion =~ s/(\\end\{document)/$annotation$1/;
 3227: 		}
 3228: 
 3229: 		if ($flag_latex_header_remove ne 'NO') {
 3230: 		    $texversion = &latex_header_footer_remove($texversion);
 3231: 		} else {	
 3232: 		    $texversion =~ s/\\end\{document}/\\vskip 0\.5mm\\noindent\\makebox\[\\textwidth\/\$number_of_columns\]\[b\]\{\\hrulefill\}/;
 3233: 		}
 3234: 		$result .= $texversion;
 3235: 		$flag_latex_header_remove = 'YES';
 3236: 	    } elsif ($urlp=~ /\.pdf$/i) {
 3237: 		if ($i > 0) {
 3238: 		    $result .= '\cleardoublepage';
 3239: 		}
 3240:                 my $texfrompdf = &include_pdf($urlp);
 3241:                 if ($flag_latex_header_remove ne 'NO') {
 3242:                     $texfrompdf = &latex_header_footer_remove($texfrompdf);
 3243:                 }
 3244:                 $result .= $texfrompdf;
 3245: 		if ($i != $#master_seq) {
 3246: 		    if ($numberofcolumns eq '1') {
 3247: 			$result .= '\newpage';
 3248: 		    } else {
 3249: 			# the \\'s seem to be needed to let LaTeX know there's something
 3250: 			# on the page since LaTeX seems to not like to clear an empty page.
 3251: 			#
 3252: 			$result .= '\\ \cleardoublepage';
 3253: 		    }
 3254: 		}
 3255: 		$flag_latex_header_remove = 'YES';
 3256: 
 3257: 	    } else {
 3258: 		$texversion=&unsupported($urlp,$helper->{'VARS'}->{'LATEX_TYPE'},
 3259: 					 $master_seq[$i]);
 3260: 		if ($flag_latex_header_remove ne 'NO') {
 3261: 		    $texversion = &latex_header_footer_remove($texversion);
 3262: 		} else {
 3263: 		    $texversion =~ s/\\end\{document}//;
 3264: 		}
 3265: 		$result .= $texversion;
 3266: 		$flag_latex_header_remove = 'YES';
 3267: 	    }
 3268: 	    if (&Apache::loncommon::connection_aborted($r)) {
 3269: 		last;
 3270: 	    }
 3271: 	}
 3272: 	&Apache::lonxml::clear_problem_counter();
 3273: 	if ($flag_page_in_sequence eq 'YES') {
 3274: 	    $result =~ s/\\usepackage\{calc}/\\usepackage{calc}\\usepackage{longtable}/;
 3275: 	}	
 3276: 	$result .= '\end{document}';
 3277:      } elsif (($print_type eq 'problems_for_students')           ||
 3278: 	      ($print_type eq 'problems_for_students_from_page') ||
 3279: 	      ($print_type eq 'all_problems_students')           ||
 3280: 	      ($print_type eq 'resources_for_students')          ||
 3281: 	      ($print_type eq 'incomplete_problems_selpeople_course') ||
 3282: 	      ($print_type eq 'map_incomplete_problems_people_seq') ||
 3283:               ($print_type eq 'select_sequences_problems_for_students') ||
 3284:               ($print_type eq 'select_sequences_resources_for_students')) {
 3285: 
 3286: 
 3287:      #-- prints assignments for whole class or for selected students
 3288: 	 my $type;
 3289: 	 if (($print_type eq 'problems_for_students')           ||
 3290: 	     ($print_type eq 'problems_for_students_from_page') ||
 3291: 	     ($print_type eq 'all_problems_students')           ||
 3292: 	     ($print_type eq 'incomplete_problems_selpeople_course') ||
 3293: 	     ($print_type eq 'map_incomplete_problems_people_seq') ||
 3294:              ($print_type eq 'select_sequences_problems_for_students')) {
 3295: 	     $selectionmade=5;
 3296: 	     $type='problems';
 3297: 	 } elsif (($print_type eq 'resources_for_students') ||
 3298:                   ($print_type eq 'select_sequences_resources_for_students')) {
 3299: 	     $selectionmade=8;
 3300: 	     $type='resources';
 3301: 	 }
 3302: 	 my @students=split /\|\|\|/, $helper->{'VARS'}->{'STUDENTS'};
 3303: 	 #   The normal sort order is by section then by students within the
 3304: 	 #   section. If the helper var student_sort is 1, then the user has elected
 3305: 	 #   to override this and output the students by name.
 3306: 	 #    Each element of the students array is of the form:
 3307: 	 #       username:domain:section:last, first:status
 3308: 	 #
 3309: 	 #  Note that student sort is not compatible with printing
 3310: 	 #  1 section per pdf...so that setting overrides.
 3311: 	 #
 3312: 	 if (($helper->{'VARS'}->{'student_sort'}    eq 1)  &&
 3313: 	     ($helper->{'VARS'}->{'SPLIT_PDFS'} ne "sections")) {
 3314: 	     @students = sort compare_names  @students;
 3315: 	 } else {
 3316: 	     @students = sort compare_sections @students;
 3317: 	 }
 3318: 	 &adjust_number_to_print($helper);
 3319: 
 3320:          if ($helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq '0' ||
 3321: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq 'all' ) {
 3322: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'}=$#students+1;
 3323: 	 }
 3324: 	 # If we are splitting on section boundaries, we need
 3325: 	 # to remember that in split_on_sections and
 3326: 	 # print all of the students in the list.
 3327: 	 #
 3328: 	 my $split_on_sections = 0;
 3329: 	 if ($helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq 'section') {
 3330: 	     $split_on_sections = 1;
 3331: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'} = $#students+1;
 3332: 	 }
 3333: 	 my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 3334: 
 3335:          my $map;
 3336:          if ($helper->{VARS}->{'symb'}) {
 3337:              unless ((($print_type eq 'all_problems_students') ||
 3338:                       ($print_type eq 'incomplete_problems_selpeople_course')) &&
 3339:                       $perm{'pfo'}) {
 3340:                  ($map, my $id, my $resource) =
 3341:                      &Apache::lonnet::decode_symb($helper->{VARS}->{'symb'});
 3342:              }
 3343:          } elsif (($helper->{'VARS'}->{'postdata'} eq '/adm/navmaps') && ($perm{'pfo'})) {
 3344:              $map = $helper->{'VARS'}->{'SEQUENCE'};
 3345:          }
 3346: 
 3347: 	 #loop over students
 3348: 
 3349:  	 my $flag_latex_header_remove = 'NO';
 3350: 	 my %moreenv;
 3351:          $moreenv{'instructor_comments'}='hide';
 3352: 	 $moreenv{'textwidth'}=&get_textwidth($helper,$LaTeXwidth);
 3353: 	 $moreenv{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 3354: 	 $moreenv{'print_annotations'} = $helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 3355: 	 $moreenv{'problem_split'}    = $parmhash{'problem_stream_switch'};
 3356: 	 $moreenv{'suppress_tries'}   = $parmhash{'suppress_tries'};
 3357: 	 if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes')  ||
 3358: 	     ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes')) {
 3359: 	     $moreenv{'problem_split'}='yes';
 3360: 	 }
 3361: 	 my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$#students+1);
 3362: 	 my $student_counter=-1;
 3363: 	 my $i = 0;
 3364: 	 my $last_section = (split(/:/,$students[0]))[2];
 3365:          my $nohidemap;
 3366:          if ($perm{'pav'} && $perm{'vgr'}) {
 3367:              $nohidemap = 1;
 3368:          }
 3369: 	 foreach my $person (@students) {
 3370:              my $duefile="/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.due";
 3371: 	     if (-e $duefile) {
 3372: 		 my $temp_file = Apache::File->new('>>'.$duefile);
 3373: 		 print $temp_file "1969\n";
 3374: 	     }
 3375: 	     $student_counter++;
 3376: 	     if ($split_on_sections) {
 3377: 		 my $this_section = (split(/:/,$person))[2];
 3378: 		 if ($this_section ne $last_section) {
 3379: 		     $i++;
 3380: 		     $last_section = $this_section;
 3381: 		 }
 3382: 	     } else {
 3383: 		 $i=int($student_counter/$helper->{'VARS'}{'NUMBER_TO_PRINT'});
 3384: 	     }
 3385: 	     my $actual_seq = master_seq_to_person_seq($map, \@master_seq,
 3386:                                                        $person, undef, $nohidemap);
 3387: 	     my ($output,$fullname, $printed)=&print_resources($r,$helper,
 3388: 						     $person,$type,
 3389: 						     \%moreenv,  $actual_seq,
 3390: 						     $flag_latex_header_remove,
 3391: 						     $LaTeXwidth);
 3392: 	     $resources_printed .= ":";
 3393: 	     $print_array[$i].=$output;
 3394: 	     $student_names[$i].=$person.':'.$fullname.'_END_';
 3395: #	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,&mt('last student').' '.$fullname);
 3396: 	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 3397: 	     $flag_latex_header_remove = 'YES';
 3398:              if ($printed) {
 3399:                  $lastprinted = $fullname;
 3400:              }
 3401: 	     if (&Apache::loncommon::connection_aborted($r)) { last; }
 3402: 	 }
 3403: 	 &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3404: 	 $result .= $print_array[0].'  \end{document}';
 3405:      } elsif (($print_type eq 'problems_for_anon')      ||
 3406: 	      ($print_type eq 'problems_for_anon_page') ||
 3407: 	      ($print_type eq 'resources_for_anon')     ||
 3408:               ($print_type eq 'select_sequences_problems_for_anon') ||
 3409:               ($print_type eq 'select_sequences_resources_for_anon')) {
 3410:          $selectionmade = 9;
 3411: 	 my $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 3412: 	 my $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 3413: 	 my $num_todo=$helper->{'VARS'}->{'NUMBER_TO_PRINT_TOTAL'};
 3414: 	 my $code_name=$helper->{'VARS'}->{'ANON_CODE_STORAGE_NAME'};
 3415: 	 my $old_name=$helper->{'VARS'}->{'REUSE_OLD_CODES'};
 3416: 	 my $single_code = $helper->{'VARS'}->{'SINGLE_CODE'};
 3417: 	 my $selected_code = $helper->{'VARS'}->{'CODE_SELECTED_FROM_LIST'};
 3418: 	 my $code_option=$helper->{'VARS'}->{'CODE_OPTION'};
 3419:          my @lines = &Apache::lonnet::get_scantronformat_file();
 3420: 	 my ($code_type,$code_length,$bubbles_per_row)=('letter',6,10);
 3421: 	 foreach my $line (@lines) {
 3422:              next if (($line =~ /^\#/) || ($line eq ''));
 3423: 	     my ($name,$type,$length,$bubbles_per_item) =
 3424:                  (split(/:/,$line))[0,2,4,17];
 3425: 	     if ($name eq $code_option) {
 3426: 		 $code_length=$length;
 3427: 		 if ($type eq 'number') { $code_type = 'number'; }
 3428:                  chomp($bubbles_per_item);
 3429:                  if (($bubbles_per_item ne '') && ($bubbles_per_item > 0)) {
 3430:                      $bubbles_per_row = $bubbles_per_item;
 3431:                  }
 3432: 	     }
 3433: 	 }
 3434:          my $map;
 3435:          if ($helper->{VARS}{'symb'}) {
 3436:              ($map, my $id, my $resource) =
 3437:                  &Apache::lonnet::decode_symb($helper->{VARS}{'symb'});
 3438:          } elsif (($helper->{'VARS'}->{'postdata'} eq '/adm/navmaps') && ($perm{'pfo'})) {
 3439:              $map = $helper->{'VARS'}->{'SEQUENCE'};
 3440:          }
 3441: 	 my %moreenv = ('textwidth' => &get_textwidth($helper,$LaTeXwidth));
 3442: 	 $moreenv{'problem_split'}    = $parmhash{'problem_stream_switch'};
 3443:          $moreenv{'suppress_tries'} = $parmhash{'suppress_tries'};
 3444:          $moreenv{'instructor_comments'}='hide';
 3445:          $moreenv{'bubbles_per_row'} = $bubbles_per_row;
 3446: 	 my $seed=time+($$<<16)+($$);
 3447: 	 my @allcodes;
 3448: 	 if ($old_name) {
 3449: 	     my %result=&Apache::lonnet::get('CODEs',
 3450: 					     [$old_name,"type\0$old_name"],
 3451: 					     $cdom,$cnum);
 3452: 	     $code_type=$result{"type\0$old_name"};
 3453: 	     @allcodes=split(',',$result{$old_name});
 3454: 	     $num_todo=scalar(@allcodes);
 3455: 	 } elsif ($selected_code) { # Selection value is always numeric.
 3456: 	     $num_todo = 1;
 3457: 	     @allcodes = ($selected_code);
 3458: 	 } elsif ($single_code) {
 3459: 
 3460: 	     $num_todo    = 1;	# Unconditionally one code to do.
 3461: 	     # If an alpha code have to convert to numbers so it can be
 3462: 	     # converted back to letters again :-)
 3463: 	     #
 3464: 	     if ($code_type ne 'number') {
 3465: 		 $single_code = &letters_to_num($single_code);
 3466: 	     }
 3467: 	     @allcodes = ($single_code);
 3468: 	 } else {
 3469: 	     my %allcodes;
 3470: 	     srand($seed);
 3471: 	     for (my $i=0;$i<$num_todo;$i++) {
 3472: 		 $moreenv{'CODE'}=&get_CODE(\%allcodes,$i,$seed,$code_length,
 3473: 					    $code_type);
 3474: 	     }
 3475:              $code_name =~ s/^\s+//;
 3476:              $code_name =~ s/\s+$//;
 3477: 	     if ($code_name) {
 3478: 		 &Apache::lonnet::put('CODEs',
 3479: 				      {
 3480: 					$code_name =>join(',',keys(%allcodes)),
 3481: 					"type\0$code_name" => $code_type
 3482: 				      },
 3483: 				      $cdom,$cnum);
 3484: 	     }
 3485: 	     @allcodes=keys(%allcodes);
 3486: 	 }
 3487: 	 my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 3488: 	 my ($type) = split(/_/,$print_type);
 3489: 	 &adjust_number_to_print($helper);
 3490: 	 my $number_per_page=$helper->{'VARS'}->{'NUMBER_TO_PRINT'};
 3491: 	 if ($number_per_page eq '0' || $number_per_page eq 'all'
 3492: 	     || $number_per_page eq 'section') {
 3493: 	     $number_per_page=$num_todo > 0 ? $num_todo : 1;
 3494: 	 }
 3495: 	 my $flag_latex_header_remove = 'NO';
 3496: 	 my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$num_todo);
 3497: 	 my $count=0;
 3498:          my $nohidemap;
 3499:          if ($perm{'pav'} && $perm{'vgr'}) {
 3500:              $nohidemap = 1;
 3501:          }
 3502: 	 foreach my $code (sort(@allcodes)) {
 3503: 	     my $file_num=int($count/$number_per_page);
 3504: 	     if ($code_type eq 'number') {
 3505: 		 $moreenv{'CODE'}=$code;
 3506: 	     } else {
 3507: 		 $moreenv{'CODE'}=&num_to_letters($code);
 3508: 	     }
 3509:              $env{'form.CODE'} = $moreenv{'CODE'};
 3510:              my $actual_seq = master_seq_to_person_seq($map, \@master_seq,
 3511:                                                        undef,
 3512:                                                        $moreenv{'CODE'}, $nohidemap);
 3513:              delete($env{'form.CODE'});
 3514: 	     my ($output,$fullname, $printed)=
 3515: 		 &print_resources($r,$helper,'anonymous',$type,\%moreenv,
 3516: 				  $actual_seq,$flag_latex_header_remove,
 3517: 				  $LaTeXwidth);
 3518: 	     $resources_printed .= ":";
 3519: 	     $print_array[$file_num].=$output;
 3520: 	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 3521: 				       &mt('last assignment').' '.$fullname);
 3522: 	     $flag_latex_header_remove = 'YES';
 3523: 	     $count++;
 3524:              if ($printed) {
 3525:                  $lastprinted = $fullname;
 3526:              }
 3527: 	     if (&Apache::loncommon::connection_aborted($r)) { last; }
 3528: 	 }
 3529: 	 &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3530: 	 $result .= $print_array[0].'  \end{document}';
 3531:      } elsif ($print_type eq 'problems_from_directory') {
 3532:     #prints selected problems from the subdirectory
 3533: 	$selectionmade = 6;
 3534:         my @list_of_files=split /\|\|\|/, $helper->{'VARS'}->{'FILES'};
 3535: 	@list_of_files=sort @list_of_files;
 3536: 	my $flag_latex_header_remove = 'NO';
 3537: 	my $rndseed=time;
 3538: 	if ($helper->{'VARS'}->{'curseed'}) {
 3539: 	    $rndseed=$helper->{'VARS'}->{'curseed'};
 3540: 	}
 3541: 	for (my $i=0;$i<=$#list_of_files;$i++) {
 3542: 
 3543: 	    &Apache::lonenc::reset_enc();
 3544: 
 3545: 	    my $urlp = $list_of_files[$i];
 3546: 	    $urlp=~s|//|/|;
 3547: 	    if ($urlp=~/\//) {
 3548: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 3549: 		$form{'rndseed'}=$rndseed;
 3550: 		$urlp =~ s|^$Apache::lonnet::perlvar{'lonDocRoot'}||;
 3551: 		$resources_printed .= $urlp.':';
 3552: 		my $texversion=&ssi_with_retries($urlp, $ssi_retry_count, %form);
 3553: 		if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 3554: 		   ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 3555: 		    #  Don't permanently pervert %form:
 3556: 		    my %answerform = %form;
 3557: 		    $answerform{'grade_target'}='answer';
 3558: 		    $answerform{'answer_output_mode'}='tex';
 3559: 		    $answerform{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 3560: 		    $answerform{'rndseed'}=$rndseed;
 3561: 		    $resources_printed .= $urlp.':';
 3562: 		    my $answer=&ssi_with_retries($urlp, $ssi_retry_count, %answerform);
 3563: 		    if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 3564: 			$texversion=~s/(\\keephidden\{ENDOFPROBLEM})/$answer$1/;
 3565: 		    } else {
 3566: 			$texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 3567: 			if ($helper->{'VARS'}->{'construction'} ne '1') {
 3568: 			    $texversion.='\vskip 0 mm \noindent ';
 3569: 			    $texversion.=&path_to_problem ($urlp,$LaTeXwidth);
 3570: 			} else {
 3571: 			    $texversion.='\vskip 0 mm \noindent\textbf{'.
 3572:                                          &mt("Printing from Authoring Space: No Title").'}\vskip 0 mm ';
 3573: 			    $texversion.=&path_to_problem ($urlp,$LaTeXwidth);
 3574: 			}
 3575: 			$texversion.='\vskip 1 mm '.$answer.'\end{document}';
 3576: 		    }
 3577: 		}
 3578:                 #this chunk is responsible for printing the path to problem
 3579: 
 3580: 		my $newurlp=&path_to_problem($urlp,$LaTeXwidth);
 3581: 		$texversion =~ s/(\\begin\{minipage}\{\\textwidth})/$1 $newurlp/;
 3582: 		if ($flag_latex_header_remove ne 'NO') {
 3583: 		    $texversion = &latex_header_footer_remove($texversion);
 3584: 		} else {
 3585: 		    $texversion =~ s/\\end\{document}//;
 3586: 		}
 3587: 		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 3588: 		    $texversion=&IndexCreation($texversion,$urlp);
 3589: 		}
 3590: 		if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 3591: 		    $texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
 3592: 
 3593: 		}
 3594: 		$result .= $texversion;
 3595: 	    }
 3596: 	    $flag_latex_header_remove = 'YES';
 3597: 	}
 3598: 	if ($helper->{VARS}->{'construction'} eq '1') {$result=~s/(\\typeout)/ RANDOM SEED IS $rndseed $1/;}
 3599: 	$result .= '\end{document}';      	
 3600:     }
 3601: #-------------------------------------------------------- corrections for the different page formats
 3602: 
 3603:     # Only post process if that has not been turned off e.g. by a raw latex resource.
 3604: 
 3605:     if ($do_postprocessing) {
 3606:         my $mostrecent;
 3607:         if ((($selectionmade == 5) || ($selectionmade == 8) || ($selectionmade == 9)) &&
 3608:             (($numberofcolumns == 1) || ($laystyle eq 'album' && $papersize eq 'a4'))) {
 3609:             $mostrecent = $lastprinted;
 3610:         }
 3611: 	$result = &page_format_transformation($papersize,
 3612: 					      $laystyle,$numberofcolumns,
 3613: 					      $print_type,$result,
 3614: 					      $helper->{VARS}->{'assignment'},
 3615: 					      $helper->{'VARS'}->{'TABLE_CONTENTS'},
 3616: 					      $helper->{'VARS'}->{'TABLE_INDEX'},
 3617: 					      $selectionmade,$mostrecent);
 3618: 	$result = &latex_corrections($number_of_columns,$result,$selectionmade,
 3619: 				     $helper->{'VARS'}->{'ANSWER_TYPE'});
 3620: 	#if ($numberofcolumns == 1) {
 3621: 	$result =~ s/\\textwidth\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\textwidth= $helper->{'VARS'}->{'pagesize.width'} $helper->{'VARS'}->{'pagesize.widthunit'} /;
 3622: 	$result =~ s/\\textheight\s*=?\s*-?\d*\.?\d*\s*(cm|mm|in)/\\textheight $helper->{'VARS'}->{'pagesize.height'} $helper->{'VARS'}->{'pagesize.heightunit'} /;
 3623: 	$result =~ s/\\evensidemargin\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\evensidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
 3624: 	$result =~ s/\\oddsidemargin\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\oddsidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
 3625: 	#}
 3626:     }
 3627: 
 3628:     # Set URLback so we can provide a link back to the resource and to change options.
 3629:     # (Since the browser back button does not currently work with https,
 3630:     # the back link is useful even when there is an easy-to-miss LON-CAPA back button.)
 3631: 
 3632:     my $URLback=''; #link to original document
 3633:     if ($helper->{'VARS'}->{'construction'} eq '1') {
 3634: 	$URLback=$helper->{'VARS'}->{'filename'};
 3635:     } elsif ($helper->{VARS}{'symb'}) {
 3636:         my ($map, $id, $url) = &Apache::lonnet::decode_symb($helper->{VARS}{'symb'});
 3637:         my $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 3638:         my $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 3639:         my ($anchor,$usehttp,$plainurl);
 3640:         $url = &Apache::lonnet::clutter($url);
 3641:         $plainurl = $url;
 3642:         if (($ENV{'SERVER_PORT'} == 443) && ($env{'request.course.id'}) &&
 3643:             (($url =~ m{^\Q/public/$cdom/$cnum/syllabus\E($|\?)}) ||
 3644:              ($url =~ m{^\Q/adm/wrapper/ext/\E(?!https:)}))) {
 3645:             unless ((&Apache::lonnet::uses_sts()) || (&Apache::lonnet::waf_allssl())) {
 3646:                 $usehttp = 1;
 3647:             }
 3648:         }
 3649:         if ($env{'request.enc'}) {
 3650:             $url = &Apache::lonenc::encrypted($url);
 3651:         }
 3652:         if ($url ne '') {
 3653:             my $symb = $helper->{VARS}{'symb'};
 3654:             if ($url =~ m{^\Q/adm/wrapper/ext/\E}) {
 3655:                 my $link = $url;
 3656:                 ($link,$anchor) = ($url =~ /^([^\#]+)(?:|(\#[^\#]+))$/);
 3657:                 if ($anchor) {
 3658:                     ($symb) = ($helper->{VARS}{'symb'} =~ /^([^\#]+)/);
 3659:                 }
 3660:                 $url = $link;
 3661:             }
 3662:             $URLback = $url;
 3663:             if ($usehttp) {
 3664:                 $URLback .= (($URLback =~ /\?/) ? '&amp;':'?').'usehttp=1';
 3665:             }
 3666:             unless ($plainurl =~ /\.page$/) {
 3667:                 $URLback .= (($URLback =~ /\?/) ? '&amp;':'?').'symb='.&escape($symb.$anchor);
 3668:             }
 3669:         }
 3670:     } elsif (($helper->{VARS}->{'postdata'} eq '/adm/navmaps') &&
 3671:              ($env{'request.course.id'})) {
 3672:         $URLback=$helper->{VARS}->{'postdata'};
 3673:     }
 3674:     #
 3675:     # Final adjustment of the font size:
 3676:     #
 3677: 
 3678:     $result = set_font_size($result);
 3679: 
 3680:     # Insert any babel headers required.
 3681: 
 3682:     $result       = &collect_languages($result);
 3683: 
 3684: 
 3685: #-- writing .tex file in prtspool
 3686:     my $temp_file;
 3687:     my $identifier = &Apache::loncommon::get_cgi_id();
 3688:     my $filename = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout_$identifier.tex";
 3689:     if (!($#print_array>0)) {
 3690:        unless ($temp_file = Apache::File->new('>'.$filename)) {
 3691: 	  $r->log_error("Couldn't open $filename for output $!");
 3692: 	  return SERVER_ERROR;
 3693:        }
 3694:        print $temp_file $result;
 3695:        my $begin=index($result,'\begin{document}',0);
 3696:        my $inc=substr($result,0,$begin+16);
 3697:     } else {
 3698:        my $begin=index($result,'\begin{document}',0);
 3699:        my $inc=substr($result,0,$begin+16);
 3700:        for (my $i=0;$i<=$#print_array;$i++) {
 3701: 	  if ($i==0) {
 3702: 	      $print_array[$i]=$result;
 3703: 	  } else {
 3704: 	      $print_array[$i].='\end{document}';
 3705: 	      $print_array[$i] =
 3706: 		&latex_corrections($number_of_columns,$print_array[$i],
 3707: 				   $selectionmade,
 3708: 				   $helper->{'VARS'}->{'ANSWER_TYPE'});
 3709: 
 3710: 	      my $anobegin=index($print_array[$i],'\setcounter{page}',0);
 3711: 	      substr($print_array[$i],0,$anobegin)='';
 3712: 	      $print_array[$i]=$inc.$print_array[$i];
 3713: 	  }
 3714: 	  my $temp_file;
 3715: 	  my $newfilename=$filename;
 3716: 	  my $num=$i+1;
 3717: 	  $newfilename =~s/\.tex$//;
 3718: 	  $newfilename=sprintf("%s_%03d.tex",$newfilename, $num);
 3719: 	  unless ($temp_file = Apache::File->new('>'.$newfilename)) {
 3720: 	      $r->log_error("Couldn't open $newfilename for output $!");
 3721: 	      return SERVER_ERROR;
 3722: 	  }
 3723: 	  print $temp_file $print_array[$i];
 3724:        }
 3725:     }
 3726:     my $student_names='';
 3727:     if ($#print_array>0) {
 3728:         for (my $i=0;$i<=$#print_array;$i++) {
 3729:   	  $student_names.=$student_names[$i].'_ENDPERSON_';
 3730: 	}
 3731:     } else {
 3732: 	if ($#student_names>-1) {
 3733: 	   $student_names=$student_names[0].'_ENDPERSON_';
 3734: 	} else {
 3735:            my $fullname = &get_name($env{'user.name'},$env{'user.domain'});
 3736: 	   $student_names=join(':',$env{'user.name'},$env{'user.domain'},
 3737: 				    $env{'request.course.sec'},$fullname).
 3738: 					'_ENDPERSON_'.'_END_';
 3739: 	}
 3740:      }
 3741: 	
 3742:      # logic for now is too complex to trace if this has been defined
 3743:      #  yet.
 3744:      my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3745:      my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3746:      &Apache::lonnet::appenv({'cgi.'.$identifier.'.file'   => $filename,
 3747: 				'cgi.'.$identifier.'.layout'  => $laystyle,
 3748: 				'cgi.'.$identifier.'.numcol'  => $numberofcolumns,
 3749: 				'cgi.'.$identifier.'.paper'  => $papersize,
 3750: 				'cgi.'.$identifier.'.selection' => $selectionmade,
 3751: 				'cgi.'.$identifier.'.tableofcontents' => $helper->{'VARS'}->{'TABLE_CONTENTS'},
 3752: 				'cgi.'.$identifier.'.tableofindex' => $helper->{'VARS'}->{'TABLE_INDEX'},
 3753: 				'cgi.'.$identifier.'.role' => $perm{'pav'},
 3754: 				'cgi.'.$identifier.'.numberoffiles' => $#print_array,
 3755: 				'cgi.'.$identifier.'.studentnames' => $student_names,
 3756: 				'cgi.'.$identifier.'.backref' => &escape($URLback),});
 3757:     &Apache::lonnet::appenv({"cgi.$identifier.user"    => $env{'user.name'},
 3758: 				"cgi.$identifier.domain"  => $env{'user.domain'},
 3759: 				"cgi.$identifier.courseid" => $cnum,
 3760: 				"cgi.$identifier.coursedom" => $cdom,
 3761: 				"cgi.$identifier.resources" => $resources_printed});
 3762: 	
 3763:     my $end_page = &Apache::loncommon::end_page();
 3764:     my $continue_text = &mt('Continue');
 3765:     # If there's been an unrecoverable SSI error, report it to the user
 3766:     if ($ssi_error) {
 3767:         my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
 3768:         $r->print('<br /><p class="LC_error">'.&mt('An unrecoverable network error occurred:').'</p><p>'.
 3769:                   &mt('At least one of the resources you chose to print could not be rendered due to an unrecoverable error when communicating with a server:').
 3770:                   '<br />'.$ssi_last_error_resource.'<br />'.$ssi_last_error.
 3771:                   '</p><p>'.&mt('You can continue using the link provided below, but make sure to carefully inspect your output file! The errors will be marked in the file.').'<br />'.
 3772:                   &mt('You may be able to reprint the individual resources for which this error occurred, as the issue may be temporary.').
 3773:                   '<br />'.&mt('If the error persists, please contact the [_1] for assistance.',$helpurl).'</p><p>'.
 3774:                   &mt('We apologize for the inconvenience.').'</p>'.
 3775:                   '<a href="/cgi-bin/printout.pl?'.$identifier.'">'.$continue_text.'</a>'.$end_page);
 3776:     } else {
 3777: 	$r->print(<<FINALEND);
 3778: <br />
 3779: <meta http-equiv="Refresh" content="0; url=/cgi-bin/printout.pl?$identifier" />
 3780: <a href="/cgi-bin/printout.pl?$identifier">$continue_text</a>
 3781: $end_page
 3782: FINALEND
 3783:     }                                     # endif ssi errors.
 3784: }
 3785: 
 3786: 
 3787: sub get_CODE {
 3788:     my ($all_codes,$num,$seed,$size,$type)=@_;
 3789:     my $max='1'.'0'x$size;
 3790:     my $newcode;
 3791:     while(1) {
 3792: 	$newcode=sprintf("%0".$size."d",int(rand($max)));
 3793: 	if (!exists($$all_codes{$newcode})) {
 3794: 	    $$all_codes{$newcode}=1;
 3795: 	    if ($type eq 'number' ) {
 3796: 		return $newcode;
 3797: 	    } else {
 3798: 		return &num_to_letters($newcode);
 3799: 	    }
 3800: 	}
 3801:     }
 3802: }
 3803: 
 3804: sub print_resources {
 3805:     my ($r,$helper,$person,$type,$moreenv,$master_seq,$remove_latex_header,
 3806: 	$LaTeXwidth)=@_;
 3807:     my $current_output = '';
 3808:     my $printed = '';
 3809:     my ($username,$userdomain,$usersection) = split /:/,$person;
 3810:     my $fullname = &get_name($username,$userdomain);
 3811:     my $namepostfix = "\\\\";	# Both anon and not anon should get the same vspace.
 3812: 
 3813: 
 3814:     #
 3815:     # Figure out if we need to filter the output by
 3816:     # the incomplete problems for that person
 3817:     #
 3818:     my $print_type = $helper->{'VARS'}->{'PRINT_TYPE'};
 3819:     my $print_incomplete = 0;
 3820:     if (($print_type eq 'map_incomplete_problems_people_seq')   ||
 3821: 	($print_type eq 'incomplete_problems_selpeople_course')) {
 3822: 	$print_incomplete = 1;
 3823:     }
 3824:     if ($person eq 'anonymous') {
 3825: 	$namepostfix .=&mt('Name:')." ";
 3826: 	$fullname = "CODE - ".$moreenv->{'CODE'};
 3827:     }
 3828: 
 3829:     #  Fullname may have special latex characters that need \ prefixing:
 3830:     #
 3831: 
 3832:     my $i           = 0;
 3833:     my $actually_printed = 0;	# Count of resources printed.
 3834:     #goes through all resources, checks if they are available for
 3835:     #current student, and produces output
 3836: 
 3837:     &Apache::lonxml::clear_problem_counter();
 3838:     my %page_breaks  = &get_page_breaks($helper);
 3839:     my $columns_in_format = (split(/\|/,$helper->{'VARS'}->{'FORMAT'}))[1];
 3840:     #
 3841:     #   end each student with a
 3842:     #   Special that allows the post processor to even out the page
 3843:     #   counts later.  Nasty problem this... it would be really
 3844:     #   nice to put the special in as a postscript comment
 3845:     #   e.g. \special{ps:\ENDOFSTUDENTSTAMP}  unfortunately,
 3846:     #   The special gets passed the \ and dvips puts it in the output file
 3847:     #   so we will just rely on printout.pl to strip ENDOFSTUDENTSTAMP from the
 3848:     #   postscript.  Each ENDOFSTUDENTSTAMP will go on a line by itself.
 3849:     #
 3850: 
 3851:     my $syllabus_first = 0;
 3852:     my $current_assignment = "";
 3853:     my $assignment;
 3854:     my $courseidinfo = &get_course();
 3855:     my $possprint = scalar(@{$master_seq});
 3856: 
 3857:     foreach my $curresline (@{$master_seq})  {
 3858: 	if (defined $page_breaks{$curresline}) {
 3859: 	    if($i != 0) {
 3860: 		$current_output.= "\\newpage\n";
 3861: 	    }
 3862: 	}
 3863: 	$current_output .= &get_extra_vspaces($helper, $curresline);
 3864: 	$i++;
 3865: 	my ($map,$id,$res_url) = &Apache::lonnet::decode_symb($curresline);
 3866: 
 3867: 	# See if we need to emit a new header:
 3868: 
 3869: 	if ( !($type eq 'problems' &&
 3870: 	       ($curresline!~ m/$LONCAPA::assess_page_re/)) ) {
 3871: 	    if ($print_incomplete && !&incomplete($username, $userdomain, $usersection, $res_url)) {
 3872: 		next;
 3873: 	    }
 3874: 	    $actually_printed++; # we're going to print one.
 3875: 
 3876: 	    if (&Apache::lonnet::allowed('bre',$res_url)) {
 3877: 		if ($res_url!~m|^ext/|
 3878: 		    && $res_url=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 3879: 		    $printed .= $curresline.':';
 3880: 		    &Apache::lonxml::remember_problem_counter();
 3881: 
 3882: 		    my $rendered = &get_student_view_with_retries($curresline,$ssi_retry_count,$username,$userdomain,$env{'request.course.id'},'tex',$moreenv);
 3883:                     if ($res_url =~ /\.page$/) {
 3884:                         if ($remove_latex_header eq 'NO') {
 3885:                             if (!($rendered =~ /\\begin\{document\}/)) {
 3886:                                 $rendered = &print_latex_header().$rendered;
 3887:                             }
 3888:                         }
 3889:                         if ($remove_latex_header eq 'YES') {
 3890:                             $rendered = &latex_header_footer_remove($rendered);
 3891:                         } else {
 3892:                             $rendered =~ s/\\end\{document}\d*//;
 3893:                         }
 3894:                     }
 3895: 		    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 3896: 		       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 3897: 			#   Use a copy of the hash so we don't pervert it on future loop passes.
 3898: 			my %answerenv = %{$moreenv};
 3899: 			$answerenv{'answer_output_mode'}='tex';
 3900: 
 3901: 
 3902: 			$answerenv{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 3903: 
 3904: 			&Apache::lonxml::restore_problem_counter();
 3905: 
 3906: 			my $ansrendered = &Apache::loncommon::get_student_answers($curresline,$username,$userdomain,$env{'request.course.id'},%answerenv);
 3907: 
 3908: 			if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 3909: 			    $rendered=~s/(\\keephidden\{ENDOFPROBLEM})/$ansrendered$1/;
 3910: 			} else {
 3911: 			    my $header =&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 3912:                             unless ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only') {
 3913:                                 $header =~ s/\\begin\{document}//;     #<<<<<
 3914:                             }
 3915: 			    my $title = &Apache::lonnet::gettitle($curresline);
 3916: 			    $title = &Apache::lonxml::latex_special_symbols($title);
 3917: 			    my $body   ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 3918: 			    $body     .=&path_to_problem($res_url,$LaTeXwidth);
 3919: 			    $body     .='\vskip 1 mm '.$ansrendered;
 3920: 			    $body     = &encapsulate_minipage($body,$answerenv{'problem_split'});
 3921: 			    $rendered = $header.$body;
 3922: 			}
 3923: 		    }
 3924: 		    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 3925: 			my $url = &Apache::lonnet::clutter($res_url);
 3926: 			my $annotation = &annotate($url);
 3927: 			$rendered =~  s/(\\keephidden\{ENDOFPROBLEM})/$annotation$1/;
 3928: 		    }
 3929: 		    my $junk;
 3930: 		    if ($remove_latex_header eq 'YES') {
 3931: 			$rendered = &latex_header_footer_remove($rendered);
 3932: 		    } else {
 3933: 			$rendered =~ s/\\end\{document}//;
 3934: 		    }
 3935: 		    $current_output .= $rendered;
 3936: 		} elsif ($res_url=~/\/(smppg|syllabus|aboutme|bulletinboard|ext\.tool)$/) {
 3937: 		    if ($i == 1) {
 3938: 			$syllabus_first = 1;
 3939: 		    }
 3940: 		    $printed .= $curresline.':';
 3941: 		    my $rendered = &get_student_view_with_retries($curresline,$ssi_retry_count,$username,$userdomain,$env{'request.course.id'},'tex',$moreenv);
 3942: 		    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 3943: 			my $url = &Apache::lonnet::clutter($res_url);
 3944: 			my $annotation = &annotate($url);
 3945: 			$annotation    =~ s/(\\end\{document})/$annotation$1/;
 3946: 		    }
 3947: 		    if ($remove_latex_header eq 'YES') {
 3948: 			$rendered = &latex_header_footer_remove($rendered);
 3949: 		    } else {
 3950: 			$rendered =~ s/\\end\{document}//;
 3951: 		    }
 3952: 		    $current_output .= $rendered.'\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\strut \vskip 0 mm \strut ';
 3953: 		} elsif($res_url =~ /\.pdf$/) {
 3954: 		    my $url = &Apache::lonnet::clutter($res_url);
 3955: 		    my $rendered  = &include_pdf($url);
 3956: 		    if ($remove_latex_header ne 'NO') {
 3957: 			$rendered = &latex_header_footer_remove($rendered);
 3958: 		    }
 3959: 		    $current_output .= $rendered;
 3960: 		} else {
 3961: 		    my $rendered = &unsupported($res_url,$helper->{'VARS'}->{'LATEX_TYPE'},$curresline);
 3962: 		    if ($remove_latex_header ne 'NO') {
 3963: 			$rendered = &latex_header_footer_remove($rendered);
 3964: 		    } else {
 3965: 			$rendered =~ s/\\end\{document}//;
 3966: 		    }
 3967: 		    $current_output .= $rendered;
 3968: 		}
 3969: 	    }
 3970: 	    $remove_latex_header = 'YES';
 3971: 	}
 3972: 	$assignment = &Apache::lonxml::latex_special_symbols(
 3973: 	    &Apache::lonnet::gettitle($map), 'header');
 3974: 	if (($assignment ne $current_assignment) && ($assignment ne "")) {
 3975: 	    my $header_line = &format_page_header($LaTeXwidth, $parmhash{'print_header_format'},
 3976: 						  $assignment, $courseidinfo,
 3977: 						  $fullname, $usersection);
 3978: 	    my $header_start = ($columns_in_format == 1) ? '\lhead'
 3979: 		: '\fancyhead[LO]';
 3980: 	    $header_line = $header_start.'{'.$header_line.'}';
 3981: 	    $current_output = $current_output . $header_line;
 3982: 	    $current_assignment = $assignment;
 3983: 	}
 3984: 
 3985: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 3986:     }
 3987:     # If we are printing incomplete it's possible we don't have
 3988:     # anything to print.  The print subsystem is not so good at handling
 3989:     # that so we're going to generate a stub that says there are no
 3990:     # incomplete resources for the person.
 3991:     #
 3992: 
 3993:     if ($actually_printed == 0) {
 3994:         my $message = &mt('No resources to print');
 3995:         if (!$possprint) {
 3996:             if ($perm{'pav'} || $perm{'pfo'}) {
 3997:                 $message = &mt('There are no unhidden resources to print.')."\n\n".
 3998:                            &mt('The most likely reason is one of the following: ')."\n".
 3999:                            '\begin{itemize}'."\n".
 4000:                            '\item '.&mt("The 'Resource hidden from students' parameter is set for the folder being printed.")."\n".
 4001:                            '\item '.&mt("'Hidden' is checked in the Course Editor individually for each resource in the folder being printed.")."\n".
 4002:                            '\end{itemize}'."\n\n".
 4003:                            &mt("Note: to print a bubblesheet exam which you want to hide from students, ".
 4004:                                "use the Course Editor to check the 'Hidden' checkbox for the exam folder itself.")."\n";
 4005:             }
 4006:         } elsif ($print_incomplete) {
 4007:             $message = &mt('No incomplete resources');
 4008:         }
 4009:         if ($message) {
 4010: 	    $current_output  = &encapsulate_minipage("\\vskip -10mm \n$message\n \\vskip 100 mm { }\n",$moreenv->{'problem_split'});
 4011:         }
 4012: 	if ($remove_latex_header eq "NO") {
 4013: 	    $current_output = &print_latex_header() . $current_output;
 4014: 	} else {
 4015: 	    $current_output = &latex_header_footer_remove($current_output);
 4016: 	}
 4017:     }
 4018: 
 4019:     if ($syllabus_first) {
 4020:         $current_output =~ s/\\\\ Last updated:/Last updated:/
 4021:     }
 4022:     my $currentassignment=&Apache::lonxml::latex_special_symbols($helper->{VARS}->{'assignment'},'header');
 4023:     my $header_line =
 4024:     &format_page_header($LaTeXwidth, $parmhash{'print_header_format'},
 4025:                         $currentassignment, $courseidinfo, $fullname, $usersection);
 4026:     my $header_start = ($columns_in_format == 1) ? '\lhead' : '\fancyhead[LO]';
 4027:     my $newheader = $header_start.'{'.$header_line.'}';
 4028:     if ($current_output=~/\\documentclass/) {
 4029: 	$current_output =~ s/\\begin\{document}/\\setlength{\\topmargin}{1cm} \\begin{document}\\noindent\\parbox{\\minipagewidth}{\\noindent$newheader$namepostfix}\\vskip 5 mm /;
 4030: 
 4031:     } else {
 4032: 	my $blankpages =
 4033: 	    '\clearpage\strut\clearpage'x$helper->{'VARS'}->{'EMPTY_PAGES'};
 4034: 	
 4035: 	$current_output = '\strut\vspace*{-6 mm}\\newline'.
 4036: 	    &copyright_line().' \newpage '.$blankpages.$end_of_student.
 4037: 	    '\setcounter{page}{1}\noindent\parbox{\minipagewidth}{\noindent'.
 4038: 	    $newheader.$namepostfix. '} \vskip 5 mm '.$current_output;
 4039: 
 4040:     }
 4041:     #
 4042:     #  Close the student bracketing.
 4043:     #
 4044:     return ($current_output,$fullname, $printed);
 4045: 
 4046: }
 4047: 
 4048: sub printing_blocked {
 4049:     my ($r,$blocktext) = @_;
 4050:     my $title = &mt('Preparing Printout');
 4051:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4052:     &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/printout',
 4053:                                             text=> $title});
 4054:     my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs($title);
 4055:     &Apache::loncommon::content_type($r,'text/html');
 4056:     &Apache::loncommon::no_cache($r);
 4057:     $r->send_http_header;
 4058:     $r->print(&Apache::loncommon::start_page('Preparing Printout').
 4059:               $breadcrumbs.
 4060:               $blocktext.
 4061:               &Apache::loncommon::end_page());
 4062:     return;
 4063: }
 4064: 
 4065: sub handler {
 4066: 
 4067:     my $r = shift;
 4068: 
 4069:     if ($env{'request.course.id'}) {
 4070:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4071:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4072:         my $clientip = &Apache::lonnet::get_requestor_ip($r);
 4073:         my ($blocked,$blocktext) =
 4074:             &Apache::loncommon::blocking_status('printout',$clientip,$cnum,$cdom);
 4075:         if ($blocked) {
 4076:             my $checkrole = "cm./$cdom/$cnum";
 4077:             if ($env{'request.course.sec'} ne '') {
 4078:                 $checkrole .= "/$env{'request.course.sec'}";
 4079:             }
 4080:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4081:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 4082:                 &printing_blocked($r,$blocktext);
 4083:                 return OK;
 4084:             }
 4085:         }
 4086:     }
 4087: 
 4088:     &init_perm();
 4089:     my $helper = printHelper($r);
 4090:     if (!ref($helper)) {
 4091: 	return $helper;
 4092:     }
 4093: 
 4094: 
 4095:     %parmhash=&Apache::lonnet::coursedescription($env{'request.course.id'});
 4096: 
 4097:     #  If a figure conversion queue file exists for this user.domain
 4098:     # we delete it since it can only be bad (if it were good, printout.pl
 4099:     # would have deleted it the last time around.
 4100: 
 4101:     my $conversion_queuefile = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.dat";
 4102:     if(-e $conversion_queuefile) {
 4103: 	unlink $conversion_queuefile;
 4104:     }
 4105: 
 4106:     &output_data($r,$helper,\%parmhash);
 4107:     return OK;
 4108: }
 4109: 
 4110: use Apache::lonhelper;
 4111: 
 4112: sub addMessage {
 4113:     my $text = shift;
 4114:     my $paramHash = Apache::lonhelper::getParamHash();
 4115:     $paramHash->{MESSAGE_TEXT} = $text;
 4116:     Apache::lonhelper::message->new();
 4117: }
 4118: 
 4119: 
 4120: 
 4121: sub init_perm {
 4122:     undef(%perm);
 4123:     $perm{'pav'}=&Apache::lonnet::allowed('pav',$env{'request.course.id'});
 4124:     if (!$perm{'pav'}) {
 4125: 	$perm{'pav'}=&Apache::lonnet::allowed('pav',
 4126: 		  $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 4127:     }
 4128:     $perm{'pfo'}=&Apache::lonnet::allowed('pfo',$env{'request.course.id'});
 4129:     if (!$perm{'pfo'}) {
 4130: 	$perm{'pfo'}=&Apache::lonnet::allowed('pfo',
 4131: 		  $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 4132:     }
 4133:     $perm{'vgr'}=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 4134:     if (!$perm{'vgr'}) {
 4135:         $perm{'vgr'}=&Apache::lonnet::allowed('vgr',
 4136:                    $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 4137:     }
 4138: }
 4139: 
 4140: sub get_randomly_ordered_warning {
 4141:     my ($helper,$map) = @_;
 4142: 
 4143:     my $message;
 4144: 
 4145:     my $postdata = $env{'form.postdata'} || $helper->{VARS}{'postdata'};
 4146:     my $navmap = Apache::lonnavmaps::navmap->new();
 4147:     if (defined($navmap)) {
 4148:         my $res = $navmap->getResourceByUrl($map);
 4149:         if ($res) {
 4150: 	    my $func =
 4151: 	        sub { return ($_[0]->is_map() && $_[0]->randomorder); };
 4152: 	    my @matches = $navmap->retrieveResources($res, $func,1,1,1);
 4153: 
 4154:         }
 4155:     } else {
 4156:         $message = "Retrieval of information about ordering of resources failed.";
 4157:         return '<message type="warning">'.$message.'</message>';
 4158:     }
 4159:     return;
 4160: }
 4161: 
 4162: sub printHelper {
 4163:     my $r = shift;
 4164: 
 4165:     if ($r->header_only) {
 4166:         if ($env{'browser.mathml'}) {
 4167:             &Apache::loncommon::content_type($r,'text/xml');
 4168:         } else {
 4169:             &Apache::loncommon::content_type($r,'text/html');
 4170:         }
 4171:         $r->send_http_header;
 4172:         return OK;
 4173:     }
 4174: 
 4175:     # Send header, nocache
 4176:     if ($env{'browser.mathml'}) {
 4177:         &Apache::loncommon::content_type($r,'text/xml');
 4178:     } else {
 4179:         &Apache::loncommon::content_type($r,'text/html');
 4180:     }
 4181:     &Apache::loncommon::no_cache($r);
 4182:     $r->send_http_header;
 4183:     $r->rflush();
 4184: 
 4185:     # Unfortunately, this helper is so complicated we have to
 4186:     # write it by hand
 4187: 
 4188:     Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
 4189: 
 4190:     my $helper = Apache::lonhelper::helper->new("Printing Helper");
 4191:     $helper->declareVar('symb');
 4192:     $helper->declareVar('postdata');
 4193:     $helper->declareVar('curseed');
 4194:     $helper->declareVar('probstatus');
 4195:     $helper->declareVar('filename');
 4196:     $helper->declareVar('construction');
 4197:     $helper->declareVar('assignment');
 4198:     $helper->declareVar('style_file');
 4199:     $helper->declareVar('student_sort');
 4200:     $helper->declareVar('FINISHPAGE');
 4201:     $helper->declareVar('PRINT_TYPE');
 4202:     $helper->declareVar("showallfoils");
 4203:     $helper->declareVar("STUDENTS");
 4204:     $helper->declareVar("EXTRASPACE");
 4205: 
 4206: 
 4207: 
 4208: 
 4209:     #  The page breaks and extra spaces
 4210:     #  can get loaded initially from the course environment:
 4211:     # But we only do this in the initial state so that they are allowed to change.
 4212:     #
 4213: 
 4214: 
 4215:     &Apache::loncommon::restore_course_settings('print',
 4216: 						{'pagebreaks'  => 'scalar',
 4217: 						 'extraspace'  => 'scalar',
 4218: 						 'extraspace_units' => 'scalar',
 4219: 					         'lastprinttype' => 'scalar'});
 4220: 
 4221:     # This will persistently load in the data we want from the
 4222:     # very first screen.
 4223: 
 4224:     if($helper->{VARS}->{PRINT_TYPE} eq $env{'form.lastprinttype'}) {
 4225: 	if (!defined ($env{"form.CURRENT_STATE"})) {
 4226: 
 4227: 	    $helper->{VARS}->{FINISHPAGE} = $env{'form.pagebreaks'};
 4228: 	    $helper->{VARS}->{EXTRASPACE} = $env{'form.extraspace'};
 4229: 	    $helper->{VARS}->{EXTRASPACE_UNITS} = $env{'form.extraspace_units'};
 4230: 	} else {
 4231: 	    my $state = $env{"form.CURRENT_STATE"};
 4232: 	    if ($state eq "START") {
 4233: 		$helper->{VARS}->{FINISHPAGE} = $env{'form.pagebreaks'};
 4234: 		$helper->{VARS}->{EXTRASPACE} = $env{'form.extraspace'};
 4235: 		$helper->{VARS}->{EXTRASPACE_UNITS} = $env{'form.extraspace_units'};
 4236: 		
 4237: 	    }
 4238: 	}
 4239:     }
 4240: 
 4241:     # Detect whether we're coming from construction space
 4242:     if ($env{'form.postdata'}=~m{^/priv}) {
 4243:         $helper->{VARS}->{'filename'} = $env{'form.postdata'};
 4244:         $helper->{VARS}->{'construction'} = 1;
 4245:     } else {
 4246:         if ($env{'form.postdata'}) {
 4247:             unless ($env{'form.postdata'} eq '/adm/navmaps') {
 4248:                 $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($env{'form.postdata'});
 4249:             }
 4250: 	    if ( $helper->{VARS}->{'symb'} eq '') {
 4251: 		$helper->{VARS}->{'postdata'} = $env{'form.postdata'};
 4252: 	    }
 4253:         }
 4254:         if ($env{'form.symb'}) {
 4255:             $helper->{VARS}->{'symb'} = $env{'form.symb'};
 4256:         }
 4257:         if ($env{'form.url'}) {
 4258:             unless ($env{'form.url'} eq '/adm/navmaps') {
 4259:                 $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($helper->{VARS}->{'postdata'});
 4260:             }
 4261:         }
 4262:     }
 4263: 
 4264:     if ($helper->{VARS}->{'symb'} ne '') {
 4265:         $helper->{VARS}->{'symb'}=
 4266: 	    &Apache::lonenc::check_encrypt($helper->{VARS}->{'symb'});
 4267:     }
 4268:     my ($resourceTitle,$sequenceTitle,$mapTitle,$cdom,$cnum);
 4269:     if ($helper->{VARS}->{'postdata'} eq '/adm/navmaps') {
 4270:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4271:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4272:         if ($env{'course.'.$env{'request.course.id'}.'.url'} eq
 4273:             "uploaded/$cdom/$cnum/default.sequence") {
 4274:             my $navmap = Apache::lonnavmaps::navmap->new();
 4275:             if (ref($navmap)) {
 4276:                 my @toplevelres = $navmap->retrieveResources('',sub { !(($_[0]->is_map()) || ($_[0]->src =~ /^\/adm\/navmaps/)) },0,0);
 4277:                 if (@toplevelres) {
 4278:                     my @printable;
 4279:                     if ($perm{'pav'} || $perm{'pfo'}) {
 4280:                         @printable = @toplevelres;
 4281:                     } else {
 4282:                         @printable = $navmap->retrieveResources(undef,sub { $_[0]->resprintable() },0,1);
 4283:                     }
 4284:                     if (@printable) {
 4285:                         $sequenceTitle = 'Main Content';
 4286:                         $mapTitle = $sequenceTitle;
 4287:                     }
 4288:                 }
 4289:             }
 4290:         }
 4291:     } else {
 4292:         ($resourceTitle,$sequenceTitle,$mapTitle) = &details_for_menu($helper);
 4293:     }
 4294:     if ($sequenceTitle ne '') {$helper->{VARS}->{'assignment'}=$sequenceTitle;}
 4295: 
 4296:     # Extract map
 4297:     my $symb = $helper->{VARS}->{'symb'};
 4298:     my ($map, $id, $url);
 4299:     my $subdir;
 4300:     my $is_published=0;		# True when printing from resource space.
 4301:     my $res_printable = 1;	# By default the current resource is printable.
 4302:     my $res_error;
 4303:     my $userCanPrint = ($perm{'pav'} || $perm{'pfo'});
 4304:     my $res_printstartdate;
 4305:     my $res_printenddate;
 4306:     my $map_open = 0;
 4307:     my $map_close = 0xffffffff;
 4308:     my $course_open = 0;
 4309:     my $course_close = 0xffffffff;
 4310: 
 4311:     # Get the resource name from construction space
 4312:     if ($helper->{VARS}->{'construction'}) {
 4313:         $resourceTitle = substr($helper->{VARS}->{'filename'},
 4314:                                 rindex($helper->{VARS}->{'filename'}, '/')+1);
 4315:         $subdir = substr($helper->{VARS}->{'filename'},
 4316:                          0, rindex($helper->{VARS}->{'filename'}, '/') + 1);
 4317:     } else {
 4318: 	# From course space:
 4319: 
 4320: 	if ($symb ne '') {
 4321: 	    ($map, $id, $url) = &Apache::lonnet::decode_symb($symb);
 4322: 	    $helper->{VARS}->{'postdata'} =
 4323: 		&Apache::lonenc::check_encrypt(&Apache::lonnet::clutter($url));
 4324:         } elsif (($helper->{VARS}->{'postdata'} eq '/adm/navmaps') &&
 4325:                 ($env{'request.course.id'} ne '')) {
 4326:             if ($env{'course.'.$env{'request.course.id'}.'.url'} eq
 4327:                 "uploaded/$cdom/$cnum/default.sequence") {
 4328:                 $map = $env{'course.'.$env{'request.course.id'}.'.url'};
 4329:                 $url = $helper->{VARS}->{'postdata'};
 4330:             }
 4331:         }
 4332:         if (($symb ne '') || ($map ne '')) {
 4333:             if (!$userCanPrint) {
 4334: 	        my $navmap = Apache::lonnavmaps::navmap->new();
 4335:                 if (ref($navmap)) {
 4336:                     my $res;
 4337:                     if ($symb ne '') {
 4338: 	                $res = $navmap->getBySymb($symb);
 4339:                     } elsif ($map ne '') {
 4340:                         $res = $navmap->getResourceByUrl($map);
 4341:                     }
 4342:                     if (ref($res)) {
 4343: 	                $res_printable = $res->resprintable(); #printability in course context
 4344: 	                ($res_printstartdate, $res_printenddate) = &get_print_dates($res);
 4345: 	                ($course_open, $course_close) = &course_print_dates($res);
 4346: 	                ($map_open, $map_close) = &map_print_dates($res);
 4347:                     } else {
 4348:                         $res_error = 1;
 4349:                     }
 4350:                 } else {
 4351:                     $res_error = 1;
 4352:                 }
 4353:             }
 4354: 	} else {
 4355: 	    # Resource space.
 4356: 
 4357: 	    $url = $helper->{VARS}->{'postdata'};
 4358: 	    $is_published=1;	# From resource space.
 4359: 	}
 4360: 	$url = &Apache::lonnet::clutter($url);
 4361:         if (!$resourceTitle) { # if the resource doesn't have a title, use the filename
 4362:             my $postdata = $helper->{VARS}->{'postdata'};
 4363:             $resourceTitle = substr($postdata, rindex($postdata, '/') + 1);
 4364:         }
 4365:         if (($url eq '/adm/navmaps') && ($map eq $env{'course.'.$env{'request.course.id'}.'.url'})) {
 4366:             $res_printable=0;
 4367:         } else {
 4368:             $subdir = &Apache::lonnet::filelocation("", $url);
 4369:         }
 4370: 
 4371: 
 4372:     }
 4373:     if (!$helper->{VARS}->{'curseed'} && $env{'form.curseed'}) {
 4374: 	$helper->{VARS}->{'curseed'}=$env{'form.curseed'};
 4375:     }
 4376: 
 4377:     if (!$helper->{VARS}->{'probstatus'} && $env{'form.problemtype'}) {
 4378: 	$helper->{VARS}->{'probstatus'}=$env{'form.problemstatus'};
 4379:     }
 4380: 
 4381:     my $userCanSeeHidden = Apache::lonnavmaps::advancedUser();
 4382: 
 4383:     Apache::lonhelper::registerHelperTags();
 4384: 
 4385:     # "Delete everything after the last slash."
 4386:     $subdir =~ s|/[^/]+$||;
 4387: 
 4388:     # What can be printed is a very dynamic decision based on
 4389:     # lots of factors. So we need to dynamically build this list.
 4390:     # To prevent security leaks, states are only added to the wizard
 4391:     # if they can be reached, which ensures manipulating the form input
 4392:     # won't allow anyone to reach states they shouldn't have permission
 4393:     # to reach.
 4394: 
 4395:     # printChoices is tracking the kind of printing the user can
 4396:     # do, and will be used in a choices construction later.
 4397:     # In the meantime we will be adding states and elements to
 4398:     # the helper by hand.
 4399:     my $printChoices = [];
 4400:     my $paramHash;
 4401: 
 4402:     # If there is a current resource and it is printable
 4403:     # Give that as a choice.
 4404: 
 4405:     if ($resourceTitle && $res_printable) {
 4406:         push(@{$printChoices}, ["<b><i>$resourceTitle</i></b> (".&mt('the resource you just saw on the screen').")", 'current_document', 'PAGESIZE']);
 4407:     }
 4408: 
 4409:     # Useful filter strings
 4410: 
 4411:     my $isPrintable = ' && $res->resprintable()';
 4412: 
 4413:     my $isProblem = '(($res->is_problem()||$res->contains_problem() ||$res->is_practice()))';
 4414:     $isProblem .= $isPrintable unless $userCanPrint;
 4415:     $isProblem .= ' && !$res->randomout()' if !$userCanSeeHidden;
 4416:     my $isProblemOrMap = '($res->is_problem() || $res->contains_problem() || $res->is_sequence() || $res->is_practice())';
 4417:     $isProblemOrMap .= $isPrintable unless $userCanPrint;
 4418:     my $isNotMap = '(!$res->is_sequence())';
 4419:     $isNotMap .= $isPrintable unless $userCanPrint;
 4420:     $isNotMap .= ' && !$res->randomout()' if !$userCanSeeHidden;
 4421:     my $isMap = '$res->is_map()';
 4422:     $isMap .= $isPrintable unless $userCanPrint;
 4423:     my $symbFilter = '$res->shown_symb() ';
 4424:     my $urlValue = '$res->link()';
 4425: 
 4426:     $helper->declareVar('SEQUENCE');
 4427: 
 4428:     # If we're in a sequence...
 4429: 
 4430:     my $start_new_option;
 4431:     if ($perm{'pav'}) {
 4432: 	$start_new_option =
 4433: 	    "<option text='".&mt('Start new page[_1]before selected','<br />').
 4434: 	    "' variable='FINISHPAGE' />".
 4435: 	    "<option text='".&mt('Extra space[_1]before selected','<br />').
 4436: 	    "' variable='EXTRASPACE' type='text' />" .
 4437: 	    "<option " .
 4438: 	    "' variable='POSSIBLE_RESOURCES' type='hidden' />".
 4439: 	    "<option text='".&mt('Space units[_1]check for mm','<br />').
 4440: 	    "' variable='EXTRASPACE_UNITS' type='checkbox' />"
 4441: 	    ;
 4442:     }
 4443: 
 4444:     # If not construction space user can print the components of a page:
 4445: 
 4446:     my $page_ispage;
 4447:     my $page_title;
 4448:     if (!$helper->{VARS}->{'construction'}) {
 4449: 	my $varspostdata = $helper->{VARS}->{'postdata'};
 4450: 	my $varsassignment = $helper->{VARS}->{'assignment'};
 4451: 	my $page_navmap         = Apache::lonnavmaps::navmap->new();
 4452: 	if (defined($page_navmap)) {
 4453: 	    my @page_resources      = $page_navmap->retrieveResources($url);
 4454: 	    if(defined($page_resources[0])) {
 4455: 		$page_ispage       = $page_resources[0]->is_page();
 4456: 		$page_title     = $page_resources[0]->title();
 4457: 		my $resourcesymb   = $page_resources[0]->symb();
 4458: 		my ($pagemap, $pageid, $pageurl) = &Apache::lonnet::decode_symb($symb);
 4459: 		if ($page_ispage) {
 4460: 		    push(@{$printChoices},
 4461: 		    [&mt('Selected [_1]Problems[_2] from page [_3]', '<b>', '</b>', '<b><i>'.$page_title.'</i></b>'),
 4462: 		     'map_problems_in_page',
 4463: 		     'CHOOSE_PROBLEMS_PAGE']);
 4464: 		    push(@{$printChoices},
 4465: 		    [&mt('Selected [_1]Resources[_2] from page [_3]', '<b>', '</b>', '<b><i>'.$page_title.'</i></b>'),
 4466: 		     'map_resources_in_page',
 4467: 		     'CHOOSE_RESOURCES_PAGE']);
 4468: 		}
 4469:         my $helperFragment = &generate_resource_chooser('CHOOSE_PROBLEMS_PAGE',
 4470: 							'Select Problem(s) to print',
 4471: 							"multichoice='1' toponly='1' addstatus='1' closeallpages='1' modallink='1'",
 4472: 							'RESOURCES',
 4473: 							'PAGESIZE',
 4474: 							$url,
 4475: 							$isProblem, '',  $symbFilter,
 4476: 							$start_new_option);
 4477: 
 4478: 
 4479:       $helperFragment .= &generate_resource_chooser('CHOOSE_RESOURCES_PAGE',
 4480: 						    'Select Resource(s) to print',
 4481: 						    'multichoice="1" toponly="1" addstatus="1" closeallpages="1" modallink="1" suppressNavmap="1"',
 4482: 						    'RESOURCES',
 4483: 						    'PAGESIZE',
 4484: 						    $url,
 4485: 						    $isNotMap, '', $symbFilter,
 4486: 						    $start_new_option);
 4487: 
 4488: 
 4489: 
 4490: 
 4491: 
 4492: 	&Apache::lonxml::xmlparse($r, 'helper', $helperFragment);
 4493: 	
 4494: 	    }
 4495: 	}
 4496:     }
 4497: 
 4498:     if (($helper->{'VAR'}->{'construction'} ne '1' ) &&
 4499: 	$helper->{VARS}->{'postdata'} &&
 4500: 	$helper->{VARS}->{'assignment'}) {
 4501: 
 4502: 	# BZ 5209 - Print incomplete problems from sequence:
 4503: 	# the exact form of this depends on whether or not we are privileged or a mere
 4504: 	# plebe of s student:
 4505: 
 4506:         my $optionText    = '';
 4507: 	my $printSelector = 'map_incomplete_problems_seq';
 4508: 	my $nextState     = 'CHOOSE_INCOMPLETE_SEQ';
 4509: 	my $textSuffix    = '';
 4510:         my $nocurrloc = '';
 4511:         if ($helper->{VARS}->{'postdata'} eq '/adm/navmaps') {
 4512:             $nocurrloc = 1;
 4513:         }
 4514: 
 4515: 	if ($userCanPrint)  {
 4516: 	    $printSelector = 'map_incomplete_problems_people_seq';
 4517: 	    $nextState     = 'CHOOSE_INCOMPLETE_PEOPLE_SEQ';
 4518: 	    $textSuffix    = ' for selected students';
 4519: 	    my $helperStates =
 4520: 		&create_incomplete_folder_selstud_helper($helper, $map, $nocurrloc);
 4521: 	    &Apache::lonxml::xmlparse($r, 'helper', $helperStates);
 4522: 	} else {
 4523: 	    if (&printable($map_open, $map_close)) {
 4524: 		my $helperStates = &create_incomplete_folder_helper($helper, $map, $nocurrloc); # Create needed states for student.
 4525: 		&Apache::lonxml::xmlparse($r, 'helper', $helperStates);
 4526: 	    } else {
 4527: 		# TODO: Figure out how to break the news...this folder is not printable.
 4528: 	    }
 4529: 	}
 4530: 
 4531: 	if ($userCanPrint || &printable($map_open, $map_close)) {
 4532:             if ($helper->{VARS}->{'postdata'} eq '/adm/navmaps') {
 4533:                 $optionText = &mt('Selected [_1]Incomplete Problems[_2] [_3]not in a folder[_4]' . $textSuffix,
 4534:                                   '<b>','</b>','<i>','</i>');
 4535:             } else {
 4536:                 $optionText = &mt('Selected [_1]Incomplete Problems[_2] from folder [_3]' . $textSuffix,
 4537:                                   '<b>','</b>','<b><i>'.$sequenceTitle.'</b></i>');
 4538:             }
 4539: 	    push(@{$printChoices},
 4540: 		 [$optionText,
 4541: 		  $printSelector,
 4542: 		  $nextState]);
 4543: 	}
 4544:         # Allow problems from sequence
 4545: 	if ($userCanPrint || &printable($map_open, $map_close)) {
 4546:             if ($helper->{VARS}->{'postdata'} eq '/adm/navmaps') {
 4547:                 $optionText = &mt('Selected [_1]Problems[_2] [_3]not in a folder[_4]','<b>','</b>','<i>','</i>');
 4548:             } else {
 4549:                 $optionText = &mt('Selected [_1]Problems[_2] from folder [_3]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>');
 4550:             }
 4551: 	    push(@{$printChoices},
 4552: 	    [$optionText,
 4553: 	     'map_problems',
 4554: 	     'CHOOSE_PROBLEMS']);
 4555: 	    # Allow all resources from sequence
 4556:             if ($helper->{VARS}->{'postdata'} eq '/adm/navmaps') {
 4557:                 $optionText = &mt('Selected [_1]Resources[_2] [_3]not in a folder[_4]','<b>','</b>','<i>','</i>');
 4558:             } else {
 4559:                 $optionText = &mt('Selected [_1]Resources[_2] from folder [_3]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>');
 4560:             }
 4561: 	    push(@{$printChoices}, [$optionText,
 4562: 				    'map_problems_pages',
 4563: 				    'CHOOSE_PROBLEMS_HTML']);
 4564: 	    my $helperFragment = &generate_resource_chooser('CHOOSE_PROBLEMS',
 4565: 							    'Select Problem(s) to print',
 4566: 							    'multichoice="1" toponly="1" addstatus="1" closeallpages="1" modallink="1" nocurrloc="'.$nocurrloc.'"',
 4567: 							    'RESOURCES',
 4568: 							    'PAGESIZE',
 4569: 							    $map,
 4570: 							    $isProblem, '',
 4571: 							    $symbFilter,
 4572: 							    $start_new_option);
 4573: 	    $helperFragment .= &generate_resource_chooser('CHOOSE_PROBLEMS_HTML',
 4574: 							  'Select Resource(s) to print',
 4575: 							  'multichoice="1" toponly="1" addstatus="1" closeallpages="1" modallink="1" nocurrloc="'.$nocurrloc.'" suppressNavmap="1"',
 4576: 							  'RESOURCES',
 4577: 							  'PAGESIZE',
 4578: 							  $map,
 4579: 							  $isNotMap, '',
 4580: 							  $symbFilter,
 4581: 							  $start_new_option);
 4582: 
 4583: 	    &Apache::lonxml::xmlparse($r, 'helper', $helperFragment);
 4584: 	} else {
 4585: 	    # TODO: Figure out how to tell them the folder is not printable.
 4586: 	}
 4587:     }
 4588: 	# If the user has pfo (print for others) allow them to print all
 4589: 	# problems and resources  in the entire course, optionally for selected students
 4590: 	my $post_data = $helper->{VARS}->{'postdata'};
 4591: 
 4592:     if ($perm{'pfo'} &&  !$is_published  &&
 4593:         ($post_data=~/\/res\// || $post_data =~/\/(syllabus|smppg|aboutme|bulletinboard)$/)) {
 4594: 
 4595: 	# BZ 5209 - incomplete problems from entire course:
 4596: 
 4597: 	push(@{$printChoices},
 4598: 	     [&mt('Selected [_1]Incomplete Problems[_2] from [_3]entire course[_4] for [_5]selected people[_6]',
 4599:               '<b>','</b>','<b>','</b>','<b>','</b>'),
 4600: 	      'incomplete_problems_selpeople_course', 'INCOMPLETE_PROBLEMS_COURSE_RESOURCES']);
 4601: 	my $helperFragment = &create_incomplete_course_helper($helper); # Create needed states.
 4602: 
 4603: 	&Apache::lonxml::xmlparse($r, 'helper', $helperFragment);
 4604: 
 4605: 	#  Selected problems/resources from entire course:
 4606: 
 4607:         push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from [_3]entire course[_4]','<b>','</b>','<b>','</b>'), 'all_problems', 'ALL_PROBLEMS']);
 4608: 	push(@{$printChoices}, [&mt('Selected [_1]Resources[_2] from [_3]entire course[_4]','<b>','</b>','<b>','</b>'), 'all_resources', 'ALL_RESOURCES']);
 4609: 	push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from [_3]entire course[_4] for [_5]selected people[_6]','<b>','</b>','<b>','</b>','<b>','</b>'), 'all_problems_students', 'ALL_PROBLEMS_STUDENTS']);
 4610: my $suffixXml = <<ALL_PROBLEMS;
 4611:   <state name="STUDENTS1" title="Select People">
 4612:       <message><b>Select sorting order of printout</b> </message>
 4613:     <choices variable='student_sort'>
 4614:       <choice computer='0'>Sort by section then student</choice>
 4615:       <choice computer='1'>Sort by students across sections.</choice>
 4616:     </choices>
 4617:       <message><br /><hr /><br /> </message>
 4618:       <student multichoice='1' variable="STUDENTS" nextstate="PRINT_FORMATTING" coursepersonnel="1"/>
 4619:   </state>
 4620: ALL_PROBLEMS
 4621:          &Apache::lonxml::xmlparse($r, 'helper',
 4622: 				   &generate_resource_chooser('ALL_PROBLEMS',
 4623: 							      'Select Problem(s) to print',
 4624: 							      'multichoice="1" suppressEmptySequences="0" addstatus="1" closeallpages="1" modallink="1"',
 4625: 							      'RESOURCES',
 4626: 							      'PAGESIZE',
 4627: 							      '',
 4628: 							      $isProblemOrMap, $isNotMap,
 4629: 							      $symbFilter,
 4630: 							      $start_new_option) .
 4631: 				   &generate_resource_chooser('ALL_RESOURCES',
 4632: 							      'Select Resource(s) to print',
 4633: 							      'toponly="0" multichoice="1" suppressEmptySequences="0" addstatus="1" closeallpages="1" modallink="1" suppressNavmap="1"',
 4634: 							      'RESOURCES',
 4635: 							      'PAGESIZE',
 4636: 							      '',
 4637: 							      $isNotMap,'',$symbFilter,
 4638: 							      $start_new_option) .
 4639: 				   &generate_resource_chooser('ALL_PROBLEMS_STUDENTS',
 4640: 							      'Select Problem(s) to print',
 4641: 							      'toponly="0" multichoice="1" suppressEmptySequences="0" addstatus="1" closeallpages="1" modallink="1"',
 4642: 							      'RESOURCES',
 4643: 							      'STUDENTS1',
 4644: 							      '',
 4645: 							      $isProblemOrMap,'' , $symbFilter,
 4646: 							      $start_new_option) .
 4647: 				     $suffixXml
 4648: 				   );
 4649: 
 4650: 	if ($helper->{VARS}->{'assignment'}) {
 4651: 
 4652: 	    # If we were looking at a page, allow a selection of problems from the page
 4653: 	    # either for selected students or for coded assignments.
 4654: 
 4655: 	    if ($page_ispage) {
 4656: 		push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from page [_3] for [_4]selected people[_5]',
 4657: 					    '<b>', '</b>', '<b><i>'.$page_title.'</i></b>', '<b>', '</b>'),
 4658: 					'problems_for_students_from_page', 'CHOOSE_TGT_STUDENTS_PAGE']);
 4659: 		push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from page [_3] for [_4]CODEd assignments[_5]',
 4660: 					    '<b>', '</b>', '<b><i>'.$page_title.'</i></b>', '<b>', '</b>'),
 4661: 					'problems_for_anon_page', 'CHOOSE_ANON1_PAGE']);
 4662: 	    }
 4663: 	    push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from folder [_3] for [_4]selected people[_5]',
 4664: 					'<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'),
 4665: 				    'problems_for_students', 'CHOOSE_STUDENTS']);
 4666: 	    push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from folder [_3] for [_4]CODEd assignments[_5]',
 4667: 					'<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'),
 4668: 				    'problems_for_anon', 'CHOOSE_ANON1']);
 4669: 	}
 4670: 
 4671:         my ($randomly_ordered_warning,$codechoice,$code_selection,$namechoice) =
 4672:             &generate_common_choosers($r,$helper,$map,$url,$isProblem,$symbFilter,$start_new_option);
 4673: 
 4674: 	if ($helper->{VARS}->{'assignment'}) {
 4675: 
 4676: 	    # Assignment printing:
 4677: 
 4678: 	    push(@{$printChoices}, [&mt('Selected [_1]Resources[_2] from folder [_3] for [_4]selected people[_5]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'), 'resources_for_students', 'CHOOSE_STUDENTS1']);
 4679: 	    push(@{$printChoices}, [&mt('Selected [_1]Resources[_2] from folder [_3] for [_4]CODEd assignments[_5]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'), 'resources_for_anon', 'CHOOSE_ANON2']);
 4680: 	}
 4681: 
 4682:         # resource_selector will hold a few states that:
 4683:         #   - Allow resources to be selected for printing.
 4684:         #   - Determine pagination between assignments.
 4685:         #   - Determine how many assignments should be bundled into a single PDF.
 4686:         # TODO:
 4687:         #    Probably good to do things like separate this up into several vars, each
 4688:         #    with one state, and use REGEXPs at inclusion time to set state names
 4689:         #    and next states for better mix and match capability
 4690:         #
 4691: 
 4692: 	my $resource_selector=<<RESOURCE_SELECTOR;
 4693:     <state name="SELECT_RESOURCES" title="Select Resources">
 4694:     $randomly_ordered_warning
 4695:     <nextstate>PRINT_FORMATTING</nextstate>
 4696:     <message><br /><big><i><b>Select resources for the assignment</b></i></big><br /></message>
 4697:     <resource variable="RESOURCES" multichoice="1" addstatus="1"
 4698:               closeallpages="1" modallink="1">
 4699:       <filterfunc>return $isNotMap;</filterfunc>
 4700:       <mapurl>$map</mapurl>
 4701:       <valuefunc>return $symbFilter;</valuefunc>
 4702:       $start_new_option
 4703:       </resource>
 4704:     </state>
 4705: RESOURCE_SELECTOR
 4706: 
 4707:         $resource_selector .= &generate_format_selector($helper,
 4708:                                                         'Format of the print job',
 4709:                                                         'PRINT_FORMATTING');
 4710: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_STUDENTS1);
 4711:   <state name="CHOOSE_STUDENTS1" title="Select Students and Resources">
 4712:     <choices variable='student_sort'>
 4713:       <choice computer='0'>Sort by section then student</choice>
 4714:       <choice computer='1'>Sort by students across sections.</choice>
 4715:     </choices>
 4716:     <message><br /><hr /><br /></message>
 4717:     <student multichoice='1' variable="STUDENTS" nextstate="SELECT_RESOURCES" coursepersonnel="1" />
 4718: 
 4719:     </state>
 4720:     $resource_selector
 4721: CHOOSE_STUDENTS1
 4722: 
 4723: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_ANON2);
 4724:   <state name="CHOOSE_ANON2" title="Select CODEd Assignments">
 4725:     <nextstate>SELECT_RESOURCES</nextstate>
 4726:     <message><h4>Fill out one of the forms below</h4></message>
 4727:     <message><br /><hr /> <br /></message>
 4728:     <message><h3>Generate new CODEd Assignments</h3></message>
 4729:     <message><table><tr><td><b>Number of CODEd assignments to print:</b></td><td></message>
 4730:     <string variable="NUMBER_TO_PRINT_TOTAL" maxlength="5" size="5"  noproceed="1">
 4731:        <validator>
 4732: 	if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) < 1) &&
 4733: 	    !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                &&
 4734: 	    !\$helper->{'VARS'}{'SINGLE_CODE'}                   &&
 4735: 	    !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 4736: 	    return "You need to specify the number of assignments to print";
 4737: 	}
 4738:         if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) >= 1)  &&
 4739:              (\$helper->{'VARS'}{'SINGLE_CODE'} ne '') ) {
 4740:             return 'Specifying number of codes to print and a specific code is not compatible';
 4741:         }
 4742: 	return undef;
 4743:        </validator>
 4744:     </string>
 4745:     <message></td></tr><tr><td></message>
 4746:     <message><b>Names to save the CODEs under for later:</b></message>
 4747:     <message></td><td></message>
 4748:     <string variable="ANON_CODE_STORAGE_NAME" maxlength="50" size="20" />
 4749:     <message></td></tr><tr><td></message>
 4750:     <message><b>Bubblesheet type:</b></message>
 4751:     <message></td><td></message>
 4752:     <dropdown variable="CODE_OPTION" multichoice="0" allowempty="0">
 4753:     $codechoice
 4754:     </dropdown>
 4755:     <message></td></tr><tr><td></table></message>
 4756:     <message><br /><hr /><h3>Print a Specific CODE </h3><br /><table></message>
 4757:     <message><tr><td><b>Enter a CODE to print:</b></td><td></message>
 4758:     <string variable="SINGLE_CODE" size="10">
 4759:         <validator>
 4760: 	   if(!\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}           &&
 4761: 	      !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                 &&
 4762: 	      !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 4763: 	      return &Apache::lonprintout::is_code_valid(\$helper->{'VARS'}{'SINGLE_CODE'},
 4764: 						      \$helper->{'VARS'}{'CODE_OPTION'});
 4765: 	  } elsif (\$helper->{'VARS'}{'SINGLE_CODE'} ne ''){
 4766: 	      return 'Specifying a code name is incompatible specifying number of codes.';
 4767: 	   } else {
 4768: 	       return undef;	# Other forces control us.
 4769: 	   }
 4770:         </validator>
 4771:     </string>
 4772:     <message></td></tr><tr><td></message>
 4773:         $code_selection
 4774:     <message></td></tr></table></message>
 4775:     <message><hr /><h3>Reprint a Set of Saved CODEs</h3><table><tr><td></message>
 4776:     <message><b>Select saved CODEs:</b></message>
 4777:     <message></td><td></message>
 4778:     <dropdown variable="REUSE_OLD_CODES">
 4779:         $namechoice
 4780:     </dropdown>
 4781:     <message></td></tr></table></message>
 4782:   </state>
 4783:     $resource_selector
 4784: CHOOSE_ANON2
 4785:     }
 4786: 
 4787:     # FIXME: That RE should come from a library somewhere.
 4788:     if (($perm{'pav'}
 4789:         && ($subdir ne '')
 4790: 	&& $subdir ne $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'
 4791: 	&& (defined($helper->{'VARS'}->{'construction'})
 4792: 	    ||
 4793: 	    (&Apache::lonnet::allowed('bre',$subdir) eq 'F'
 4794: 	     &&
 4795: 	     $helper->{VARS}->{'postdata'}=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)/)
 4796: 	    ))
 4797: 	&& $helper->{VARS}->{'assignment'} eq ""
 4798: 	) {
 4799: 	my $pretty_dir = &Apache::lonnet::hreflocation($subdir);
 4800:         push(@{$printChoices}, [&mt('Selected [_1]Problems[_2] from current subdirectory [_3]','<b>','</b>','<b><i>'.$pretty_dir.'</i></b>','<b>','</b>'), 'problems_from_directory', 'CHOOSE_FROM_SUBDIR']);
 4801:         my $xmlfrag = <<CHOOSE_FROM_SUBDIR;
 4802:   <state name="CHOOSE_FROM_SUBDIR" title="Select File(s) from <b><small>$pretty_dir</small></b> to print">
 4803: 
 4804:     <files variable="FILES" multichoice='1'>
 4805:       <nextstate>PAGESIZE</nextstate>
 4806:       <filechoice>return '$subdir';</filechoice>
 4807: CHOOSE_FROM_SUBDIR
 4808: 
 4809:         # this is broken up because I really want interpolation above,
 4810:         # and I really DON'T want it below
 4811:         $xmlfrag .= <<'CHOOSE_FROM_SUBDIR';
 4812:       <filefilter>return Apache::lonhelper::files::not_old_version($filename) &&
 4813: 	  $filename =~ m/\.(problem|exam|quiz|assess|survey|form|library)$/;
 4814:       </filefilter>
 4815:       </files>
 4816:     </state>
 4817: CHOOSE_FROM_SUBDIR
 4818:         &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 4819:     }
 4820: 
 4821:     # Allow the user to select any sequence in the course, feed it to
 4822:     # another resource selector for that sequence
 4823:     if ((!$helper->{VARS}->{'construction'}) &&
 4824:         (!$is_published || (($subdir eq '') && ($url eq '/adm/navmaps')))) {
 4825:         push(@$printChoices,[&mt('Selected [_1]Resources[_2] from [_3]selected folder[_4] in course',
 4826:                                  '<b>','</b>','<b>','</b>'),
 4827:                              'select_sequences','CHOOSE_SEQUENCE']);
 4828:         my $escapedSequenceName;
 4829:         if ($helper->{VARS}->{'SEQUENCE'} ne '') {
 4830:             $escapedSequenceName = $helper->{VARS}->{'SEQUENCE'};
 4831:         } elsif (($subdir eq '') && ($url eq '/adm/navmaps')) {
 4832:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4833:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4834:             if ($env{'course.'.$env{'request.course.id'}.'.url'} eq
 4835:                 "uploaded/$cdom/$cnum/default.sequence") {
 4836:                 $escapedSequenceName = $env{'course.'.$env{'request.course.id'}.'.url'};
 4837:             }
 4838:         }
 4839:         #Escape apostrophes and backslashes for Perl
 4840:         $escapedSequenceName =~ s/\\/\\\\/g;
 4841:         $escapedSequenceName =~ s/'/\\'/g;
 4842:         my $nocurrloc;
 4843:         if (($subdir eq '') && ($url eq '/adm/navmaps')) {
 4844:             $nocurrloc = 'nocurrloc="1"';
 4845:             if ($perm{'pfo'}) {
 4846:                 push(@{$printChoices},
 4847:                     [&mt('Selected [_1]Problems[_2] from [_3]selected folder[_4] in course for [_5]selected people[_6]',
 4848:                          '<b>','</b>','<b>','</b>','<b>','</b>'),
 4849:                          'select_sequences_problems_for_students','CHOOSE_SEQUENCE_STUDENTS'],
 4850:                     [&mt('Selected [_1]Problems[_2] from [_3]selected folder[_4] in course  for [_5]CODEd assignments[_6]',
 4851:                          '<b>','</b>','<b>','</b>','<b>','</b>'),
 4852:                          'select_sequences_problems_for_anon','CHOOSE_SEQUENCE_ANON1'],
 4853:                     [&mt('Selected [_1]Resources[_2] from [_3]selected folder[_4] in course for [_5]selected people[_6]',
 4854:                          '<b>','</b>','<b>','</b>','<b>','</b>'),
 4855:                          'select_sequences_resources_for_students','CHOOSE_SEQUENCE_STUDENTS1'],
 4856:                     [&mt('Selected [_1]Resources[_2] from [_3]selected folder[_4] in course for [_5]CODEd assignments[_6]',
 4857:                          '<b>','</b>','<b>','</b>','<b>','</b>'),
 4858:                          'select_sequences_resources_for_anon','CHOOSE_SEQUENCE_ANON2']);
 4859:                 if ($escapedSequenceName) {
 4860:                     my ($randomly_ordered_warning,$codechoice,$code_selection,$namechoice) =
 4861:                         &generate_common_choosers($r,$helper,$escapedSequenceName,$escapedSequenceName,
 4862:                                                   $isProblem,$symbFilter,$start_new_option);
 4863: 
 4864:                     my $resource_selector = <<RESOURCE_SELECTOR;
 4865:   <state name="CHOOSE_STUDENTS2" title="Select Students and Resources">
 4866:     <choices variable='student_sort'>
 4867:       <choice computer='0'>Sort by section then student</choice>
 4868:       <choice computer='1'>Sort by students across sections.</choice>
 4869:     </choices>
 4870:     <message><br /><hr /><br /></message>
 4871:     <student multichoice='1' variable="STUDENTS" nextstate="SELECT_RESOURCES" coursepersonnel="1" />
 4872: 
 4873:     </state>
 4874:     <state name="SELECT_RESOURCES" title="Select Resources">
 4875:     $randomly_ordered_warning
 4876:     <nextstate>PRINT_FORMATTING</nextstate>
 4877:     <message>(mark desired resources then click "next" button) <br /></message>
 4878:     <resource variable="RESOURCES" multichoice="1" addstatus="1"
 4879:               closeallpages="1" modallink="1" suppressNavmap="1" $nocurrloc>
 4880:       <filterfunc>return $isNotMap;</filterfunc>
 4881:       <mapurl>$escapedSequenceName</mapurl>
 4882:       <valuefunc>return $symbFilter;</valuefunc>
 4883:       $start_new_option
 4884:       </resource>
 4885:     </state>
 4886: RESOURCE_SELECTOR
 4887: 
 4888:                     my $anon3 = &generate_code_selector($helper,
 4889:                                                         'CHOOSE_ANON3',
 4890:                                                         'SELECT_RESOURCES',
 4891:                                                         $codechoice,
 4892:                                                         $code_selection,
 4893:                                                         $namechoice) . $resource_selector;
 4894: 
 4895:                     &Apache::lonxml::xmlparse($r, 'helper',$anon3);
 4896:                 }
 4897:             }
 4898:         }
 4899:         if (($subdir eq '') && ($url eq '/adm/navmaps') && ($perm{'pfo'})) {
 4900:             &Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_FROM_ANY_SEQUENCE);
 4901:   <state name="CHOOSE_SEQUENCE" title="Select Sequence To Print From">
 4902:     <message>Select the sequence to print resources from:</message>
 4903:     <resource variable="SEQUENCE">
 4904:       <nextstate>CHOOSE_FROM_ANY_SEQUENCE</nextstate>
 4905:       <filterfunc>return &Apache::lonprintout::printable_sequence(\$res);</filterfunc>
 4906:       <valuefunc>return $urlValue;</valuefunc>
 4907:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 4908:         </choicefunc>
 4909:       </resource>
 4910:     </state>
 4911:   <state name="CHOOSE_SEQUENCE_STUDENTS" title="Select Sequence To Print From">
 4912:     <message>Select the sequence to print resources from:</message>
 4913:     <resource variable="SEQUENCE">
 4914:       <nextstate>CHOOSE_STUDENTS</nextstate>
 4915:       <filterfunc>return &Apache::lonprintout::printable_sequence(\$res);</filterfunc>
 4916:       <valuefunc>return $urlValue;</valuefunc>
 4917:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 4918:         </choicefunc>
 4919:       </resource>
 4920:     </state>
 4921:   <state name="CHOOSE_SEQUENCE_ANON1" title="Select Sequence To Print From">
 4922:     <message>Select the sequence to print resources from:</message>
 4923:     <resource variable="SEQUENCE">
 4924:       <nextstate>CHOOSE_ANON1</nextstate>
 4925:       <filterfunc>return &Apache::lonprintout::printable_sequence(\$res);</filterfunc>
 4926:       <valuefunc>return $urlValue;</valuefunc>
 4927:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 4928:         </choicefunc>
 4929:       </resource>
 4930:     </state>
 4931:   <state name="CHOOSE_SEQUENCE_STUDENTS1" title="Select Sequence To Print From">
 4932:     <message>Select the sequence to print resources from:</message>
 4933:     <resource variable="SEQUENCE">
 4934:       <nextstate>CHOOSE_STUDENTS2</nextstate>
 4935:       <filterfunc>return &Apache::lonprintout::printable_sequence(\$res);</filterfunc>
 4936:       <valuefunc>return $urlValue;</valuefunc>
 4937:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 4938:         </choicefunc>
 4939:       </resource>
 4940:     </state>
 4941:   <state name="CHOOSE_SEQUENCE_ANON2" title="Select Sequence To Print From">
 4942:     <message>Select the sequence to print resources from:</message>
 4943:     <resource variable="SEQUENCE">
 4944:       <nextstate>CHOOSE_ANON3</nextstate>
 4945:       <filterfunc>return &Apache::lonprintout::printable_sequence(\$res);</filterfunc>
 4946:       <valuefunc>return $urlValue;</valuefunc>
 4947:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 4948:         </choicefunc>
 4949:       </resource>
 4950:     </state>
 4951:   <state name="CHOOSE_FROM_ANY_SEQUENCE" title="Select Resources To Print">
 4952:     <message>(mark desired resources then click "next" button) <br /></message>
 4953:     <resource variable="RESOURCES" multichoice="1" toponly='1' addstatus="1"
 4954:               closeallpages="1" modallink="1" suppressNavmap="1" $nocurrloc>
 4955:       <nextstate>PAGESIZE</nextstate>
 4956:       <filterfunc>return $isNotMap</filterfunc>
 4957:       <mapurl evaluate='1'>return '$escapedSequenceName';</mapurl>
 4958:       <valuefunc>return $symbFilter;</valuefunc>
 4959:       $start_new_option
 4960:       </resource>
 4961:     </state>
 4962: CHOOSE_FROM_ANY_SEQUENCE
 4963:         } else {
 4964: 	    &Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_FROM_ANY_SEQUENCE);
 4965:   <state name="CHOOSE_SEQUENCE" title="Select Sequence To Print From">
 4966:     <message>Select the sequence to print resources from:</message>
 4967:     <resource variable="SEQUENCE">
 4968:       <nextstate>CHOOSE_FROM_ANY_SEQUENCE</nextstate>
 4969:       <filterfunc>return &Apache::lonprintout::printable_sequence(\$res);</filterfunc>
 4970:       <valuefunc>return $urlValue;</valuefunc>
 4971:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 4972: 	</choicefunc>
 4973:       </resource>
 4974:     </state>
 4975:   <state name="CHOOSE_FROM_ANY_SEQUENCE" title="Select Resources To Print">
 4976:     <message>(mark desired resources then click "next" button) <br /></message>
 4977:     <resource variable="RESOURCES" multichoice="1" toponly='1' addstatus="1"
 4978:               closeallpages="1" modallink="1" suppressNavmap="1" $nocurrloc>
 4979:       <nextstate>PAGESIZE</nextstate>
 4980:       <filterfunc>return $isNotMap</filterfunc>
 4981:       <mapurl evaluate='1'>return '$escapedSequenceName';</mapurl>
 4982:       <valuefunc>return $symbFilter;</valuefunc>
 4983:       $start_new_option
 4984:       </resource>
 4985:     </state>
 4986: CHOOSE_FROM_ANY_SEQUENCE
 4987:         }
 4988:     }
 4989:     my $numchoices = 0;
 4990:     if (ref($printChoices) eq 'ARRAY') {
 4991:         $numchoices = @{$printChoices};
 4992:     }
 4993:     # Early out if nothing to print
 4994:     if (!$numchoices) {
 4995:         $r->print(&Apache::loncommon::start_page('Printing Helper').
 4996:                   '<h2>'.&mt('Unable to determine print context').'</h2>'.
 4997:                   '<p>'.&mt('Please display a resource, and then click the "Print" button/icon').'</p>');
 4998:         my $prtspool=$r->dir_config('lonPrtDir');
 4999:         my $footer = &recently_generated($prtspool);
 5000:         $r->print($footer.&Apache::loncommon::end_page());
 5001:         return OK;
 5002:     }
 5003: 
 5004:     # Generate the first state, to select which resources get printed.
 5005:     Apache::lonhelper::state->new("START", "Select Printing Options:");
 5006:     if (!$res_printable) {
 5007:         my $noprintmsg;
 5008:         if ($res_error) {
 5009:             $noprintmsg = &mt('Print availability for current resource could not be determined');
 5010:         } else {
 5011:             my $now = time;
 5012:             my $shownprintstart = &Apache::lonlocal::locallocaltime($res_printstartdate);
 5013:             my $shownprintend = &Apache::lonlocal::locallocaltime($res_printenddate);
 5014:             if (($res_printenddate) && ($res_printenddate < $now)) {
 5015:                 $noprintmsg = &mt('Printing for current resource no longer available (ended: [_1])',
 5016:                                   $shownprintend);
 5017:             } else {
 5018:                 if (($res_printstartdate) && ($res_printstartdate > $now)) {
 5019:                     if (($res_printenddate) && ($res_printenddate > $now) && ($res_printenddate > $res_printstartdate)) {
 5020:                         $noprintmsg = &mt('Printing for current resource is only possible between [_1] and [_2]',
 5021:                                           $shownprintstart,$shownprintend);
 5022:                     } elsif (!$res_printenddate) {
 5023:                         $noprintmsg = &mt('Printing for current resource will only be possible starting [_1]',
 5024:                                           $shownprintstart);
 5025:                     } else {
 5026:                         $noprintmsg = &mt('Printing for current resource is unavailable');
 5027:                     }
 5028:                 }
 5029:             }
 5030:         }
 5031: 
 5032:         if ($noprintmsg) {
 5033:             $paramHash = Apache::lonhelper::getParamHash();
 5034: 	    $paramHash->{MESSAGE_TEXT} =
 5035:                 '<p class="LC_info">'.$noprintmsg.'</p>';
 5036: 	    Apache::lonhelper::message->new();
 5037:         }
 5038:     }
 5039:     $paramHash = Apache::lonhelper::getParamHash();
 5040:     $paramHash = Apache::lonhelper::getParamHash();
 5041:     $paramHash->{MESSAGE_TEXT} = "";
 5042:     Apache::lonhelper::message->new();
 5043:     $paramHash = Apache::lonhelper::getParamHash();
 5044:     $paramHash->{'variable'} = 'PRINT_TYPE';
 5045:     $paramHash->{CHOICES} = $printChoices;
 5046:     Apache::lonhelper::choices->new();
 5047: 
 5048:     my $startedTable = 0; # have we started an HTML table yet? (need
 5049:                           # to close it later)
 5050: 
 5051:     if (($perm{'pav'} and $perm{'vgr'}) or
 5052: 	($helper->{VARS}->{'construction'} eq '1')) {
 5053: 	&addMessage('<br />'
 5054:                    .'<h3>'.&mt('Print Options').'</h3>'
 5055:                    .&Apache::lonhtmlcommon::start_pick_box()
 5056:                    .&Apache::lonhtmlcommon::row_title(
 5057:                        '<label for="ANSWER_TYPE_forminput">'
 5058:                       .&mt('Print Answers')
 5059:                       .'</label>'
 5060:                     )
 5061:         );
 5062:         $paramHash = Apache::lonhelper::getParamHash();
 5063: 	$paramHash->{'variable'} = 'ANSWER_TYPE';
 5064: 	$helper->declareVar('ANSWER_TYPE');
 5065:         $paramHash->{CHOICES} = [
 5066:                                    ['Without Answers', 'yes'],
 5067:                                    ['With Answers', 'no'],
 5068:                                    ['Only Answers', 'only']
 5069:                                 ];
 5070:         Apache::lonhelper::dropdown->new();
 5071: 	&addMessage(&Apache::lonhtmlcommon::row_closure());
 5072: 	$startedTable = 1;
 5073: 
 5074: #
 5075: #  Select font size.
 5076: #
 5077: 
 5078:             $helper->declareVar('fontsize');
 5079:             &addMessage(&Apache::lonhtmlcommon::row_title(&mt('Font Size')));
 5080:             my $xmlfrag = << "FONT_SELECTION";
 5081: 
 5082: 
 5083:             <dropdown variable='fontsize' multichoice='0' allowempty='0'>
 5084:             <defaultvalue>
 5085: 		  return 'normalsize';
 5086:             </defaultvalue>
 5087:             <choice computer='tiny'>Tiny</choice>
 5088:             <choice computer='sub/superscriptsize'>Script Size</choice>
 5089:             <choice computer='footnotesize'>Footnote Size</choice>
 5090:             <choice computer='small'>Small</choice>
 5091:             <choice computer='normalsize'>Normal (default)</choice>
 5092:             <choice computer='large'>larger than normal</choice>
 5093:             <choice computer='Large'>Even larger than normal</choice>
 5094:             <choice computer='LARGE'>Still larger than normal</choice>
 5095:             <choice computer='huge'>huge font size</choice>
 5096:             <choice computer='Huge'>Largest possible size</choice>
 5097:             </dropdown>
 5098: FONT_SELECTION
 5099:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 5100:             &addMessage(&Apache::lonhtmlcommon::row_closure(1));
 5101:     }
 5102: 
 5103:     if ($perm{'pav'}) {
 5104: 	if (!$startedTable) {
 5105: 	    addMessage("<hr width='33%' /><table><tr><td align='right'>".
 5106:                        '<label for="LATEX_TYPE_forminput">'.
 5107:                        &mt('LaTeX mode').
 5108:                        "</label>: </td><td>");
 5109: 	    $startedTable = 1;
 5110: 	} else {
 5111: 	    &addMessage(&Apache::lonhtmlcommon::row_title(
 5112:                            '<label for="LATEX_TYPE_forminput">'
 5113:                            .&mt('LaTeX mode')
 5114:                            .'</label>'
 5115:                         )
 5116:             );
 5117: 	}
 5118:         $paramHash = Apache::lonhelper::getParamHash();
 5119: 	$paramHash->{'variable'} = 'LATEX_TYPE';
 5120: 	$helper->declareVar('LATEX_TYPE');
 5121: 	if ($helper->{VARS}->{'construction'} eq '1') {
 5122: 	    $paramHash->{CHOICES} = [
 5123: 				     ['standard LaTeX mode', 'standard'],
 5124: 				     ['LaTeX batchmode', 'batchmode'], ];
 5125: 	} else {
 5126: 	    $paramHash->{CHOICES} = [
 5127: 				     ['LaTeX batchmode', 'batchmode'],
 5128: 				     ['standard LaTeX mode', 'standard'] ];
 5129: 	}
 5130:         Apache::lonhelper::dropdown->new();
 5131: 
 5132: 	&addMessage(&Apache::lonhtmlcommon::row_closure()
 5133:                    .&Apache::lonhtmlcommon::row_title(
 5134:                         '<label for="TABLE_CONTENTS_forminput">'
 5135:                        .&mt('Print Table of Contents')
 5136:                        .'</label>'
 5137:                     )
 5138:         );
 5139:         $paramHash = Apache::lonhelper::getParamHash();
 5140: 	$paramHash->{'variable'} = 'TABLE_CONTENTS';
 5141: 	$helper->declareVar('TABLE_CONTENTS');
 5142:         $paramHash->{CHOICES} = [
 5143:                                    ['No', 'no'],
 5144:                                    ['Yes', 'yes'] ];
 5145:         Apache::lonhelper::dropdown->new();
 5146: 	&addMessage(&Apache::lonhtmlcommon::row_closure());
 5147: 
 5148: 	if (not $helper->{VARS}->{'construction'}) {
 5149: 	    &addMessage(&Apache::lonhtmlcommon::row_title(
 5150:                             '<label for="TABLE_INDEX_forminput">'
 5151:                            .&mt('Print Index')
 5152:                            .'</label>'
 5153:                         )
 5154:             );
 5155: 	    $paramHash = Apache::lonhelper::getParamHash();
 5156: 	    $paramHash->{'variable'} = 'TABLE_INDEX';
 5157: 	    $helper->declareVar('TABLE_INDEX');
 5158: 	    $paramHash->{CHOICES} = [
 5159: 				     ['No', 'no'],
 5160: 				     ['Yes', 'yes'] ];
 5161: 	    Apache::lonhelper::dropdown->new();
 5162:             &addMessage(&Apache::lonhtmlcommon::row_closure());
 5163:             &addMessage(&Apache::lonhtmlcommon::row_title(
 5164:                             '<label for="PRINT_DISCUSSIONS_forminput">'
 5165:                            .&mt('Print Discussions')
 5166:                            .'</label>'
 5167:                         )
 5168:             );
 5169: 	    $paramHash = Apache::lonhelper::getParamHash();
 5170: 	    $paramHash->{'variable'} = 'PRINT_DISCUSSIONS';
 5171: 	    $helper->declareVar('PRINT_DISCUSSIONS');
 5172: 	    $paramHash->{CHOICES} = [
 5173: 				     ['No', 'no'],
 5174: 				     ['Yes', 'yes'] ];
 5175: 	    Apache::lonhelper::dropdown->new();
 5176:             &addMessage(&Apache::lonhtmlcommon::row_closure());
 5177: 
 5178: 	    # Prompt for printing annotations too.
 5179: 		
 5180: 	    &addMessage(&Apache::lonhtmlcommon::row_title(
 5181:                             '<label for="PRINT_ANNOTATIONS_forminput">'
 5182:                            .&mt('Print Annotations')
 5183:                            .'</label>'
 5184:                         )
 5185:             );
 5186: 	    $paramHash = Apache::lonhelper::getParamHash();
 5187: 	    $paramHash->{'variable'} = "PRINT_ANNOTATIONS";
 5188: 	    $helper->declareVar("PRINT_ANNOTATIONS");
 5189: 	    $paramHash->{CHOICES} = [
 5190: 				     ['No', 'no'],
 5191: 				     ['Yes', 'yes']];
 5192: 	    Apache::lonhelper::dropdown->new();
 5193:             &addMessage(&Apache::lonhtmlcommon::row_closure());
 5194: 
 5195:             &addMessage(&Apache::lonhtmlcommon::row_title(&mt('Foils')));
 5196: 	    $paramHash = Apache::lonhelper::getParamHash();
 5197: 	    $paramHash->{'multichoice'} = "true";
 5198: 	    $paramHash->{'allowempty'}  = "true";
 5199: 	    $paramHash->{'variable'}   = "showallfoils";
 5200: 	    $paramHash->{'CHOICES'} = [ [&mt('Show All Foils'), "1"] ];
 5201: 	    Apache::lonhelper::choices->new();
 5202:             &addMessage(&Apache::lonhtmlcommon::row_closure(1));
 5203: 	}
 5204: 
 5205: 	if ($helper->{'VARS'}->{'construction'}) {
 5206: 	    my $stylevalue='$Apache::lonnet::env{"construct.style"}';
 5207:             my $randseedtext=&mt("Use random seed");
 5208:             my $stylefiletext=&mt("Use style file");
 5209:             my $selectfiletext=&mt("Select style file");
 5210: 
 5211: 	    my $xmlfrag .= '<message>'
 5212:             .&Apache::lonhtmlcommon::row_title('<label for="curseed_forminput">'
 5213:                                               .$randseedtext
 5214:                                               .'</label>'
 5215:              )
 5216:             .'</message>
 5217:             <string variable="curseed" size="15" maxlength="15">
 5218:                 <defaultvalue>
 5219:                    return '.$helper->{VARS}->{'curseed'}.';
 5220:                 </defaultvalue>'
 5221:             .'</string>'
 5222:             .'<message>'
 5223:             .&Apache::lonhtmlcommon::row_closure()
 5224:             .&Apache::lonhtmlcommon::row_title('<label for="style_file">'
 5225:                                               .$stylefiletext
 5226:                                               .'</label>'
 5227:              )
 5228:             .'</message>
 5229:              <string variable="style_file" size="40">
 5230:                 <defaultvalue>
 5231:                     return '.$stylevalue.';
 5232:                 </defaultvalue>
 5233:              </string><message>&nbsp;'
 5234: .qq|<a href="javascript:openbrowser('helpform','style_file_forminput','sty')">|
 5235: .$selectfiletext.'</a>'
 5236:             .&Apache::lonhtmlcommon::row_closure()
 5237:             .&Apache::lonhtmlcommon::row_title(&mt('Show All Foils'))
 5238:             .'</message>
 5239: 	     <choices allowempty="1" multichoice="true" variable="showallfoils">
 5240:                 <choice computer="1">&nbsp;</choice>
 5241:              </choices>'
 5242: 	    .'<message>'
 5243:             .&Apache::lonhtmlcommon::row_closure()
 5244:             .'</message>';
 5245:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 5246: 
 5247: 
 5248:             &addMessage(&Apache::lonhtmlcommon::row_title(&mt('Problem Type')));
 5249: 	    #
 5250: 	    # Initial value from construction space:
 5251: 	    #
 5252: 	    if (!$helper->{VARS}->{'probstatus'} && $env{'form.problemtype'}) {
 5253: 		$helper->{VARS}->{'probstatus'} = $env{'form.problemtype'};	# initial value
 5254: 	    }
 5255: 	    $xmlfrag = << "PROBTYPE";
 5256: 		<dropdown variable="probstatus" multichoice="0" allowempty="0">
 5257: 		   <defaultvalue>
 5258: 		      return "$helper->{VARS}->{'probstatus'}";
 5259:                    </defaultvalue>
 5260: 		   <choice computer="problem">Homework Problem</choice>
 5261: 		   <choice computer="exam">Bubblesheet Exam Problem</choice>
 5262: 		   <choice computer="survey">Survey question</choice>
 5263:                    ,choice computer="anonsurvey"Anonymous survey question</choice>
 5264: 		</dropdown>
 5265: PROBTYPE
 5266:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 5267:             &addMessage(&Apache::lonhtmlcommon::row_closure(1));
 5268: 
 5269: 
 5270: 
 5271:         }
 5272:     }
 5273: 
 5274: 
 5275: 
 5276: 
 5277:     if ($startedTable) {
 5278:         &addMessage(&Apache::lonhtmlcommon::end_pick_box());
 5279:     }
 5280: 
 5281:     Apache::lonprintout::page_format_state->new("FORMAT");
 5282: 
 5283:     # Generate the PAGESIZE state which will offer the user the margin
 5284:     # choices if they select one column
 5285:     Apache::lonhelper::state->new("PAGESIZE", "Set Margins");
 5286:     Apache::lonprintout::page_size_state->new('pagesize', 'FORMAT', 'FINAL');
 5287: 
 5288: 
 5289:     $helper->process();
 5290: 
 5291: 
 5292:     # MANUAL BAILOUT CONDITION:
 5293:     # If we're in the "final" state, bailout and return to handler
 5294:     if ($helper->{STATE} eq 'FINAL') {
 5295:         return $helper;
 5296:     }
 5297: 
 5298:     my $footer;
 5299:     if ($helper->{STATE} eq 'START') {
 5300:         my $prtspool=$r->dir_config('lonPrtDir');
 5301: 	$footer = &recently_generated($prtspool);
 5302:     }
 5303:     $r->print($helper->display($footer));
 5304:     &Apache::lonhelper::unregisterHelperTags();
 5305: 
 5306:     return OK;
 5307: }
 5308: 
 5309: 
 5310: 1;
 5311: 
 5312: package Apache::lonprintout::page_format_state;
 5313: 
 5314: =pod
 5315: 
 5316: =head1 Helper element: page_format_state
 5317: 
 5318: See lonhelper.pm documentation for discussion of the helper framework.
 5319: 
 5320: Apache::lonprintout::page_format_state is an element that gives the
 5321: user an opportunity to select the page layout they wish to print
 5322: with: Number of columns, portrait/landscape, and paper size. If you
 5323: want to change the paper size choices, change the @paperSize array
 5324: contents in this package.
 5325: 
 5326: page_format_state is always directly invoked in lonprintout.pm, so there
 5327: is no tag interface. You actually pass parameters to the constructor.
 5328: 
 5329: =over 4
 5330: 
 5331: =item * B<new>(varName): varName is where the print information will be stored in the format FIXME.
 5332: 
 5333: =back
 5334: 
 5335: =cut
 5336: 
 5337: use Apache::lonhelper;
 5338: 
 5339: no strict;
 5340: @ISA = ("Apache::lonhelper::element");
 5341: use strict;
 5342: use Apache::lonlocal;
 5343: use Apache::lonnet;
 5344: 
 5345: my $maxColumns = 2;
 5346: # it'd be nice if these all worked
 5347: #my @paperSize = ("letter [8 1/2x11 in]", "legal [8 1/2x14 in]",
 5348: #                 "tabloid (ledger) [11x17 in]", "executive [7 1/2x10 in]",
 5349: #                 "a2 [420x594 mm]", "a3 [297x420 mm]", "a4 [210x297 mm]",
 5350: #                 "a5 [148x210 mm]", "a6 [105x148 mm]" );
 5351: my @paperSize = ("letter [8 1/2x11 in]", "legal [8 1/2x14 in]",
 5352: 		 "a4 [210x297 mm]");
 5353: 
 5354: # Tentative format: Orientation (L = Landscape, P = portrait) | Colnum |
 5355: #                   Paper type
 5356: 
 5357: sub new {
 5358:     my $self = Apache::lonhelper::element->new();
 5359: 
 5360:     shift;
 5361: 
 5362:     $self->{'variable'} = shift;
 5363:     my $helper = Apache::lonhelper::getHelper();
 5364:     $helper->declareVar($self->{'variable'});
 5365:     bless($self);
 5366:     return $self;
 5367: }
 5368: 
 5369: sub render {
 5370:     my $self = shift;
 5371:     my $helper = Apache::lonhelper::getHelper();
 5372:     my $result = '';
 5373:     my $var = $self->{'variable'};
 5374:     my $PageLayout=&mt('Page layout');
 5375:     my $NumberOfColumns=&mt('Number of columns');
 5376:     my $PaperType=&mt('Paper type');
 5377:     my $landscape=&mt('Landscape');
 5378:     my $portrait=&mt('Portrait');
 5379:     my $pdfFormLabel=&mt('PDF Form Fields');
 5380:     my $with=&mt('with Form Fields');
 5381:     my $without=&mt('without Form Fields');
 5382: 
 5383: 
 5384:     $result.='<h3>'.&mt('Layout Options').'</h3>'
 5385:             .&Apache::loncommon::start_data_table()
 5386:             .&Apache::loncommon::start_data_table_header_row()
 5387:             .'<th>'.$PageLayout.'</th>'
 5388:             .'<th>'.$NumberOfColumns.'</th>'
 5389:             .'<th>'.$PaperType.'</th>'
 5390:             .'<th>'.$pdfFormLabel.'</th>'
 5391:             .&Apache::loncommon::end_data_table_header_row()
 5392:             .&Apache::loncommon::start_data_table_row()
 5393:     .'<td>'
 5394:     .'<label><input type="radio" name="'.${var}.'.layout" value="L" />'.$landscape.'</label><br />'
 5395:     .'<label><input type="radio" name="'.${var}.'.layout" value="P" checked="checked" />'.$portrait.'</label>'
 5396:     .'</td>';
 5397: 
 5398:     $result.='<td align="center">'
 5399:             .'<select name="'.${var}.'.cols">';
 5400: 
 5401:     my $i;
 5402:     for ($i = 1; $i <= $maxColumns; $i++) {
 5403:         if ($i == 2) {
 5404:             $result .= '<option value="'.$i.'" selected="selected">'.$i.'</option>'."\n";
 5405:         } else {
 5406:             $result .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 5407:         }
 5408:     }
 5409: 
 5410:     $result .= "</select></td><td>\n";
 5411:     $result .= "<select name='${var}.paper'>\n";
 5412: 
 5413:     my %parmhash=&Apache::lonnet::coursedescription($env{'request.course.id'});
 5414:     my $DefaultPaperSize=lc($parmhash{'default_paper_size'});
 5415:     $DefaultPaperSize=~s/\s//g;
 5416:     if ($DefaultPaperSize eq '') {$DefaultPaperSize='letter';}
 5417:     $i = 0;
 5418:     foreach (@paperSize) {
 5419: 	$_=~/(\w+)/;
 5420: 	my $papersize=$1;
 5421:         if ($paperSize[$i]=~/$DefaultPaperSize/) {
 5422:             $result .= '<option selected="selected" value="'.$papersize.'">'.$paperSize[$i].'</option>'."\n";
 5423:         } else {
 5424:             $result .= '<option value="'.$papersize.'">'.$paperSize[$i].'</option>'."\n";
 5425:         }
 5426:         $i++;
 5427:     }
 5428:     $result .= <<HTML;
 5429:         </select>
 5430:     </td>
 5431:     <td align='center'>
 5432:         <select name='${var}.pdfFormFields'>
 5433:             <option selected="selected" value="no">$without</option>
 5434:             <option value="yes">$with</option>
 5435:         </select>
 5436:     </td>
 5437: HTML
 5438:     $result.=&Apache::loncommon::end_data_table_row()
 5439:             .&Apache::loncommon::end_data_table();
 5440: 
 5441:     return $result;
 5442: }
 5443: 
 5444: sub postprocess {
 5445:     my $self = shift;
 5446: 
 5447:     my $var = $self->{'variable'};
 5448:     my $helper = Apache::lonhelper->getHelper();
 5449:     $helper->{VARS}->{$var} =
 5450:         $env{"form.$var.layout"} . '|' . $env{"form.$var.cols"} . '|' .
 5451:         $env{"form.$var.paper"} . '|' . $env{"form.$var.pdfFormFields"};
 5452:     return 1;
 5453: }
 5454: 
 5455: 1;
 5456: 
 5457: package Apache::lonprintout::page_size_state;
 5458: 
 5459: =pod
 5460: 
 5461: =head1 Helper element: page_size_state
 5462: 
 5463: See lonhelper.pm documentation for discussion of the helper framework.
 5464: 
 5465: Apache::lonprintout::page_size_state is an element that gives the
 5466: user the opportunity to further refine the page settings if they
 5467: select a single-column page.
 5468: 
 5469: page_size_state is always directly invoked in lonprintout.pm, so there
 5470: is no tag interface. You actually pass parameters to the constructor.
 5471: 
 5472: =over 4
 5473: 
 5474: =item * B<new>(varName): varName is where the print information will be stored in the format FIXME.
 5475: 
 5476: =back
 5477: 
 5478: =cut
 5479: 
 5480: use Apache::lonhelper;
 5481: use Apache::lonnet;
 5482: no strict;
 5483: @ISA = ("Apache::lonhelper::element");
 5484: use strict;
 5485: 
 5486: 
 5487: 
 5488: sub new {
 5489:     my $self = Apache::lonhelper::element->new();
 5490: 
 5491:     shift; # disturbs me (probably prevents subclassing) but works (drops
 5492:            # package descriptor)... - Jeremy
 5493: 
 5494:     $self->{'variable'} = shift;
 5495:     my $helper = Apache::lonhelper::getHelper();
 5496:     $helper->declareVar($self->{'variable'});
 5497: 
 5498:     # The variable name of the format element, so we can look into
 5499:     # $helper->{VARS} to figure out whether the columns are one or two
 5500:     $self->{'formatvar'} = shift;
 5501: 
 5502: 
 5503:     $self->{NEXTSTATE} = shift;
 5504:     bless($self);
 5505: 
 5506:     return $self;
 5507: }
 5508: 
 5509: sub render {
 5510:     my $self = shift;
 5511:     my $helper = Apache::lonhelper::getHelper();
 5512:     my $result = '';
 5513:     my $var = $self->{'variable'};
 5514: 
 5515: 
 5516: 
 5517:     if (defined $self->{ERROR_MSG}) {
 5518:         $result .= '<br /><span class="LC_error">' . $self->{ERROR_MSG} . '</span><br />';
 5519:     }
 5520: 
 5521:     my $format = $helper->{VARS}->{$self->{'formatvar'}};
 5522: 
 5523:     # Use format to get sensible defaults for the margins:
 5524: 
 5525: 
 5526:     my ($laystyle, $cols, $papersize) = split(/\|/, $format);
 5527:     ($papersize)                      = split(/ /, $papersize);
 5528: 
 5529:     $laystyle = &Apache::lonprintout::map_laystyle($laystyle);
 5530: 
 5531: 
 5532: 
 5533:     my %size;
 5534:     ($size{'width_and_units'},
 5535:      $size{'height_and_units'},
 5536:      $size{'margin_and_units'})=
 5537: 	 &Apache::lonprintout::page_format($papersize, $laystyle, $cols);
 5538: 
 5539:     foreach my $dimension ('width','height','margin') {
 5540: 	($size{$dimension},$size{$dimension.'_unit'}) =
 5541: 	    split(/ +/, $size{$dimension.'_and_units'},2);
 5542:        	
 5543: 	foreach my $unit ('cm','in') {
 5544: 	    $size{$dimension.'_options'} .= '<option ';
 5545: 	    if ($size{$dimension.'_unit'} eq $unit) {
 5546: 		$size{$dimension.'_options'} .= 'selected="selected" ';
 5547: 	    }
 5548: 	    $size{$dimension.'_options'} .= '>'.$unit.'</option>';
 5549: 	}
 5550:     }
 5551: 
 5552:     # Adjust margin for LaTeX margin: .. requires units == cm or in.
 5553: 
 5554:     if ($size{'margin_unit'} eq 'in') {
 5555: 	$size{'margin'} += 1;
 5556:     }  else {
 5557: 	$size{'margin'} += 2.54;
 5558:     }
 5559:     my %lt = &Apache::lonlocal::texthash(
 5560:         'format' => 'How should each column be formatted?',
 5561:         'width'  => 'Width',
 5562:         'height' => 'Height',
 5563:         'margin' => 'Left Margin'
 5564:     );
 5565: 
 5566:     $result .= '<p>'.$lt{'format'}.'</p>'
 5567:               .&Apache::lonhtmlcommon::start_pick_box()
 5568:               .&Apache::lonhtmlcommon::row_title($lt{'width'})
 5569:               .'<input type="text" name="'.$var.'.width" value="'.$size{'width'}.'" size="4" />'
 5570:               .'<select name="'.$var.'.widthunit">'
 5571:               .$size{'width_options'}
 5572:               .'</select>'
 5573:               .&Apache::lonhtmlcommon::row_closure()
 5574:               .&Apache::lonhtmlcommon::row_title($lt{'height'})
 5575:               .'<input type="text" name="'.$var.'.height" value="'.$size{'height'}.'" size="4" />'
 5576:               .'<select name="'.$var.'.heightunit">'
 5577:               .$size{'height_options'}
 5578:               .'</select>'
 5579:               .&Apache::lonhtmlcommon::row_closure()
 5580:               .&Apache::lonhtmlcommon::row_title($lt{'margin'})
 5581:               .'<input type="text" name="'.$var.'.lmargin" value="'.$size{'margin'}.'" size="4" />'
 5582:               .'<select name="'.$var.'.lmarginunit">'
 5583:               .$size{'margin_options'}
 5584:               .'</select>'
 5585:               .&Apache::lonhtmlcommon::row_closure(1)
 5586:               .&Apache::lonhtmlcommon::end_pick_box();
 5587:     # <p>Hint: Some instructors like to leave scratch space for the student by
 5588:     # making the width much smaller than the width of the page.</p>
 5589: 
 5590:     return $result;
 5591: }
 5592: 
 5593: 
 5594: sub preprocess {
 5595:     my $self = shift;
 5596:     my $helper = Apache::lonhelper::getHelper();
 5597: 
 5598:     my $format = $helper->{VARS}->{$self->{'formatvar'}};
 5599: 
 5600:     #  If the user does not have 'pav' privilege, set default widths and
 5601:     #  on to the next state right away.
 5602:     #
 5603:     if (!$perm{'pav'}) {
 5604: 	my $var = $self->{'variable'};
 5605: 	my $format = $helper->{VARS}->{$self->{'formatvar'}};
 5606: 	
 5607: 	my ($laystyle, $cols, $papersize) = split(/\|/, $format);
 5608: 	($papersize)                      = split(/ /, $papersize);
 5609: 	
 5610: 	
 5611: 	$laystyle = &Apache::lonprintout::map_laystyle($laystyle);
 5612: 
 5613: 	#  Figure out some good defaults for the print out and set them:
 5614: 	
 5615: 	my %size;
 5616: 	($size{'width'},
 5617: 	 $size{'height'},
 5618: 	 $size{'lmargin'})=
 5619: 	     &Apache::lonprintout::page_format($papersize, $laystyle, $cols);
 5620: 	
 5621: 	foreach my $dim ('width', 'height', 'lmargin') {
 5622: 	    my ($value, $units) = split(/ /, $size{$dim});
 5623: 
 5624: 	    $helper->{VARS}->{"$var.".$dim}      = $value;
 5625: 	    $helper->{VARS}->{"$var.".$dim.'unit'} = $units;
 5626: 
 5627: 	}
 5628: 	
 5629: 
 5630: 	# Transition to the next state
 5631: 
 5632: 	$helper->changeState($self->{NEXTSTATE});
 5633:     }
 5634: 
 5635:     return 1;
 5636: }
 5637: 
 5638: sub postprocess {
 5639:     my $self = shift;
 5640: 
 5641:     my $var = $self->{'variable'};
 5642:     my $helper = Apache::lonhelper->getHelper();
 5643:     my $width = $helper->{VARS}->{$var .'.width'} = $env{"form.${var}.width"};
 5644:     my $height = $helper->{VARS}->{$var .'.height'} = $env{"form.${var}.height"};
 5645:     my $lmargin = $helper->{VARS}->{$var .'.lmargin'} = $env{"form.${var}.lmargin"};
 5646:     $helper->{VARS}->{$var .'.widthunit'} = $env{"form.${var}.widthunit"};
 5647:     $helper->{VARS}->{$var .'.heightunit'} = $env{"form.${var}.heightunit"};
 5648:     $helper->{VARS}->{$var .'.lmarginunit'} = $env{"form.${var}.lmarginunit"};
 5649: 
 5650:     my $error = '';
 5651: 
 5652:     # /^-?[0-9]+(\.[0-9]*)?$/ -> optional minus, at least on digit, followed
 5653:     # by an optional period, followed by digits, ending the string
 5654: 
 5655:     if ($width !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 5656:         $error .= "Invalid width; please type only a number.<br />\n";
 5657:     }
 5658:     if ($height !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 5659:         $error .= "Invalid height; please type only a number.<br />\n";
 5660:     }
 5661:     if ($lmargin !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 5662:         $error .= "Invalid left margin; please type only a number.<br />\n";
 5663:     } else {
 5664: 	# Adjust for LaTeX 1.0 inch margin:
 5665: 
 5666: 	if ($env{"form.${var}.lmarginunit"} eq "in") {
 5667: 	    $helper->{VARS}->{$var.'.lmargin'} = $lmargin - 1;
 5668: 	} else {
 5669: 	    $helper->{VARS}->{$var.'.lmargin'} = $lmargin - 2.54;
 5670: 	}
 5671:     }
 5672: 
 5673:     if (!$error) {
 5674:         Apache::lonhelper::getHelper()->changeState($self->{NEXTSTATE});
 5675:         return 1;
 5676:     } else {
 5677:         $self->{ERROR_MSG} = $error;
 5678:         return 0;
 5679:     }
 5680: }
 5681: 
 5682: __END__
 5683: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>