File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.625: download - view: text, annotated - select for diffs
Sat Dec 8 20:10:26 2012 UTC (11 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Printing Problems/Resources from folder for CODEd assignments:
  - If randomorder parameter set for folder, seed used for ordering of
    resources is set in lonnet::rndseed() based on CODE.

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

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