File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.604: download - view: text, annotated - select for diffs
Mon Nov 7 13:41:43 2011 UTC (12 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Cleanup

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

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