File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.627.2.30: download - view: text, annotated - select for diffs
Thu Mar 5 18:33:35 2020 UTC (4 years, 2 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3
- For 2.11
  Backport 1.670, 1.671, 1.672

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

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