File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.616: download - view: text, annotated - select for diffs
Mon May 28 10:31:17 2012 UTC (12 years ago) by foxr
Branches: MAIN
CVS tags: HEAD
BZ 3462 - Alter choices presented to students if folders or the course itself
are not printable.

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

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