File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.568.2.5: download - view: text, annotated - select for diffs
Tue May 11 12:22:10 2010 UTC (14 years ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.568: preferred, unified
- Backport 1.574, 1.575.

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

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