File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.597: download - view: text, annotated - select for diffs
Thu Sep 15 12:09:44 2011 UTC (13 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate unused code from rev 1.586.
  - &generate_format_selector() includes the same code, and is in active use.

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

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