File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.615: download - view: text, annotated - select for diffs
Tue Apr 10 09:49:36 2012 UTC (12 years, 2 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
BZ3462 Inidicate why it's not possible to print the current resource

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

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