File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.501: download - view: text, annotated - select for diffs
Wed May 2 01:33:49 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: version_2_4_X, version_2_4_2, version_2_4_1, version_2_4_0, version_2_3_99_0, HEAD
- switch Store to Save

    1: #
    2: # The LearningOnline Network
    3: # Printout
    4: #
    5: # $Id: lonprintout.pm,v 1.501 2007/05/02 01:33:49 albertel 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: 
   31: use strict;
   32: use Apache::Constants qw(:common :http);
   33: use Apache::lonxml;
   34: use Apache::lonnet;
   35: use Apache::loncommon;
   36: use Apache::inputtags;
   37: use Apache::grades;
   38: use Apache::edit;
   39: use Apache::File();
   40: use Apache::lonnavmaps;
   41: use LONCAPA::map();
   42: use POSIX qw(strftime);
   43: use Apache::lonlocal;
   44: use Carp;
   45: use LONCAPA;
   46: 
   47: my %perm;
   48: my %parmhash;
   49: my $resources_printed;
   50: 
   51: # Fetch the contents of a resource, uninterpreted.
   52: # This is used here to fetch a latex file to be included
   53: # verbatim into the printout<
   54: # NOTE: Ask Guy if there is a lonnet function similar to this?
   55: #
   56: # Parameters:
   57: #   URL of the file
   58: #
   59: sub fetch_raw_resource {
   60:     my ($url) = @_;
   61: 
   62:     my $filename  = &Apache::lonnet::filelocation("", $url);
   63:     my $contents  = &Apache::lonnet::getfile($filename);
   64: 
   65:     if ($contents == -1) {
   66: 	return "File open failed for $filename";      # This will bomb the print.
   67:     }
   68:     return $contents;
   69: 
   70:     
   71: }
   72: 
   73: #
   74: #   printf_style_subst  item format_string repl
   75: #  
   76: # Does printf style substitution for a format string that
   77: # can have %[n]item in it.. wherever, %[n]item occurs,
   78: # rep is substituted in format_string.  Note that
   79: # [n] is an optional integer length.  If provided,
   80: # repl is truncated to at most [n] characters prior to 
   81: # substitution.
   82: #
   83: sub printf_style_subst {
   84:     my ($item, $format_string, $repl) = @_;
   85:     my $result = "";
   86:     while ($format_string =~ /(%)(\d*)\Q$item\E/g ) {
   87: 	my $fmt = $1;
   88: 	my $size = $2;
   89: 	my $subst = $repl;
   90: 	if ($size ne "") {
   91: 	    $subst = substr($subst, 0, $size);
   92: 	    
   93: 	    #  Here's a nice edge case.. supose the end of the
   94: 	    #  substring is a \.  In that case may have  just
   95: 	    #  chopped off a TeX escape... in that case, we append
   96: 	    #   " " for the trailing character, and let the field 
   97: 	    #  spill over a bit (sigh).
   98: 	    #  We don't just chop off the last character in order to deal
   99: 	    #  with one last pathology, and that would be if substr had
  100: 	    #  trimmed us to e.g. \\\  
  101: 
  102: 
  103: 	    if ($subst =~ /\\$/) {
  104: 		$subst .= " ";
  105: 	    }
  106: 	}
  107: 	my $item_pos = pos($format_string);
  108: 	$result .= substr($format_string, 0, $item_pos - length($size) -2) . $subst;
  109:         $format_string = substr($format_string, pos($format_string));
  110:     }
  111: 
  112:     # Put the residual format string into the result:
  113: 
  114:     $result .= $format_string;
  115: 
  116:     return $result;
  117: }
  118: 
  119: 
  120: # Format a header according to a format.  
  121: # 
  122: 
  123: # Substitutions:
  124: #     %a    - Assignment name.
  125: #     %c    - Course name.
  126: #     %n    - Student name.
  127: #
  128: sub format_page_header {
  129:     my ($width, $format, $assignment, $course, $student) = @_;
  130:     
  131:     $width = &recalcto_mm($width); # Get width in mm.
  132:     #  Default format?
  133: 
  134:     if ($format eq '') {
  135: 	# For the default format, we may need to truncate
  136: 	# elements..  To do this we need to get the page width.
  137: 	# we assume that each character is about 2mm in width.
  138: 	# (correct for the header text size??).  We ignore
  139: 	# any formatting (e.g. boldfacing in this).
  140: 	# 
  141: 	# - Allow the student/course to be one line.
  142: 	#   but only truncate the course.
  143: 	# - Allow the assignment to be 2 lines (wrapped).
  144: 	#
  145: 	my $chars_per_line = $width/2; # Character/textline.
  146: 
  147: 
  148: 	my $firstline = "$student $course";
  149: 	if (length($firstline) > $chars_per_line) {
  150: 	    my $lastchar = $chars_per_line - length($student) - 1;
  151: 	    if ($lastchar > 0) {
  152: 		$course = substr($course, 0, $lastchar);
  153: 	    } else {		# Nothing left of course:
  154: 		$course = '';
  155: 	    }
  156: 	}
  157: 	if (length($assignment) > $chars_per_line) {
  158: 	    $assignment = substr($assignment, 0, $chars_per_line);
  159: 	}
  160: 	
  161: 	$format =  "\\textbf{$student} $course \\hfill \\thepage \\\\ \\textit{$assignment}";
  162: 	
  163:     } else {
  164: 	# An open question is how to handle long user formatted page headers...
  165: 	# A possible future is to support e.g. %na so that the user can control
  166: 	# the truncation of the elements that can appear in the header.
  167: 	#
  168: 	$format =  &printf_style_subst("a", $format, $assignment);
  169: 	$format =  &printf_style_subst("c", $format, $course);
  170: 	$format =  &printf_style_subst("n", $format, $student);
  171: 
  172: 	# If the user put %'s in the format string, they  must be escaped
  173: 	# to \% else LaTeX will think they are comments and terminate
  174: 	# the line.. which is bad!!!
  175: 
  176: 
  177:     }
  178:     
  179: 
  180:     return $format;
  181:     
  182: }
  183: 
  184: #
  185: #   Convert a numeric code to letters
  186: #
  187: sub num_to_letters {
  188:     my ($num) = @_;
  189:     my @nums= split('',$num);
  190:     my @num_to_let=('A'..'Z');
  191:     my $word;
  192:     foreach my $digit (@nums) { $word.=$num_to_let[$digit]; }
  193:     return $word;
  194: }
  195: #   Convert a letter code to numeric.
  196: #
  197: sub letters_to_num {
  198:     my ($letters) = @_;
  199:     my @letters = split('', uc($letters));
  200:    my %substitution;
  201:     my $digit = 0;
  202:     foreach my $letter ('A'..'J') {
  203: 	$substitution{$letter} = $digit;
  204: 	$digit++;
  205:     }
  206:     #  The substitution is done as below to preserve leading
  207:     #  zeroes which are needed to keep the code size exact
  208:     #
  209:     my $result ="";
  210:     foreach my $letter (@letters) {
  211: 	$result.=$substitution{$letter};
  212:     }
  213:     return $result;
  214: }
  215: 
  216: #  Determine if a code is a valid numeric code.  Valid
  217: #  numeric codes must be comprised entirely of digits and
  218: #  have a correct number of digits.
  219: #
  220: #  Parameters:
  221: #     value      - proposed code value.
  222: #     num_digits - Number of digits required.
  223: #
  224: sub is_valid_numeric_code {
  225:     my ($value, $num_digits) = @_;
  226:     #   Remove leading/trailing whitespace;
  227:     $value =~ s/^\s*//g;
  228:     $value =~ s/\s*$//g;
  229:     
  230:     #  All digits?
  231:     if ($value !~ /^[0-9]+$/) {
  232: 	return "Numeric code $value has invalid characters - must only be digits";
  233:     }
  234:     if (length($value) != $num_digits) {
  235: 	return "Numeric code $value incorrect number of digits (correct = $num_digits)";
  236:     }
  237:     return undef;
  238: }
  239: #   Determines if a code is a valid alhpa code.  Alpha codes
  240: #   are ciphers that map  [A-J,a-j] -> 0..9 0..9.
  241: #   They also have a correct digit count.
  242: # Parameters:
  243: #     value          - Proposed code value.
  244: #     num_letters    - correct number of letters.
  245: # Note:
  246: #    leading and trailing whitespace are ignored.
  247: #
  248: sub is_valid_alpha_code {
  249:     my ($value, $num_letters) = @_;
  250:     
  251:      # strip leading and trailing spaces.
  252: 
  253:     $value =~ s/^\s*//g;
  254:     $value =~ s/\s*$//g;
  255: 
  256:     #  All alphas in the right range?
  257:     if ($value !~ /^[A-J,a-j]+$/) {
  258: 	return "Invalid letter code $value must only contain A-J";
  259:     }
  260:     if (length($value) != $num_letters) {
  261: 	return "Letter code $value has incorrect number of letters (correct = $num_letters)";
  262:     }
  263:     return undef;
  264: }
  265: 
  266: #   Determine if a code entered by the user in a helper is valid.
  267: #   valid depends on the code type and the type of code selected.
  268: #   The type of code selected can either be numeric or 
  269: #   Alphabetic.  If alphabetic, the code, in fact is a simple
  270: #   substitution cipher for the actual numeric code: 0->A, 1->B ...
  271: #   We'll be nice and be case insensitive for alpha codes.
  272: # Parameters:
  273: #    code_value    - the value of the code the user typed in.
  274: #    code_option   - The code type selected from the set in the scantron format
  275: #                    table.
  276: # Returns:
  277: #    undef         - The code is valid.
  278: #    other         - An error message indicating what's wrong.
  279: #
  280: sub is_code_valid {
  281:     my ($code_value, $code_option) = @_;
  282:     my ($code_type, $code_length) = ('letter', 6);	# defaults.
  283:     open(FG, $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
  284:     foreach my $line (<FG>) {
  285: 	my ($name, $type, $length) = (split(/:/, $line))[0,2,4];
  286: 	if($name eq $code_option) {
  287: 	    $code_length = $length;
  288: 	    if($type eq 'number') {
  289: 		$code_type = 'number';
  290: 	    }
  291: 	}
  292:     }
  293:     my $valid;
  294:     if ($code_type eq 'number') {
  295: 	return &is_valid_numeric_code($code_value, $code_length);
  296:     } else {
  297: 	return &is_valid_alpha_code($code_value, $code_length);
  298:     }
  299: 
  300: }
  301: 
  302: #   Compare two students by name.  The students are in the form
  303: #   returned by the helper:
  304: #      user:domain:section:last,   first:status
  305: #   This is a helper function for the perl sort built-in  therefore:
  306: # Implicit Inputs:
  307: #    $a     - The first element to compare (global)
  308: #    $b     - The second element to compare (global)
  309: # Returns:
  310: #   -1   - $a < $b
  311: #    0   - $a == $b
  312: #   +1   - $a > $b
  313: #   Note that the initial comparison is done on the last names with the
  314: #   first names only used to break the tie.
  315: #
  316: #
  317: sub compare_names {
  318:     #  First split the names up into the primary fields.
  319: 
  320:     my ($u1, $d1, $s1, $n1, $stat1) = split(/:/, $a);
  321:     my ($u2, $d2, $s2, $n2, $stat2) = split(/:/, $b);
  322: 
  323:     # Now split the last name and first name of each n:
  324:     #
  325: 
  326:     my ($l1,$f1) = split(/,/, $n1);
  327:     my ($l2,$f2) = split(/,/, $n2);
  328: 
  329:     # We don't bother to remove the leading/trailing whitespace from the
  330:     # firstname, unless the last names compare identical.
  331: 
  332:     if($l1 lt $l2) {
  333: 	return -1;
  334:     }
  335:     if($l1 gt $l2) {
  336: 	return  1;
  337:     }
  338: 
  339:     # Break the tie on the first name, but there are leading (possibly trailing
  340:     # whitespaces to get rid of first 
  341:     #
  342:     $f1 =~ s/^\s+//;		# Remove leading...
  343:     $f1 =~ s/\s+$//;		# Trailing spaces from first 1...
  344:     
  345:     $f2 =~ s/^\s+//;
  346:     $f2 =~ s/\s+$//;		# And the same for first 2...
  347: 
  348:     if($f1 lt $f2) {
  349: 	return -1;
  350:     }
  351:     if($f1 gt $f2) {
  352: 	return 1;
  353:     }
  354:     
  355:     #  Must be the same name.
  356: 
  357:     return 0;
  358: }
  359: 
  360: sub latex_header_footer_remove {
  361:     my $text = shift;
  362:     $text =~ s/\\end{document}//;
  363:     $text =~ s/\\documentclass([^&]*)\\begin{document}//;
  364:     return $text;
  365: }
  366: #
  367: #  If necessary, encapsulate text inside 
  368: #  a minipage env.
  369: #  necessity is determined by the problem_split param.
  370: #
  371: sub encapsulate_minipage {
  372:     my ($text) = @_;
  373:     if (!($env{'form.problem.split'} =~ /yes/i)) {
  374: 	$text = '\begin{minipage}{\textwidth}'.$text.'\end{minipage}';
  375:     }
  376:     return $text;
  377: }
  378: #
  379: #  The NUMBER_TO_PRINT and SPLIT_PDFS
  380: #  variables interact, this sub looks at these two parameters
  381: #  and comes up with a final value for NUMBER_TO_PRINT which can be:
  382: #     all     - if SPLIT_PDFS eq 'all'.
  383: #     1       - if SPLIT_PDFS eq 'oneper'
  384: #     section - if SPLIT_PDFS eq 'sections'
  385: #     <unchanged> - if SPLIT_PDFS eq 'usenumber'
  386: #
  387: sub adjust_number_to_print {
  388:     my $helper = shift;
  389: 
  390:     my $split_pdf = $helper->{'VARS'}->{'SPLIT_PDFS'};
  391:     
  392:     if ($split_pdf eq 'all') {
  393: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 'all';
  394:     } elsif ($split_pdf eq 'oneper') {
  395: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 1;
  396:     } elsif ($split_pdf eq 'sections') {
  397: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 'section';
  398:     } elsif ($split_pdf eq 'usenumber') {
  399: 	#  Unmodified.
  400:     } else {
  401: 	# Error!!!!
  402: 
  403: 	croak "bad SPLIT_PDFS: $split_pdf in lonprintout::adjust_number_to_print";
  404:     }
  405: }
  406: 
  407: sub character_chart {
  408:     my $result = shift;	
  409:     $result =~ s/&\#0?0?(7|9);//g;
  410:     $result =~ s/&\#0?(10|13);//g;
  411:     $result =~ s/&\#0?32;/ /g;
  412:     $result =~ s/&\#0?33;/!/g;
  413:     $result =~ s/&(\#0?34|quot);/\"/g;
  414:     $result =~ s/&\#0?35;/\\\#/g;
  415:     $result =~ s/&\#0?36;/\\\$/g;
  416:     $result =~ s/&\#0?37;/\\%/g; 
  417:     $result =~ s/&(\#0?38|amp);/\\&/g; 
  418:     $result =~ s/&\#(0?39|146);/\'/g;
  419:     $result =~ s/&\#0?40;/(/g;
  420:     $result =~ s/&\#0?41;/)/g;
  421:     $result =~ s/&\#0?42;/\*/g;
  422:     $result =~ s/&\#0?43;/\+/g;
  423:     $result =~ s/&\#(0?44|130);/,/g;
  424:     $result =~ s/&\#0?45;/-/g;
  425:     $result =~ s/&\#0?46;/\./g;
  426:     $result =~ s/&\#0?47;/\//g;
  427:     $result =~ s/&\#0?48;/0/g;
  428:     $result =~ s/&\#0?49;/1/g;
  429:     $result =~ s/&\#0?50;/2/g;
  430:     $result =~ s/&\#0?51;/3/g;
  431:     $result =~ s/&\#0?52;/4/g;
  432:     $result =~ s/&\#0?53;/5/g;
  433:     $result =~ s/&\#0?54;/6/g;
  434:     $result =~ s/&\#0?55;/7/g;
  435:     $result =~ s/&\#0?56;/8/g;
  436:     $result =~ s/&\#0?57;/9/g;
  437:     $result =~ s/&\#0?58;/:/g;
  438:     $result =~ s/&\#0?59;/;/g;
  439:     $result =~ s/&(\#0?60|lt|\#139);/\$<\$/g;
  440:     $result =~ s/&\#0?61;/\\ensuremath\{=\}/g;
  441:     $result =~ s/&(\#0?62|gt|\#155);/\\ensuremath\{>\}/g;
  442:     $result =~ s/&\#0?63;/\?/g;
  443:     $result =~ s/&\#0?65;/A/g;
  444:     $result =~ s/&\#0?66;/B/g;
  445:     $result =~ s/&\#0?67;/C/g;
  446:     $result =~ s/&\#0?68;/D/g;
  447:     $result =~ s/&\#0?69;/E/g;
  448:     $result =~ s/&\#0?70;/F/g;
  449:     $result =~ s/&\#0?71;/G/g;
  450:     $result =~ s/&\#0?72;/H/g;
  451:     $result =~ s/&\#0?73;/I/g;
  452:     $result =~ s/&\#0?74;/J/g;
  453:     $result =~ s/&\#0?75;/K/g;
  454:     $result =~ s/&\#0?76;/L/g;
  455:     $result =~ s/&\#0?77;/M/g;
  456:     $result =~ s/&\#0?78;/N/g;
  457:     $result =~ s/&\#0?79;/O/g;
  458:     $result =~ s/&\#0?80;/P/g;
  459:     $result =~ s/&\#0?81;/Q/g;
  460:     $result =~ s/&\#0?82;/R/g;
  461:     $result =~ s/&\#0?83;/S/g;
  462:     $result =~ s/&\#0?84;/T/g;
  463:     $result =~ s/&\#0?85;/U/g;
  464:     $result =~ s/&\#0?86;/V/g;
  465:     $result =~ s/&\#0?87;/W/g;
  466:     $result =~ s/&\#0?88;/X/g;
  467:     $result =~ s/&\#0?89;/Y/g;
  468:     $result =~ s/&\#0?90;/Z/g;
  469:     $result =~ s/&\#0?91;/[/g;
  470:     $result =~ s/&\#0?92;/\\ensuremath\{\\setminus\}/g;
  471:     $result =~ s/&\#0?93;/]/g;
  472:     $result =~ s/&\#(0?94|136);/\\ensuremath\{\\wedge\}/g;
  473:     $result =~ s/&\#(0?95|138|154);/\\underline{\\makebox[2mm]{\\strut}}/g;
  474:     $result =~ s/&\#(0?96|145);/\`/g;
  475:     $result =~ s/&\#0?97;/a/g;
  476:     $result =~ s/&\#0?98;/b/g;
  477:     $result =~ s/&\#0?99;/c/g;
  478:     $result =~ s/&\#100;/d/g;
  479:     $result =~ s/&\#101;/e/g;
  480:     $result =~ s/&\#102;/f/g;
  481:     $result =~ s/&\#103;/g/g;
  482:     $result =~ s/&\#104;/h/g;
  483:     $result =~ s/&\#105;/i/g;
  484:     $result =~ s/&\#106;/j/g;
  485:     $result =~ s/&\#107;/k/g;
  486:     $result =~ s/&\#108;/l/g;
  487:     $result =~ s/&\#109;/m/g;
  488:     $result =~ s/&\#110;/n/g;
  489:     $result =~ s/&\#111;/o/g;
  490:     $result =~ s/&\#112;/p/g;
  491:     $result =~ s/&\#113;/q/g;
  492:     $result =~ s/&\#114;/r/g;
  493:     $result =~ s/&\#115;/s/g;
  494:     $result =~ s/&\#116;/t/g;
  495:     $result =~ s/&\#117;/u/g;
  496:     $result =~ s/&\#118;/v/g;
  497:     $result =~ s/&\#119;/w/g;
  498:     $result =~ s/&\#120;/x/g;
  499:     $result =~ s/&\#121;/y/g;
  500:     $result =~ s/&\#122;/z/g;
  501:     $result =~ s/&\#123;/\\{/g;
  502:     $result =~ s/&\#124;/\|/g;
  503:     $result =~ s/&\#125;/\\}/g;
  504:     $result =~ s/&\#126;/\~/g;
  505:     $result =~ s/&\#131;/\\textflorin /g;
  506:     $result =~ s/&\#132;/\"/g;
  507:     $result =~ s/&\#133;/\\ensuremath\{\\ldots\}/g;
  508:     $result =~ s/&\#134;/\\ensuremath\{\\dagger\}/g;
  509:     $result =~ s/&\#135;/\\ensuremath\{\\ddagger\}/g;
  510:     $result =~ s/&\#137;/\\textperthousand /g;
  511:     $result =~ s/&\#140;/{\\OE}/g;
  512:     $result =~ s/&\#147;/\`\`/g;
  513:     $result =~ s/&\#148;/\'\'/g;
  514:     $result =~ s/&\#149;/\\ensuremath\{\\bullet\}/g;
  515:     $result =~ s/&(\#150|\#8211);/--/g;
  516:     $result =~ s/&\#151;/---/g;
  517:     $result =~ s/&\#152;/\\ensuremath\{\\sim\}/g;
  518:     $result =~ s/&\#153;/\\texttrademark /g;
  519:     $result =~ s/&\#156;/\\oe/g;
  520:     $result =~ s/&\#159;/\\\"Y/g;
  521:     $result =~ s/&(\#160|nbsp);/~/g;
  522:     $result =~ s/&(\#161|iexcl);/!\`/g;
  523:     $result =~ s/&(\#162|cent);/\\textcent /g;
  524:     $result =~ s/&(\#163|pound);/\\pounds /g; 
  525:     $result =~ s/&(\#164|curren);/\\textcurrency /g;
  526:     $result =~ s/&(\#165|yen);/\\textyen /g;
  527:     $result =~ s/&(\#166|brvbar);/\\textbrokenbar /g;
  528:     $result =~ s/&(\#167|sect);/\\textsection /g;
  529:     $result =~ s/&(\#168|uml);/\\texthighdieresis /g;
  530:     $result =~ s/&(\#169|copy);/\\copyright /g;
  531:     $result =~ s/&(\#170|ordf);/\\textordfeminine /g;
  532:     $result =~ s/&(\#172|not);/\\ensuremath\{\\neg\}/g;
  533:     $result =~ s/&(\#173|shy);/ - /g;
  534:     $result =~ s/&(\#174|reg);/\\textregistered /g;
  535:     $result =~ s/&(\#175|macr);/\\ensuremath\{^{-}\}/g;
  536:     $result =~ s/&(\#176|deg);/\\ensuremath\{^{\\circ}\}/g;
  537:     $result =~ s/&(\#177|plusmn);/\\ensuremath\{\\pm\}/g;
  538:     $result =~ s/&(\#178|sup2);/\\ensuremath\{^2\}/g;
  539:     $result =~ s/&(\#179|sup3);/\\ensuremath\{^3\}/g;
  540:     $result =~ s/&(\#180|acute);/\\textacute /g;
  541:     $result =~ s/&(\#181|micro);/\\ensuremath\{\\mu\}/g;
  542:     $result =~ s/&(\#182|para);/\\P/g;
  543:     $result =~ s/&(\#183|middot);/\\ensuremath\{\\cdot\}/g;
  544:     $result =~ s/&(\#184|cedil);/\\c{\\strut}/g;
  545:     $result =~ s/&(\#185|sup1);/\\ensuremath\{^1\}/g;
  546:     $result =~ s/&(\#186|ordm);/\\textordmasculine /g;
  547:     $result =~ s/&(\#188|frac14);/\\textonequarter /g;
  548:     $result =~ s/&(\#189|frac12);/\\textonehalf /g;
  549:     $result =~ s/&(\#190|frac34);/\\textthreequarters /g;
  550:     $result =~ s/&(\#191|iquest);/?\`/g;   
  551:     $result =~ s/&(\#192|Agrave);/\\\`{A}/g;  
  552:     $result =~ s/&(\#193|Aacute);/\\\'{A}/g; 
  553:     $result =~ s/&(\#194|Acirc);/\\^{A}/g;
  554:     $result =~ s/&(\#195|Atilde);/\\~{A}/g;
  555:     $result =~ s/&(\#196|Auml);/\\\"{A}/g; 
  556:     $result =~ s/&(\#197|Aring);/{\\AA}/g;
  557:     $result =~ s/&(\#198|AElig);/{\\AE}/g;
  558:     $result =~ s/&(\#199|Ccedil);/\\c{c}/g;
  559:     $result =~ s/&(\#200|Egrave);/\\\`{E}/g;  
  560:     $result =~ s/&(\#201|Eacute);/\\\'{E}/g;    
  561:     $result =~ s/&(\#202|Ecirc);/\\^{E}/g;
  562:     $result =~ s/&(\#203|Euml);/\\\"{E}/g;
  563:     $result =~ s/&(\#204|Igrave);/\\\`{I}/g;
  564:     $result =~ s/&(\#205|Iacute);/\\\'{I}/g;    
  565:     $result =~ s/&(\#206|Icirc);/\\^{I}/g;
  566:     $result =~ s/&(\#207|Iuml);/\\\"{I}/g;    
  567:     $result =~ s/&(\#209|Ntilde);/\\~{N}/g;
  568:     $result =~ s/&(\#210|Ograve);/\\\`{O}/g;
  569:     $result =~ s/&(\#211|Oacute);/\\\'{O}/g;
  570:     $result =~ s/&(\#212|Ocirc);/\\^{O}/g;
  571:     $result =~ s/&(\#213|Otilde);/\\~{O}/g;
  572:     $result =~ s/&(\#214|Ouml);/\\\"{O}/g;    
  573:     $result =~ s/&(\#215|times);/\\ensuremath\{\\times\}/g;
  574:     $result =~ s/&(\#216|Oslash);/{\\O}/g;
  575:     $result =~ s/&(\#217|Ugrave);/\\\`{U}/g;    
  576:     $result =~ s/&(\#218|Uacute);/\\\'{U}/g;
  577:     $result =~ s/&(\#219|Ucirc);/\\^{U}/g;
  578:     $result =~ s/&(\#220|Uuml);/\\\"{U}/g;
  579:     $result =~ s/&(\#221|Yacute);/\\\'{Y}/g;
  580:     $result =~ s/&(\#223|szlig);/{\\ss}/g;
  581:     $result =~ s/&(\#224|agrave);/\\\`{a}/g;
  582:     $result =~ s/&(\#225|aacute);/\\\'{a}/g;
  583:     $result =~ s/&(\#226|acirc);/\\^{a}/g;
  584:     $result =~ s/&(\#227|atilde);/\\~{a}/g;
  585:     $result =~ s/&(\#228|auml);/\\\"{a}/g;
  586:     $result =~ s/&(\#229|aring);/{\\aa}/g;
  587:     $result =~ s/&(\#230|aelig);/{\\ae}/g;
  588:     $result =~ s/&(\#231|ccedil);/\\c{c}/g;
  589:     $result =~ s/&(\#232|egrave);/\\\`{e}/g;
  590:     $result =~ s/&(\#233|eacute);/\\\'{e}/g;
  591:     $result =~ s/&(\#234|ecirc);/\\^{e}/g;
  592:     $result =~ s/&(\#235|euml);/\\\"{e}/g;
  593:     $result =~ s/&(\#236|igrave);/\\\`{i}/g;
  594:     $result =~ s/&(\#237|iacute);/\\\'{i}/g;
  595:     $result =~ s/&(\#238|icirc);/\\^{i}/g;
  596:     $result =~ s/&(\#239|iuml);/\\\"{i}/g;
  597:     $result =~ s/&(\#240|eth);/\\ensuremath\{\\partial\}/g;
  598:     $result =~ s/&(\#241|ntilde);/\\~{n}/g;
  599:     $result =~ s/&(\#242|ograve);/\\\`{o}/g;
  600:     $result =~ s/&(\#243|oacute);/\\\'{o}/g;
  601:     $result =~ s/&(\#244|ocirc);/\\^{o}/g;
  602:     $result =~ s/&(\#245|otilde);/\\~{o}/g;
  603:     $result =~ s/&(\#246|ouml);/\\\"{o}/g;
  604:     $result =~ s/&(\#247|divide);/\\ensuremath\{\\div\}/g;
  605:     $result =~ s/&(\#248|oslash);/{\\o}/g;
  606:     $result =~ s/&(\#249|ugrave);/\\\`{u}/g; 
  607:     $result =~ s/&(\#250|uacute);/\\\'{u}/g;
  608:     $result =~ s/&(\#251|ucirc);/\\^{u}/g;
  609:     $result =~ s/&(\#252|uuml);/\\\"{u}/g;
  610:     $result =~ s/&(\#253|yacute);/\\\'{y}/g;
  611:     $result =~ s/&(\#255|yuml);/\\\"{y}/g;
  612:     $result =~ s/&\#295;/\\ensuremath\{\\hbar\}/g;
  613:     $result =~ s/&\#952;/\\ensuremath\{\\theta\}/g;
  614: #Greek Alphabet
  615:     $result =~ s/&(alpha|\#945);/\\ensuremath\{\\alpha\}/g;
  616:     $result =~ s/&(beta|\#946);/\\ensuremath\{\\beta\}/g;
  617:     $result =~ s/&(gamma|\#947);/\\ensuremath\{\\gamma\}/g;
  618:     $result =~ s/&(delta|\#948);/\\ensuremath\{\\delta\}/g;
  619:     $result =~ s/&(epsilon|\#949);/\\ensuremath\{\\epsilon\}/g;
  620:     $result =~ s/&(zeta|\#950);/\\ensuremath\{\\zeta\}/g;
  621:     $result =~ s/&(eta|\#951);/\\ensuremath\{\\eta\}/g;
  622:     $result =~ s/&(theta|\#952);/\\ensuremath\{\\theta\}/g;
  623:     $result =~ s/&(iota|\#953);/\\ensuremath\{\\iota\}/g;
  624:     $result =~ s/&(kappa|\#954);/\\ensuremath\{\\kappa\}/g;
  625:     $result =~ s/&(lambda|\#955);/\\ensuremath\{\\lambda\}/g;
  626:     $result =~ s/&(mu|\#956);/\\ensuremath\{\\mu\}/g;
  627:     $result =~ s/&(nu|\#957);/\\ensuremath\{\\nu\}/g;
  628:     $result =~ s/&(xi|\#958);/\\ensuremath\{\\xi\}/g;
  629:     $result =~ s/&(omicron|\#959);/o/g;
  630:     $result =~ s/&(pi|\#960);/\\ensuremath\{\\pi\}/g;
  631:     $result =~ s/&(rho|\#961);/\\ensuremath\{\\rho\}/g;
  632:     $result =~ s/&(sigma|\#963);/\\ensuremath\{\\sigma\}/g;
  633:     $result =~ s/&(tau|\#964);/\\ensuremath\{\\tau\}/g;
  634:     $result =~ s/&(upsilon|\#965);/\\ensuremath\{\\upsilon\}/g;
  635:     $result =~ s/&(phi|\#966);/\\ensuremath\{\\phi\}/g;
  636:     $result =~ s/&(chi|\#967);/\\ensuremath\{\\chi\}/g;
  637:     $result =~ s/&(psi|\#968);/\\ensuremath\{\\psi\}/g;
  638:     $result =~ s/&(omega|\#969);/\\ensuremath\{\\omega\}/g;
  639:     $result =~ s/&(thetasym|\#977);/\\ensuremath\{\\vartheta\}/g;
  640:     $result =~ s/&(piv|\#982);/\\ensuremath\{\\varpi\}/g;
  641:     $result =~ s/&(Alpha|\#913);/A/g;
  642:     $result =~ s/&(Beta|\#914);/B/g;
  643:     $result =~ s/&(Gamma|\#915);/\\ensuremath\{\\Gamma\}/g;
  644:     $result =~ s/&(Delta|\#916);/\\ensuremath\{\\Delta\}/g;
  645:     $result =~ s/&(Epsilon|\#917);/E/g;
  646:     $result =~ s/&(Zeta|\#918);/Z/g;
  647:     $result =~ s/&(Eta|\#919);/H/g;
  648:     $result =~ s/&(Theta|\#920);/\\ensuremath\{\\Theta\}/g;
  649:     $result =~ s/&(Iota|\#921);/I/g;
  650:     $result =~ s/&(Kappa|\#922);/K/g;
  651:     $result =~ s/&(Lambda|\#923);/\\ensuremath\{\\Lambda\}/g;
  652:     $result =~ s/&(Mu|\#924);/M/g;
  653:     $result =~ s/&(Nu|\#925);/N/g;
  654:     $result =~ s/&(Xi|\#926);/\\ensuremath\{\\Xi\}/g;
  655:     $result =~ s/&(Omicron|\#927);/O/g;
  656:     $result =~ s/&(Pi|\#928);/\\ensuremath\{\\Pi\}/g;
  657:     $result =~ s/&(Rho|\#929);/P/g;
  658:     $result =~ s/&(Sigma|\#931);/\\ensuremath\{\\Sigma\}/g;
  659:     $result =~ s/&(Tau|\#932);/T/g;
  660:     $result =~ s/&(Upsilon|\#933);/\\ensuremath\{\\Upsilon\}/g;
  661:     $result =~ s/&(Phi|\#934);/\\ensuremath\{\\Phi\}/g;
  662:     $result =~ s/&(Chi|\#935);/X/g;
  663:     $result =~ s/&(Psi|\#936);/\\ensuremath\{\\Psi\}/g;
  664:     $result =~ s/&(Omega|\#937);/\\ensuremath\{\\Omega\}/g;
  665: #Arrows (extended HTML 4.01)
  666:     $result =~ s/&(larr|\#8592);/\\ensuremath\{\\leftarrow\}/g;
  667:     $result =~ s/&(uarr|\#8593);/\\ensuremath\{\\uparrow\}/g;
  668:     $result =~ s/&(rarr|\#8594);/\\ensuremath\{\\rightarrow\}/g;
  669:     $result =~ s/&(darr|\#8595);/\\ensuremath\{\\downarrow\}/g;
  670:     $result =~ s/&(harr|\#8596);/\\ensuremath\{\\leftrightarrow\}/g;
  671:     $result =~ s/&(lArr|\#8656);/\\ensuremath\{\\Leftarrow\}/g;
  672:     $result =~ s/&(uArr|\#8657);/\\ensuremath\{\\Uparrow\}/g;
  673:     $result =~ s/&(rArr|\#8658);/\\ensuremath\{\\Rightarrow\}/g;
  674:     $result =~ s/&(dArr|\#8659);/\\ensuremath\{\\Downarrow\}/g;
  675:     $result =~ s/&(hArr|\#8660);/\\ensuremath\{\\Leftrightarrow\}/g;
  676: #Mathematical Operators (extended HTML 4.01)
  677:     $result =~ s/&(forall|\#8704);/\\ensuremath\{\\forall\}/g;
  678:     $result =~ s/&(part|\#8706);/\\ensuremath\{\\partial\}/g;
  679:     $result =~ s/&(exist|\#8707);/\\ensuremath\{\\exists\}/g;
  680:     $result =~ s/&(empty|\#8709);/\\ensuremath\{\\emptyset\}/g;
  681:     $result =~ s/&(nabla|\#8711);/\\ensuremath\{\\nabla\}/g;
  682:     $result =~ s/&(isin|\#8712);/\\ensuremath\{\\in\}/g;
  683:     $result =~ s/&(notin|\#8713);/\\ensuremath\{\\notin\}/g;
  684:     $result =~ s/&(ni|\#8715);/\\ensuremath\{\\ni\}/g;
  685:     $result =~ s/&(prod|\#8719);/\\ensuremath\{\\prod\}/g;
  686:     $result =~ s/&(sum|\#8721);/\\ensuremath\{\\sum\}/g;
  687:     $result =~ s/&(minus|\#8722);/\\ensuremath\{-\}/g;
  688:     $result =~ s/–/\\ensuremath\{-\}/g;
  689:     $result =~ s/&(lowast|\#8727);/\\ensuremath\{*\}/g;
  690:     $result =~ s/&(radic|\#8730);/\\ensuremath\{\\surd\}/g;
  691:     $result =~ s/&(prop|\#8733);/\\ensuremath\{\\propto\}/g;
  692:     $result =~ s/&(infin|\#8734);/\\ensuremath\{\\infty\}/g;
  693:     $result =~ s/&(ang|\#8736);/\\ensuremath\{\\angle\}/g;
  694:     $result =~ s/&(and|\#8743);/\\ensuremath\{\\wedge\}/g;
  695:     $result =~ s/&(or|\#8744);/\\ensuremath\{\\vee\}/g;
  696:     $result =~ s/&(cap|\#8745);/\\ensuremath\{\\cap\}/g;
  697:     $result =~ s/&(cup|\#8746);/\\ensuremath\{\\cup\}/g;
  698:     $result =~ s/&(int|\#8747);/\\ensuremath\{\\int\}/g;
  699:     $result =~ s/&(sim|\#8764);/\\ensuremath\{\\sim\}/g;
  700:     $result =~ s/&(cong|\#8773);/\\ensuremath\{\\cong\}/g;
  701:     $result =~ s/&(asymp|\#8776);/\\ensuremath\{\\approx\}/g;
  702:     $result =~ s/&(ne|\#8800);/\\ensuremath\{\\not=\}/g;
  703:     $result =~ s/&(equiv|\#8801);/\\ensuremath\{\\equiv\}/g;
  704:     $result =~ s/&(le|\#8804);/\\ensuremath\{\\leq\}/g;
  705:     $result =~ s/&(ge|\#8805);/\\ensuremath\{\\geq\}/g;
  706:     $result =~ s/&(sub|\#8834);/\\ensuremath\{\\subset\}/g;
  707:     $result =~ s/&(sup|\#8835);/\\ensuremath\{\\supset\}/g;
  708:     $result =~ s/&(nsub|\#8836);/\\ensuremath\{\\not\\subset\}/g;
  709:     $result =~ s/&(sube|\#8838);/\\ensuremath\{\\subseteq\}/g;
  710:     $result =~ s/&(supe|\#8839);/\\ensuremath\{\\supseteq\}/g;
  711:     $result =~ s/&(oplus|\#8853);/\\ensuremath\{\\oplus\}/g;
  712:     $result =~ s/&(otimes|\#8855);/\\ensuremath\{\\otimes\}/g;
  713:     $result =~ s/&(perp|\#8869);/\\ensuremath\{\\perp\}/g;
  714:     $result =~ s/&(sdot|\#8901);/\\ensuremath\{\\cdot\}/g;
  715: #Geometric Shapes (extended HTML 4.01)
  716:     $result =~ s/&(loz|\#9674);/\\ensuremath\{\\Diamond\}/g;
  717: #Miscellaneous Symbols (extended HTML 4.01)
  718:     $result =~ s/&(spades|\#9824);/\\ensuremath\{\\spadesuit\}/g;
  719:     $result =~ s/&(clubs|\#9827);/\\ensuremath\{\\clubsuit\}/g;
  720:     $result =~ s/&(hearts|\#9829);/\\ensuremath\{\\heartsuit\}/g;
  721:     $result =~ s/&(diams|\#9830);/\\ensuremath\{\\diamondsuit\}/g;
  722: #   Chemically useful 'things' contributed by Hon Kie (bug 4652).
  723:     $result =~ s/&\#8636;/\\ensuremath\{\\leftharpoonup\}/g;
  724:     $result =~ s/&\#8637;/\\ensuremath\{\\leftharpoondown\}/g;
  725:     $result =~ s/&\#8640;/\\ensuremath\{\\rightharpoonup\}/g;
  726:     $result =~ s/&\#8641;/\\ensuremath\{\\rightharpoondown\}/g;
  727:     $result =~ s/&\#8652;/\\ensuremath\{\\rightleftharpoons\}/g;
  728:     $result =~ s/&\#8605;/\\ensuremath\{\\leadsto\}/g;
  729:     $result =~ s/&\#8617;/\\ensuremath\{\\hookleftarrow\}/g;
  730:     $result =~ s/&\#8618;/\\ensuremath\{\\hookrightarrow\}/g;
  731:     $result =~ s/&\#8614;/\\ensuremath\{\\mapsto\}/g;
  732:     $result =~ s/&\#8599;/\\ensuremath\{\\nearrow\}/g;
  733:     $result =~ s/&\#8600;/\\ensuremath\{\\searrow\}/g;
  734:     $result =~ s/&\#8601;/\\ensuremath\{\\swarrow\}/g;
  735:     $result =~ s/&\#8598;/\\ensuremath\{\\nwarrow\}/g;
  736:     return $result;
  737: }
  738: 
  739: 
  740:                   #width, height, oddsidemargin, evensidemargin, topmargin
  741: my %page_formats=
  742:     ('letter' => {
  743: 	 'book' => {
  744: 	     '1' => [ '7.1 in','9.8 in', '-0.57 in','-0.57 in','0.275 in'],
  745: 	     '2' => ['3.66 in','9.8 in', '-0.57 in','-0.57 in','0.275 in']
  746: 	 },
  747: 	 'album' => {
  748: 	     '1' => [ '8.8 in', '6.8 in','-0.55 in',  '-0.55 in','0.394 in'],
  749: 	     '2' => [ '4.8 in', '6.8 in','-0.5 in', '-1.0 in','3.5 in']
  750: 	 },
  751:      },
  752:      'legal' => {
  753: 	 'book' => {
  754: 	     '1' => ['7.1 in','13 in',,'-0.57 in','-0.57 in','-0.5 in'],
  755: 	     '2' => ['3.16 in','13 in','-0.57 in','-0.57 in','-0.5 in']
  756: 	 },
  757: 	 'album' => {
  758: 	     '1' => ['12 in','7.1 in',,'-0.57 in','-0.57 in','-0.5 in'],
  759:              '2' => ['6.0 in','7.1 in','-1 in','-1 in','5 in']
  760:           },
  761:      },
  762:      'tabloid' => {
  763: 	 'book' => {
  764: 	     '1' => ['9.8 in','16 in','-0.57 in','-0.57 in','-0.5 in'],
  765: 	     '2' => ['4.9 in','16 in','-0.57 in','-0.57 in','-0.5 in']
  766: 	 },
  767: 	 'album' => {
  768: 	     '1' => ['16 in','9.8 in','-0.57 in','-0.57 in','-0.5 in'],
  769: 	     '2' => ['16 in','4.9 in','-0.57 in','-0.57 in','-0.5 in']
  770:           },
  771:      },
  772:      'executive' => {
  773: 	 'book' => {
  774: 	     '1' => ['6.8 in','9 in','-0.57 in','-0.57 in','1.2 in'],
  775: 	     '2' => ['3.1 in','9 in','-0.57 in','-0.57 in','1.2 in']
  776: 	 },
  777: 	 'album' => {
  778: 	     '1' => [],
  779: 	     '2' => []
  780:           },
  781:      },
  782:      'a2' => {
  783: 	 'book' => {
  784: 	     '1' => [],
  785: 	     '2' => []
  786: 	 },
  787: 	 'album' => {
  788: 	     '1' => [],
  789: 	     '2' => []
  790:           },
  791:      },
  792:      'a3' => {
  793: 	 'book' => {
  794: 	     '1' => [],
  795: 	     '2' => []
  796: 	 },
  797: 	 'album' => {
  798: 	     '1' => [],
  799: 	     '2' => []
  800:           },
  801:      },
  802:      'a4' => {
  803: 	 'book' => {
  804: 	     '1' => ['17.6 cm','27.2 cm','-1.397 cm','-2.11 cm','-1.27 cm'],
  805: 	     '2' => [ '9.1 cm','27.2 cm','-1.397 cm','-2.11 cm','-1.27 cm']
  806: 	 },
  807: 	 'album' => {
  808: 	     '1' => ['21.59 cm','19.558 cm','-1.397cm','-2.11 cm','0 cm'],
  809: 	     '2' => ['9.91 cm','19.558 cm','-1.397 cm','-2.11 cm','0 cm']
  810: 	 },
  811:      },
  812:      'a5' => {
  813: 	 'book' => {
  814: 	     '1' => [],
  815: 	     '2' => []
  816: 	 },
  817: 	 'album' => {
  818: 	     '1' => [],
  819: 	     '2' => []
  820:           },
  821:      },
  822:      'a6' => {
  823: 	 'book' => {
  824: 	     '1' => [],
  825: 	     '2' => []
  826: 	 },
  827: 	 'album' => {
  828: 	     '1' => [],
  829: 	     '2' => []
  830:           },
  831:      },
  832:      );
  833: 
  834: sub page_format {
  835: #
  836: #Supported paper format: "Letter [8 1/2x11 in]",      "Legal [8 1/2x14 in]",
  837: #                        "Ledger/Tabloid [11x17 in]", "Executive [7 1/2x10 in]",
  838: #                        "A2 [420x594 mm]",           "A3 [297x420 mm]",
  839: #                        "A4 [210x297 mm]",           "A5 [148x210 mm]",
  840: #                        "A6 [105x148 mm]"
  841: # 
  842:     my ($papersize,$layout,$numberofcolumns) = @_; 
  843:     return @{$page_formats{$papersize}->{$layout}->{$numberofcolumns}};
  844: }
  845: 
  846: 
  847: sub get_name {
  848:     my ($uname,$udom)=@_;
  849:     if (!defined($uname)) { $uname=$env{'user.name'}; }
  850:     if (!defined($udom)) { $udom=$env{'user.domain'}; }
  851:     my $plainname=&Apache::loncommon::plainname($uname,$udom);
  852:     if ($plainname=~/^\s*$/) { $plainname=$uname.'@'.$udom; }
  853:    $plainname=&Apache::lonxml::latex_special_symbols($plainname,'header');
  854:     return $plainname;
  855: }
  856: 
  857: sub get_course {
  858:     my $courseidinfo;
  859:     if (defined($env{'request.course.id'})) {
  860: 	$courseidinfo = &Apache::lonxml::latex_special_symbols(&unescape($env{'course.'.$env{'request.course.id'}.'.description'}),'header');
  861:     }
  862:     return $courseidinfo;
  863: }
  864: 
  865: sub page_format_transformation {
  866:     my ($papersize,$layout,$numberofcolumns,$choice,$text,$assignment,$tableofcontents,$indexlist,$selectionmade) = @_; 
  867:     my ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin);
  868: 
  869:     if ($selectionmade eq '4') {
  870: 	$assignment='Problems from the Whole Course';
  871:     } else {
  872: 	$assignment=&Apache::lonxml::latex_special_symbols($assignment,'header');
  873:     }
  874:     ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin) = &page_format($papersize,$layout,$numberofcolumns,$topmargin);
  875: 
  876: 
  877:     my $name = &get_name();
  878:     my $courseidinfo = &get_course();
  879:     if (defined($courseidinfo)) { $courseidinfo=' - '.$courseidinfo }
  880:     my $header_text  = $parmhash{'print_header_format'};
  881:     $header_text     = &format_page_header($textwidth, $header_text, $assignment,
  882: 					   $courseidinfo, $name);
  883:     my $topmargintoinsert = '';
  884:     if ($topmargin ne '0') {$topmargintoinsert='\setlength{\topmargin}{'.$topmargin.'}';}
  885:     my $fancypagestatement='';
  886:     if ($numberofcolumns eq '2') {
  887: 	$fancypagestatement="\\fancyhead{}\\fancyhead[LO]{$header_text}";
  888:     } else {
  889: 	$fancypagestatement="\\rhead{}\\chead{}\\lhead{$header_text}";
  890:     }
  891:     if ($layout eq 'album') {
  892: 	    $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\\begin{document}\\voffset=-0\.8 cm\\setcounter{page}{1}\n /;
  893:     } elsif ($layout eq 'book') {
  894: 	if ($choice ne 'All class print') { 
  895: 	    $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\\begin{document}\n\\voffset=-0\.8 cm\\setcounter{page}{1}\n/;
  896: 	} else {
  897: 	    $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{}\\begin{document}\\voffset=-0\.8cm\n\\setcounter{page}{1}  \\vskip 5 mm\n /;
  898: 	}
  899: 	if ($papersize eq 'a4') {
  900: 	    $text =~ s/(\\begin{document})/$1\\special{papersize=210mm,297mm}/;
  901: 	}
  902:     }
  903:     if ($tableofcontents eq 'yes') {$text=~s/(\\setcounter\{page\}\{1\})/$1 \\tableofcontents\\newpage /;}
  904:     if ($indexlist eq 'yes') {
  905: 	$text=~s/(\\begin{document})/\\makeindex $1/;
  906: 	$text=~s/(\\end{document})/\\strut\\\\\\strut\\printindex $1/;
  907:     }
  908:     return $text;
  909: }
  910: 
  911: 
  912: sub page_cleanup {
  913:     my $result = shift;	
  914:  
  915:     $result =~ m/\\end{document}(\d*)$/;
  916:     my $number_of_columns = $1;
  917:     my $insert = '{';
  918:     for (my $id=1;$id<=$number_of_columns;$id++) { $insert .='l'; }
  919:     $insert .= '}';
  920:     $result =~ s/(\\begin{longtable})INSERTTHEHEADOFLONGTABLE\\endfirsthead\\endhead/$1$insert/g;
  921:     $result =~ s/&\s*REMOVETHEHEADOFLONGTABLE\\\\/\\\\/g;
  922:     return $result,$number_of_columns;
  923: }
  924: 
  925: 
  926: sub details_for_menu {
  927:     my ($helper)=@_;
  928:     my $postdata=$env{'form.postdata'};
  929:     if (!$postdata) { $postdata=$helper->{VARS}{'postdata'}; }
  930:     my $name_of_resource = &Apache::lonnet::gettitle($postdata);
  931:     my $symbolic = &Apache::lonnet::symbread($postdata);
  932:     return if ( $symbolic eq '');
  933: 
  934:     my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symbolic);
  935:     $map=&Apache::lonnet::clutter($map);
  936:     my $name_of_sequence = &Apache::lonnet::gettitle($map);
  937:     if ($name_of_sequence =~ /^\s*$/) {
  938: 	$map =~ m|([^/]+)$|;
  939: 	$name_of_sequence = $1;
  940:     }
  941:     my $name_of_map = &Apache::lonnet::gettitle($env{'request.course.uri'});
  942:     if ($name_of_map =~ /^\s*$/) {
  943: 	$env{'request.course.uri'} =~ m|([^/]+)$|;
  944: 	$name_of_map = $1;
  945:     }
  946:     return ($name_of_resource,$name_of_sequence,$name_of_map);
  947: }
  948: 
  949: sub copyright_line {
  950:     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 } ';
  951: }
  952: my $end_of_student = "\n".'\special{ps:ENDOFSTUDENTSTAMP}'."\n";
  953: 
  954: sub latex_corrections {
  955:     my ($number_of_columns,$result,$selectionmade,$answer_mode) = @_;
  956: #    $result =~ s/\\includegraphics{/\\includegraphics\[width=\\minipagewidth\]{/g;
  957:     my $copyright = &copyright_line();
  958:     if ($selectionmade eq '1' || $answer_mode eq 'only') {
  959: 	$result =~ s/(\\end{document})/\\strut\\vskip 0 mm $copyright $end_of_student $1/;
  960:     } else {
  961: 	$result =~ s/(\\end{document})/\\strut\\vspace\*{-4 mm}\\newline $copyright $end_of_student $1/;
  962:     }
  963:     $result =~ s/\$number_of_columns/$number_of_columns/g;
  964:     $result =~ s/(\\end{longtable}\s*)(\\strut\\newline\\noindent\\makebox\[\\textwidth\/$number_of_columns\]\[b\]{\\hrulefill})/$2$1/g;
  965:     $result =~ s/(\\end{longtable}\s*)\\strut\\newline/$1/g;
  966: #-- LaTeX corrections     
  967:     my $first_comment = index($result,'<!--',0);
  968:     while ($first_comment != -1) {
  969: 	my $end_comment = index($result,'-->',$first_comment);
  970: 	substr($result,$first_comment,$end_comment-$first_comment+3) = '';
  971: 	$first_comment = index($result,'<!--',$first_comment);
  972:     }
  973:     $result =~ s/^\s+$//gm; #remove empty lines
  974:     #removes more than one empty space
  975:     $result =~ s|(\s\s+)|($1=~/[\n\r]/)?"\n":" "|ge;
  976:     $result =~ s/\\\\\s*\\vskip/\\vskip/gm;
  977:     $result =~ s/\\\\\s*\\noindent\s*(\\\\)+/\\\\\\noindent /g;
  978:     $result =~ s/{\\par }\s*\\\\/\\\\/gm;
  979:     $result =~ s/\\\\\s+\[/ \[/g;
  980:     #conversion of html characters to LaTeX equivalents
  981:     if ($result =~ m/&(\w+|#\d+);/) {
  982: 	$result = &character_chart($result);
  983:     }
  984:     $result =~ s/(\\end{tabular})\s*\\vskip 0 mm/$1/g;
  985:     $result =~ s/(\\begin{enumerate})\s*\\noindent/$1/g;
  986:     return $result;
  987: }
  988: 
  989: 
  990: sub index_table {
  991:     my $currentURL = shift;
  992:     my $insex_string='';
  993:     $currentURL=~s/\.([^\/+])$/\.$1\.meta/;
  994:     $insex_string=&Apache::lonnet::metadata($currentURL,'keywords');
  995:     return $insex_string;
  996: }
  997: 
  998: 
  999: sub IndexCreation {
 1000:     my ($texversion,$currentURL)=@_;
 1001:     my @key_words=split(/,/,&index_table($currentURL));
 1002:     my $chunk='';
 1003:     my $st=index $texversion,'\addcontentsline{toc}{subsection}{';
 1004:     if ($st>0) {
 1005: 	for (my $i=0;$i<3;$i++) {$st=(index $texversion,'}',$st+1);}
 1006: 	$chunk=substr($texversion,0,$st+1);
 1007: 	substr($texversion,0,$st+1)=' ';
 1008:     }
 1009:     foreach my $key_word (@key_words) {
 1010: 	if ($key_word=~/\S+/) {
 1011: 	    $texversion=~s/\b($key_word)\b/$1 \\index{$key_word} /i;
 1012: 	}
 1013:     }			
 1014:     if ($st>0) {substr($texversion,0,1)=$chunk;}
 1015:     return $texversion;
 1016: }
 1017: 
 1018: sub print_latex_header {
 1019:     my $mode=shift;
 1020:     my $output='\documentclass[letterpaper,twoside]{article}\raggedbottom';
 1021:     if (($mode eq 'batchmode') || (!$perm{'pav'})) {
 1022: 	$output.='\batchmode';
 1023:     }
 1024:     $output.='\newcommand{\keephidden}[1]{}\renewcommand{\deg}{$^{\circ}$}'."\n".
 1025:    	    '\usepackage{multirow}'."\n".
 1026: 	     '\usepackage{longtable}\usepackage{textcomp}\usepackage{makeidx}'."\n".
 1027: 	     '\usepackage[dvips]{graphicx}\usepackage{epsfig}'."\n".
 1028: 	     '\usepackage{wrapfig}'.
 1029: 	     '\usepackage{picins}\usepackage{calc}'."\n".
 1030: 	     '\newenvironment{choicelist}{\begin{list}{}{\setlength{\rightmargin}{0in}'."\n".
 1031: 	     '\setlength{\leftmargin}{0.13in}\setlength{\topsep}{0.05in}'."\n".
 1032: 	     '\setlength{\itemsep}{0.022in}\setlength{\parsep}{0in}'."\n".
 1033: 	     '\setlength{\belowdisplayskip}{0.04in}\setlength{\abovedisplayskip}{0.05in}'."\n".
 1034: 	     '\setlength{\abovedisplayshortskip}{-0.04in}'."\n".
 1035: 	     '\setlength{\belowdisplayshortskip}{0.04in}}}{\end{list}}'."\n".
 1036: 	     '\renewenvironment{theindex}{\begin{list}{}{{\vskip 1mm \noindent \large'."\n".
 1037: 	     '\textbf{Index}} \newline \setlength{\rightmargin}{0in}'."\n".
 1038: 	     '\setlength{\leftmargin}{0.13in}\setlength{\topsep}{0.01in}'."\n".
 1039: 	     '\setlength{\itemsep}{0.1in}\setlength{\parsep}{-0.02in}'."\n".
 1040: 	     '\setlength{\belowdisplayskip}{0.01in}\setlength{\abovedisplayskip}{0.01in}'."\n".
 1041: 	     '\setlength{\abovedisplayshortskip}{-0.04in}'."\n".
 1042: 	     '\setlength{\belowdisplayshortskip}{0.01in}}}{\end{list}}\begin{document}'."\n";
 1043:     return $output;	     
 1044: }
 1045: 
 1046: sub path_to_problem {
 1047:     my ($urlp,$colwidth)=@_;
 1048:     $urlp=&Apache::lonnet::clutter($urlp);
 1049: 
 1050:     my $newurlp = '';
 1051:     $colwidth=~s/\s*mm\s*$//;
 1052: #characters average about 2 mm in width
 1053:     if (length($urlp)*2 > $colwidth) {
 1054: 	my @elements = split('/',$urlp);
 1055: 	my $curlength=0;
 1056: 	foreach my $element (@elements) {
 1057: 	    if ($element eq '') { next; }
 1058: 	    if ($curlength+(length($element)*2) > $colwidth) {
 1059: 		$newurlp .=  '|\vskip -1 mm \verb|';
 1060: 		$curlength=length($element)*2;
 1061: 	    } else {
 1062: 		$curlength+=length($element)*2;
 1063: 	    }
 1064: 	    $newurlp.='/'.$element;
 1065: 	}
 1066:     } else {
 1067: 	$newurlp=$urlp;
 1068:     }
 1069:     return '{\small\noindent\verb|'.$newurlp.'|\vskip 0 mm}';
 1070: }
 1071: 
 1072: sub recalcto_mm {
 1073:     my $textwidth=shift;
 1074:     my $LaTeXwidth;
 1075:     if ($textwidth=~/(-?\d+\.?\d*)\s*cm/) {
 1076: 	$LaTeXwidth = $1*10;
 1077:     } elsif ($textwidth=~/(-?\d+\.?\d*)\s*mm/) {
 1078: 	$LaTeXwidth = $1;
 1079:     } elsif ($textwidth=~/(-?\d+\.?\d*)\s*in/) {
 1080: 	$LaTeXwidth = $1*25.4;
 1081:     }
 1082:     $LaTeXwidth.=' mm';
 1083:     return $LaTeXwidth;
 1084: }
 1085: 
 1086: sub get_textwidth {
 1087:     my ($helper,$LaTeXwidth)=@_;
 1088:     my $textwidth=$LaTeXwidth;
 1089:     if ($helper->{'VARS'}->{'pagesize.width'}=~/\d+/ &&
 1090: 	$helper->{'VARS'}->{'pagesize.widthunit'}=~/\w+/) {
 1091: 	$textwidth=&recalcto_mm($helper->{'VARS'}->{'pagesize.width'}.' '.
 1092: 				$helper->{'VARS'}->{'pagesize.widthunit'});
 1093:     }
 1094:     return $textwidth;
 1095: }
 1096: 
 1097: 
 1098: sub unsupported {
 1099:     my ($currentURL,$mode,$symb)=@_;
 1100:     if ($mode ne '') {$mode='\\'.$mode}
 1101:     my $result.= &print_latex_header($mode);
 1102:     if ($currentURL=~m|^(/adm/wrapper/)?ext/|) {
 1103: 	$currentURL=~s|^(/adm/wrapper/)?ext/|http://|;
 1104: 	my $title=&Apache::lonnet::gettitle($symb);
 1105: 	$title = &Apache::lonxml::latex_special_symbols($title);
 1106: 	$result.=' \strut \\\\ '.$title.' \strut \\\\ '.$currentURL.' ';
 1107:     } else {
 1108: 	$result.=$currentURL;
 1109:     }
 1110:     $result.= '\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill} \end{document}';
 1111:     return $result;
 1112: }
 1113: 
 1114: 
 1115: #
 1116: # List of recently generated print files
 1117: #
 1118: sub recently_generated {
 1119:     my $r=shift;
 1120:     my $prtspool=$r->dir_config('lonPrtDir');
 1121:     my $zip_result;
 1122:     my $pdf_result;
 1123:     opendir(DIR,$prtspool);
 1124: 
 1125:     my @files = 
 1126: 	grep(/^$env{'user.name'}_$env{'user.domain'}_printout_(\d+)_.*\.(pdf|zip)$/,readdir(DIR));
 1127:     closedir(DIR);
 1128: 
 1129:     @files = sort {
 1130: 	my ($actime) = (stat($prtspool.'/'.$a))[10];
 1131: 	my ($bctime) = (stat($prtspool.'/'.$b))[10];
 1132: 	return $bctime <=> $actime;
 1133:     } (@files);
 1134: 
 1135:     foreach my $filename (@files) {
 1136: 	my ($ext) = ($filename =~ m/(pdf|zip)$/);
 1137: 	my ($cdev,$cino,$cmode,$cnlink,
 1138: 	    $cuid,$cgid,$crdev,$csize,
 1139: 	    $catime,$cmtime,$cctime,
 1140: 	    $cblksize,$cblocks)=stat($prtspool.'/'.$filename);
 1141: 	my $result="<a href='/prtspool/$filename'>".
 1142: 	    &mt('Generated [_1] ([_2] bytes)',
 1143: 		&Apache::lonlocal::locallocaltime($cctime),$csize).
 1144: 		'</a><br />';
 1145: 	if ($ext eq 'pdf') { $pdf_result .= $result; }
 1146: 	if ($ext eq 'zip') { $zip_result .= $result; }
 1147:     }
 1148:     if ($zip_result) {
 1149: 	$r->print('<h4>'.&mt('Recently generated printout zip files')."</h4>\n"
 1150: 		  .$zip_result);
 1151:     }
 1152:     if ($pdf_result) {
 1153: 	$r->print('<h4>'.&mt('Recently generated printouts')."</h4>\n"
 1154: 		  .$pdf_result);
 1155:     }
 1156: }
 1157: 
 1158: #
 1159: #   Retrieve the hash of page breaks.
 1160: #
 1161: #  Inputs:
 1162: #    helper   - reference to helper object.
 1163: #  Outputs
 1164: #    A reference to a page break hash.
 1165: #
 1166: #
 1167: #use Data::Dumper;
 1168: #sub dump_helper_vars {
 1169: #    my ($helper) = @_;
 1170: #    my $helpervars = Dumper($helper->{'VARS'});
 1171: #    &Apache::lonnet::logthis("Dump of helper vars:\n $helpervars");
 1172: #}
 1173: 
 1174: sub get_page_breaks  {
 1175:     my ($helper) = @_;
 1176:     my %page_breaks;
 1177: 
 1178:     foreach my $break (split /\|\|\|/, $helper->{'VARS'}->{'FINISHPAGE'}) {
 1179: 	$page_breaks{$break} = 1;
 1180:     }
 1181:     return %page_breaks;
 1182: }
 1183: 
 1184: #  Output a sequence (recursively if neeed)
 1185: #  from construction space.
 1186: # Parameters:
 1187: #    url     = URL of the sequence to print.
 1188: #    helper  - Reference to the helper hash.
 1189: #    form    - Copy of the format hash.
 1190: #    LaTeXWidth
 1191: # Returns:
 1192: #   Text to add to the printout.
 1193: #   NOTE if the first element of the outermost sequence
 1194: #   is itself a sequence, the outermost caller may need to
 1195: #   prefix the latex with the page headers stuff.
 1196: #
 1197: sub print_construction_sequence {
 1198:     my ($currentURL, $helper, %form, $LaTeXwidth) = @_;
 1199:     my $result;
 1200:     my $rndseed=time;
 1201:     if ($helper->{'VARS'}->{'curseed'}) {
 1202: 	$rndseed=$helper->{'VARS'}->{'curseed'};
 1203:     }
 1204:     my $errtext=&LONCAPA::map::mapread($currentURL);
 1205:     # 
 1206:     #  These make this all support recursing for subsequences.
 1207:     #
 1208:     my @order    = @LONCAPA::map::order;
 1209:     my @resources = @LONCAPA::map::resources; 
 1210:     for (my $member=0;$member<=$#order;$member++) {
 1211: 	$resources[$order[$member]]=~/^([^:]*):([^:]*):/;
 1212: 	my $urlp=$2;
 1213: 	if ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm)$/) {
 1214: 	    my $texversion='';
 1215: 	    if ($helper->{'VARS'}->{'ANSWER_TYPE'} ne 'only') {
 1216: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1217: 		$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 1218: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1219: 		$form{'rndseed'}=$rndseed;
 1220: 		$resources_printed .=$urlp.':';
 1221: 		$texversion=&Apache::lonnet::ssi($urlp,%form);
 1222: 	    }
 1223: 	    if((($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 1224: 		($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) && 
 1225: 	       ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library|page)$/)) {
 1226: 		#  Don't permanently modify %$form...
 1227: 		my %answerform = %form;
 1228: 		$answerform{'grade_target'}='answer';
 1229: 		$answerform{'answer_output_mode'}='tex';
 1230: 		$answerform{'rndseed'}=$rndseed;
 1231: 		$answerform{'problem_split'}=$parmhash{'problem_stream_switch'};
 1232: 		if ($urlp=~/\/res\//) {$env{'request.state'}='published';}
 1233: 		$resources_printed .= $urlp.':';
 1234: 		my $answer=&Apache::lonnet::ssi($urlp,%answerform);
 1235: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 1236: 		    $texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 1237: 		} else {
 1238: 		    # If necessary, encapsulate answer in minipage:
 1239: 		    
 1240: 		    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1241: 		    my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 1242: 		    $title = &Apache::lonxml::latex_special_symbols($title);
 1243: 		    my $body ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 1244: 		    $body.=&path_to_problem($urlp,$LaTeXwidth);
 1245: 		    $body.='\vskip 1 mm '.$answer.'\end{document}';
 1246: 		    $body = &encapsulate_minipage($body);
 1247: 		    $texversion.=$body;
 1248: 		}
 1249: 	    }
 1250: 	    $texversion = &latex_header_footer_remove($texversion);
 1251: 
 1252: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 1253: 		$texversion=&IndexCreation($texversion,$urlp);
 1254: 	    }
 1255: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 1256: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
 1257: 	    }
 1258: 	    $result.=$texversion;
 1259: 
 1260: 	} elsif ($urlp=~/\.(sequence|page)$/) {
 1261: 	    
 1262: 	    # header:
 1263: 
 1264: 	    $result.='\strut\newline\noindent Sequence/page '.$urlp.'\strut\newline\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\newline\noindent ';
 1265: 
 1266: 	    # IF sequence, recurse:
 1267: 	    
 1268: 	    if ($urlp =~ /\.sequence$/) {
 1269: 		my $sequence_url = $urlp;
 1270: 		my $domain       = $env{'user.domain'};	# Constr. space only on local
 1271: 		my $user         = $env{'user.name'};
 1272: 
 1273: 		$sequence_url    =~ s/^\/res\/$domain/\/home/;
 1274: 		$sequence_url    =~ s/^(\/home\/$user)/$1\/public_html/;
 1275: #		$sequence_url    =~ s|\/~([^\/]+)\/|\/home\/$1\/public_html\/|;
 1276: 		$result .= &print_construction_sequence($sequence_url, 
 1277: 							$helper, %form, 
 1278: 							$LaTeXwidth);
 1279: 	    }
 1280: 	}  
 1281:     }
 1282:     if ($helper->{VARS}->{'construction'} eq '1') {$result=~s/(\\begin{document})/$1 \\fbox\{RANDOM SEED IS $rndseed\} /;}
 1283:     return $result;
 1284: }
 1285: 
 1286: sub output_data {
 1287:     my ($r,$helper,$rparmhash) = @_;
 1288:     my %parmhash = %$rparmhash;
 1289:     $resources_printed = '';
 1290:     my $do_postprocessing = 1;
 1291:     my $js = <<ENDPART;
 1292: <script type="text/javascript">
 1293:     var editbrowser;
 1294:     function openbrowser(formname,elementname,only,omit) {
 1295:         var url = '/res/?';
 1296:         if (editbrowser == null) {
 1297:             url += 'launch=1&';
 1298:         }
 1299:         url += 'catalogmode=interactive&';
 1300:         url += 'mode=parmset&';
 1301:         url += 'form=' + formname + '&';
 1302:         if (only != null) {
 1303:             url += 'only=' + only + '&';
 1304:         } 
 1305:         if (omit != null) {
 1306:             url += 'omit=' + omit + '&';
 1307:         }
 1308:         url += 'element=' + elementname + '';
 1309:         var title = 'Browser';
 1310:         var options = 'scrollbars=1,resizable=1,menubar=0';
 1311:         options += ',width=700,height=600';
 1312:         editbrowser = open(url,title,options,'1');
 1313:         editbrowser.focus();
 1314:     }
 1315: </script>
 1316: ENDPART
 1317: 
 1318:     my $start_page  = &Apache::loncommon::start_page('Preparing Printout',$js);
 1319:     my $msg = &mt('Please stand by while processing your print request, this may take some time ...');
 1320: 
 1321:     $r->print($start_page."\n<p>\n$msg\n</p>\n");
 1322: 
 1323:     # fetch the pagebreaks and store them in the course environment
 1324:     # The page breaks will be pulled into the hash %page_breaks which is
 1325:     # indexed by symb and contains 1's for each break.
 1326: 
 1327:     $env{'form.pagebreaks'}  = $helper->{'VARS'}->{'FINISHPAGE'};
 1328:     $env{'form.lastprinttype'} = $helper->{'VARS'}->{'PRINT_TYPE'}; 
 1329:     &Apache::loncommon::store_course_settings('print',
 1330: 					      {'pagebreaks'    => 'scalar',
 1331: 					       'lastprinttype' => 'scalar'});
 1332: 
 1333:     my %page_breaks  = &get_page_breaks($helper);
 1334: 
 1335:     my $format_from_helper = $helper->{'VARS'}->{'FORMAT'};
 1336:     my ($result,$selectionmade) = ('','');
 1337:     my $number_of_columns = 1; #used only for pages to determine the width of the cell
 1338:     my @temporary_array=split /\|/,$format_from_helper;
 1339:     my ($laystyle,$numberofcolumns,$papersize)=@temporary_array;
 1340:     if ($laystyle eq 'L') {
 1341: 	$laystyle='album';
 1342:     } else {
 1343: 	$laystyle='book';
 1344:     }
 1345:     my ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$laystyle,$numberofcolumns);
 1346:     my $assignment =  $env{'form.assignment'};
 1347:     my $LaTeXwidth=&recalcto_mm($textwidth); 
 1348:     my @print_array=();
 1349:     my @student_names=();
 1350: 
 1351:     #  Common settings for the %form has:
 1352:     # In some cases these settings get overriddent by specific cases, but the
 1353:     # settings are common enough to make it worthwhile factoring them out
 1354:     # here.
 1355:     #
 1356:     my %form;
 1357:     $form{'grade_target'} = 'tex';
 1358:     $form{'textwidth'}    = &get_textwidth($helper, $LaTeXwidth);
 1359: 
 1360:     # If form.showallfoils is set, then request all foils be shown:
 1361:     # privilege will be enforced both by not allowing the 
 1362:     # check box selecting this option to be presnt unless it's ok,
 1363:     # and by lonresponse's priv. check.
 1364:     # The if is here because lonresponse.pm only cares that
 1365:     # showallfoils is defined, not what the value is.
 1366: 
 1367:     if ($helper->{'VARS'}->{'showallfoils'} eq "1") { 
 1368: 	$form{'showallfoils'} = $helper->{'VARS'}->{'showallfoils'};
 1369:     }
 1370: 
 1371:     if ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'current_document') {
 1372:       #-- single document - problem, page, html, xml, ...
 1373: 	my ($currentURL,$cleanURL);
 1374: 
 1375: 	if ($helper->{'VARS'}->{'construction'} ne '1') {
 1376:             #prints published resource
 1377: 	    $currentURL=$helper->{'VARS'}->{'postdata'};
 1378: 	    $cleanURL=&Apache::lonenc::check_decrypt($currentURL);
 1379: 	} else {
 1380:             #prints resource from the construction space
 1381: 	    $currentURL='/'.$helper->{'VARS'}->{'filename'};
 1382: 	    if ($currentURL=~/([^?]+)/) {$currentURL=$1;}
 1383: 	    $cleanURL=$currentURL;
 1384: 	}
 1385: 	$selectionmade = 1;
 1386: 	if ($cleanURL!~m|^/adm/|
 1387: 	    && $cleanURL=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 1388: 	    my $rndseed=time;
 1389: 	    my $texversion='';
 1390: 	    if ($helper->{'VARS'}->{'ANSWER_TYPE'} ne 'only') {
 1391: 		my %moreenv;
 1392: 		$moreenv{'request.filename'}=$cleanURL;
 1393: 		if ($helper->{'VARS'}->{'style_file'}=~/\w/) {
 1394: 		    $moreenv{'construct.style'}=$helper->{'VARS'}->{'style_file'};
 1395: 		    my $dom = $env{'user.domain'};
 1396: 		    my $user = $env{'user.name'};
 1397: 		    my $put_result = &Apache::lonnet::put('environment',{'construct.style'=>$helper->{'VARS'}->{'style_file'}},$dom,$user);
 1398: 		}
 1399:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {$form{'problemtype'}='exam';}
 1400: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1401: 		$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 1402: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1403: 		$form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 1404: 		if ($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') {$form{'problem_split'}='yes';}
 1405: 		if ($helper->{'VARS'}->{'curseed'}) {
 1406: 		    $rndseed=$helper->{'VARS'}->{'curseed'};
 1407: 		}
 1408: 		$form{'rndseed'}=$rndseed;
 1409: 		&Apache::lonnet::appenv(%moreenv);
 1410: 
 1411: 		&Apache::lonxml::clear_problem_counter();
 1412: 
 1413: 		$resources_printed .= $currentURL.':';
 1414: 		$texversion.=&Apache::lonnet::ssi($currentURL,%form);
 1415: 
 1416: 		&Apache::lonxml::clear_problem_counter();
 1417: 
 1418: 		&Apache::lonnet::delenv('request.filename');
 1419: 	    }
 1420: 	    # current document with answers.. no need to encap in minipage
 1421: 	    #  since there's only one answer.
 1422: 
 1423: 	    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 1424: 	       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 1425: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1426: 		$form{'grade_target'}='answer';
 1427: 		$form{'answer_output_mode'}='tex';
 1428: 		$form{'rndseed'}=$rndseed;
 1429:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {
 1430: 		    $form{'problemtype'}='exam';
 1431: 		}
 1432: 		$resources_printed .= $currentURL.':';
 1433: 		my $answer=&Apache::lonnet::ssi($currentURL,%form);
 1434: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 1435: 		    $texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 1436: 		} else {
 1437: 		    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1438: 		    if ($helper->{'VARS'}->{'construction'} ne '1') {
 1439: 			my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 1440: 			$title = &Apache::lonxml::latex_special_symbols($title);
 1441: 			$texversion.='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 1442: 			$texversion.=&path_to_problem($cleanURL,$LaTeXwidth);
 1443: 		    } else {
 1444: 			$texversion.='\vskip 0 mm \noindent\textbf{Prints from construction space - there is no title.}\vskip 0 mm ';
 1445: 			my $URLpath=$cleanURL;
 1446: 			$URLpath=~s/~([^\/]+)/public_html\/$1\/$1/;
 1447: 			$texversion.=&path_to_problem ($URLpath,$LaTeXwidth);
 1448: 		    }
 1449: 		    $texversion.='\vskip 1 mm '.$answer.'\end{document}';
 1450: 		}
 1451: 	    }
 1452: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 1453: 		$texversion=&IndexCreation($texversion,$currentURL);
 1454: 	    }
 1455: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 1456: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$currentURL| \\strut\\\\\\strut /;
 1457: 
 1458: 	    }
 1459: 	    $result .= $texversion;
 1460: 	    if ($currentURL=~m/\.page\s*$/) {
 1461: 		($result,$number_of_columns) = &page_cleanup($result);
 1462: 	    }
 1463:         } elsif ($cleanURL!~m|^/adm/|
 1464: 		 && $currentURL=~/\.sequence$/ && $helper->{'VARS'}->{'construction'} eq '1') {
 1465:             #printing content of sequence from the construction space	
 1466: 	    $currentURL=~s|\/~([^\/]+)\/|\/home\/$1\/public_html\/|;
 1467: 	    $result .= &print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1468: 	    $result .= &print_construction_sequence($currentURL, $helper, %form,
 1469: 						    $LaTeXwidth);
 1470: 	    $result .= '\end{document}';  
 1471: 	    if (!($result =~ /\\begin\{document\}/)) {
 1472: 		$result = &print_latex_header() . $result;
 1473: 	    }
 1474: 	    # End construction space sequence.
 1475: 	} elsif ($cleanURL=~/\/(smppg|syllabus|aboutme|bulletinboard)$/) { 
 1476: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1477: 		if ($currentURL=~/\/syllabus$/) {$currentURL=~s/\/res//;}
 1478: 		$resources_printed .= $currentURL.':';
 1479: 		my $texversion=&Apache::lonnet::ssi($currentURL,%form);
 1480: 		$result .= $texversion;
 1481: 	} elsif ($cleanURL =~/.tex$/) {
 1482: 	    # For this sort of print of a single LaTeX file,
 1483: 	    # We can just print the LaTeX file as it is uninterpreted in any way:
 1484: 	    #
 1485: 
 1486: 	    $result = &fetch_raw_resource($currentURL);
 1487: 	    $do_postprocessing = 0; # Don't massage the result.
 1488: 
 1489: 	} else {
 1490: 	    $result.=&unsupported($currentURL,$helper->{'VARS'}->{'LATEX_TYPE'},
 1491: 				  $helper->{'VARS'}->{'symb'});
 1492: 	}
 1493:     } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems')       or
 1494:              ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_pages') or
 1495:              ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems')       or
 1496: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_resources')      or # BUGBUG
 1497: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'select_sequences')) { 
 1498:         #-- produce an output string
 1499: 	if ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems') {
 1500: 	    $selectionmade = 2;
 1501: 	} elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_pages') {
 1502: 	    $selectionmade = 3;
 1503: 	} elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems') {
 1504: 	    $selectionmade = 4;
 1505: 	} elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_resources') {  #BUGBUG
 1506: 	    $selectionmade = 4;
 1507: 	} elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'select_sequences') {
 1508: 	    $selectionmade = 7;
 1509: 	}
 1510: 	$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1511: 	$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 1512: 	$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1513: 	$form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 1514: 	if ($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') {$form{'problem_split'}='yes';}
 1515: 	my $flag_latex_header_remove = 'NO';
 1516: 	my $flag_page_in_sequence = 'NO';
 1517: 	my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 1518: 	my $prevassignment='';
 1519: 
 1520: 	&Apache::lonxml::clear_problem_counter();
 1521: 
 1522: 	my $pbreakresources = keys %page_breaks;
 1523: 	for (my $i=0;$i<=$#master_seq;$i++) {
 1524: 
 1525: 	    # Note due to document structure, not allowed to put \newpage
 1526: 	    # prior to the first resource
 1527: 
 1528: 	    if (defined $page_breaks{$master_seq[$i]}) {
 1529: 		if($i != 0) {
 1530: 		    $result.="\\newpage\n";
 1531: 		}
 1532: 	    }
 1533: 	    my ($sequence,undef,$urlp)=&Apache::lonnet::decode_symb($master_seq[$i]);
 1534: 	    $urlp=&Apache::lonnet::clutter($urlp);
 1535: 	    $form{'symb'}=$master_seq[$i];
 1536: 
 1537: 	    my $assignment=&Apache::lonxml::latex_special_symbols(&Apache::lonnet::gettitle($sequence),'header'); #title of the assignment which contains this problem
 1538: 	    if ($selectionmade==7) {$helper->{VARS}->{'assignment'}=$assignment;}
 1539: 	    if ($i==0) {$prevassignment=$assignment;}
 1540: 	    my $texversion='';
 1541: 	    if ($urlp!~m|^/adm/|
 1542: 		&& $urlp=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 1543: 		$resources_printed .= $urlp.':';
 1544: 
 1545: 		&Apache::lonxml::remember_problem_counter();
 1546: 		$texversion.=&Apache::lonnet::ssi($urlp,%form);
 1547: 		if ($urlp=~/\.page$/) {
 1548: 		    ($texversion,my $number_of_columns_page) = &page_cleanup($texversion);
 1549: 		    if ($number_of_columns_page > $number_of_columns) {$number_of_columns=$number_of_columns_page;} 
 1550: 		    $texversion =~ s/\\end{document}\d*/\\end{document}/;
 1551: 		    $flag_page_in_sequence = 'YES';
 1552: 		} 
 1553: 
 1554: 		if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 1555: 		   ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 1556: 		    #  Don't permanently pervert the %form hash
 1557: 		    my %answerform = %form;
 1558: 		    $answerform{'grade_target'}='answer';
 1559: 		    $answerform{'answer_output_mode'}='tex';
 1560: 		    $resources_printed .= $urlp.':';
 1561: 
 1562: 		    &Apache::lonxml::restore_problem_counter();
 1563: 		    my $answer=&Apache::lonnet::ssi($urlp,%answerform);
 1564: 
 1565: 		    if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 1566: 			$texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 1567: 		    } else {
 1568: 			if ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library)$/) {
 1569: 			    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1570: 			    my $title = &Apache::lonnet::gettitle($master_seq[$i]);
 1571: 			    $title = &Apache::lonxml::latex_special_symbols($title);
 1572: 			    my $body ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 1573: 			    $body   .= &path_to_problem ($urlp,$LaTeXwidth);
 1574: 			    $body   .='\vskip 1 mm '.$answer;
 1575: 			    $body    = &encapsulate_minipage($body);
 1576: 			    $texversion .= $body;
 1577: 			} else {
 1578: 			    $texversion='';
 1579: 			}
 1580: 		    }
 1581: 		}
 1582: 		if ($flag_latex_header_remove ne 'NO') {
 1583: 		    $texversion = &latex_header_footer_remove($texversion);
 1584: 		} else {
 1585: 		    $texversion =~ s/\\end{document}//;
 1586: 		}
 1587: 		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 1588: 		    $texversion=&IndexCreation($texversion,$urlp);
 1589: 		}
 1590: 		if (($selectionmade == 4) and ($assignment ne $prevassignment)) {
 1591: 		    my $name = &get_name();
 1592: 		    my $courseidinfo = &get_course();
 1593: 		    if (defined($courseidinfo)) { $courseidinfo=' - '.$courseidinfo }
 1594: 		    $prevassignment=$assignment;
 1595: 		    my $header_text = $parmhash{'print_header_format'};
 1596: 		    $header_text    = &format_page_header($textwidth, $header_text,
 1597: 							  $assignment, 
 1598: 							  $courseidinfo, 
 1599: 							  $name);
 1600: 		    if ($numberofcolumns eq '1') {
 1601: 			$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\lhead{'.$header_text.'}} \vskip 5 mm ';
 1602: 		    } else {
 1603: 			$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\fancyhead[LO]{'.$header_text.'}} \vskip 5 mm ';
 1604: 		    }			
 1605: 		}
 1606: 		$result .= $texversion;
 1607: 		$flag_latex_header_remove = 'YES';   
 1608: 	    } elsif ($urlp=~/\/(smppg|syllabus|aboutme|bulletinboard)$/) { 
 1609: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1610: 		if ($urlp=~/\/syllabus$/) {$urlp=~s/\/res//;}
 1611: 		$resources_printed .= $urlp.':';
 1612: 		my $texversion=&Apache::lonnet::ssi($urlp,%form);
 1613: 		if ($flag_latex_header_remove ne 'NO') {
 1614: 		    $texversion = &latex_header_footer_remove($texversion);
 1615: 		} else {
 1616: 		    $texversion =~ s/\\end{document}/\\vskip 0\.5mm\\noindent\\makebox\[\\textwidth\/\$number_of_columns\]\[b\]\{\\hrulefill\}/;
 1617: 		}
 1618: 		$result .= $texversion;
 1619: 		$flag_latex_header_remove = 'YES'; 
 1620: 	    } else {
 1621: 		$texversion=&unsupported($urlp,$helper->{'VARS'}->{'LATEX_TYPE'},
 1622: 					 $master_seq[$i]);
 1623: 		if ($flag_latex_header_remove ne 'NO') {
 1624: 		    $texversion = &latex_header_footer_remove($texversion);
 1625: 		} else {
 1626: 		    $texversion =~ s/\\end{document}//;
 1627: 		}
 1628: 		$result .= $texversion;
 1629: 		$flag_latex_header_remove = 'YES';   
 1630: 	    }	    
 1631: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 1632: 	}
 1633: 	&Apache::lonxml::clear_problem_counter();
 1634: 	if ($flag_page_in_sequence eq 'YES') {
 1635: 	    $result =~ s/\\usepackage{calc}/\\usepackage{calc}\\usepackage{longtable}/;
 1636: 	}	
 1637: 	$result .= '\end{document}';
 1638:      } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_students') ||
 1639: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_students')){
 1640: 
 1641: 
 1642:      #-- prints assignments for whole class or for selected students  
 1643: 	 my $type;
 1644: 	 if ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_students') {
 1645: 	     $selectionmade=5;
 1646: 	     $type='problems';
 1647: 	 } elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_students') {
 1648: 	     $selectionmade=8;
 1649: 	     $type='resources';
 1650: 	 }
 1651: 	 my @students=split /\|\|\|/, $helper->{'VARS'}->{'STUDENTS'};
 1652: 	 #   The normal sort order is by section then by students within the
 1653: 	 #   section. If the helper var student_sort is 1, then the user has elected
 1654: 	 #   to override this and output the students by name.
 1655: 	 #    Each element of the students array is of the form:
 1656: 	 #       username:domain:section:last, first:status
 1657: 	 #    
 1658: 	 #  Note that student sort is not compatible with printing 
 1659: 	 #  1 section per pdf...so that setting overrides.
 1660: 	 #   
 1661: 	 if (($helper->{'VARS'}->{'student_sort'}    eq 1)  && 
 1662: 	     ($helper->{'VARS'}->{'SPLIT_PDFS'} ne "sections")) {
 1663: 	     @students = sort compare_names  @students;
 1664: 	 }
 1665: 	 &adjust_number_to_print($helper);
 1666: 
 1667:          if ($helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq '0' ||
 1668: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq 'all' ) {
 1669: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'}=$#students+1;
 1670: 	 }
 1671: 	 # If we are splitting on section boundaries, we need 
 1672: 	 # to remember that in split_on_sections and 
 1673: 	 # print all of the students in the list.
 1674: 	 #
 1675: 	 my $split_on_sections = 0;
 1676: 	 if ($helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq 'section') {
 1677: 	     $split_on_sections = 1;
 1678: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'} = $#students+1;
 1679: 	 }
 1680: 	 my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 1681: 
 1682: 	 #loop over students
 1683: 	 my $flag_latex_header_remove = 'NO'; 
 1684: 	 my %moreenv;
 1685:          $moreenv{'instructor_comments'}='hide';
 1686: 	 $moreenv{'textwidth'}=&get_textwidth($helper,$LaTeXwidth);
 1687: 	 $moreenv{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 1688: 	 $moreenv{'problem_split'}    = $parmhash{'problem_stream_switch'};
 1689: 	 $moreenv{'suppress_tries'}   = $parmhash{'suppress_tries'};
 1690: 	 if ($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') {$moreenv{'problem_split'}='yes';}
 1691: 	 my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Print Status','Class Print Status',$#students+1,'inline','75');
 1692: 	 my $student_counter=-1;
 1693: 	 my $i = 0;
 1694: 	 my $last_section = (split(/:/,$students[0]))[2];
 1695: 	 foreach my $person (@students) {
 1696: 
 1697:              my $duefile="/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.due";
 1698: 	     if (-e $duefile) {
 1699: 		 my $temp_file = Apache::File->new('>>'.$duefile);
 1700: 		 print $temp_file "1969\n";
 1701: 	     }
 1702: 	     $student_counter++;
 1703: 	     if ($split_on_sections) {
 1704: 		 my $this_section = (split(/:/,$person))[2];
 1705: 		 if ($this_section ne $last_section) {
 1706: 		     $i++;
 1707: 		     $last_section = $this_section;
 1708: 		 }
 1709: 	     } else {
 1710: 		 $i=int($student_counter/$helper->{'VARS'}{'NUMBER_TO_PRINT'});
 1711: 	     }
 1712: 	     my ($output,$fullname, $printed)=&print_resources($r,$helper,
 1713: 						     $person,$type,
 1714: 						     \%moreenv,\@master_seq,
 1715: 						     $flag_latex_header_remove,
 1716: 						     $LaTeXwidth);
 1717: 	     $resources_printed .= ":";
 1718: 	     $print_array[$i].=$output;
 1719: 	     $student_names[$i].=$person.':'.$fullname.'_END_';
 1720: 	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,&mt('last student').' '.$fullname);
 1721: 	     $flag_latex_header_remove = 'YES';
 1722: 	     if (&Apache::loncommon::connection_aborted($r)) { last; }
 1723: 	 }
 1724: 	 &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1725: 	 $result .= $print_array[0].'  \end{document}';
 1726:      } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_anon')     ||
 1727: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_anon')  ) { 
 1728: 	 my $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 1729: 	 my $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 1730: 	 my $num_todo=$helper->{'VARS'}->{'NUMBER_TO_PRINT_TOTAL'};
 1731: 	 my $code_name=$helper->{'VARS'}->{'ANON_CODE_STORAGE_NAME'};
 1732: 	 my $old_name=$helper->{'VARS'}->{'REUSE_OLD_CODES'};
 1733: 	 my $single_code = $helper->{'VARS'}->{'SINGLE_CODE'};
 1734: 	 my $selected_code = $helper->{'VARS'}->{'CODE_SELECTED_FROM_LIST'};
 1735: 
 1736: 	 my $code_option=$helper->{'VARS'}->{'CODE_OPTION'};
 1737: 	 open(FH,$Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 1738: 	 my ($code_type,$code_length)=('letter',6);
 1739: 	 foreach my $line (<FH>) {
 1740: 	     my ($name,$type,$length) = (split(/:/,$line))[0,2,4];
 1741: 	     if ($name eq $code_option) {
 1742: 		 $code_length=$length;
 1743: 		 if ($type eq 'number') { $code_type = 'number'; }
 1744: 	     }
 1745: 	 }
 1746: 	 my %moreenv = ('textwidth' => &get_textwidth($helper,$LaTeXwidth));
 1747: 	 $moreenv{'problem_split'}    = $parmhash{'problem_stream_switch'};
 1748:          $moreenv{'instructor_comments'}='hide';
 1749: 	 my $seed=time+($$<<16)+($$);
 1750: 	 my @allcodes;
 1751: 	 if ($old_name) {
 1752: 	     my %result=&Apache::lonnet::get('CODEs',
 1753: 					     [$old_name,"type\0$old_name"],
 1754: 					     $cdom,$cnum);
 1755: 	     $code_type=$result{"type\0$old_name"};
 1756: 	     @allcodes=split(',',$result{$old_name});
 1757: 	     $num_todo=scalar(@allcodes);
 1758: 	 } elsif ($selected_code) { # Selection value is always numeric.
 1759: 	     $num_todo = 1;
 1760: 	     @allcodes = ($selected_code);
 1761: 	 } elsif ($single_code) {
 1762: 
 1763: 	     $num_todo    = 1;	# Unconditionally one code to do.
 1764: 	     # If an alpha code have to convert to numbers so it can be
 1765: 	     # converted back to letters again :-)
 1766: 	     #
 1767: 	     if ($code_type ne 'number') {
 1768: 		 $single_code = &letters_to_num($single_code);
 1769: 	     }
 1770: 	     @allcodes = ($single_code);
 1771: 	 } else {
 1772: 	     my %allcodes;
 1773: 	     srand($seed);
 1774: 	     for (my $i=0;$i<$num_todo;$i++) {
 1775: 		 $moreenv{'CODE'}=&get_CODE(\%allcodes,$i,$seed,$code_length,
 1776: 					    $code_type);
 1777: 	     }
 1778: 	     if ($code_name) {
 1779: 		 &Apache::lonnet::put('CODEs',
 1780: 				      {
 1781: 					$code_name =>join(',',keys(%allcodes)),
 1782: 					"type\0$code_name" => $code_type
 1783: 				      },
 1784: 				      $cdom,$cnum);
 1785: 	     }
 1786: 	     @allcodes=keys(%allcodes);
 1787: 	 }
 1788: 	 my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 1789: 	 my ($type) = split(/_/,$helper->{'VARS'}->{'PRINT_TYPE'});
 1790: 	 &adjust_number_to_print($helper);
 1791: 	 my $number_per_page=$helper->{'VARS'}->{'NUMBER_TO_PRINT'};
 1792: 	 if ($number_per_page eq '0' || $number_per_page eq 'all') {
 1793: 	     $number_per_page=$num_todo;
 1794: 	 }
 1795: 	 my $flag_latex_header_remove = 'NO'; 
 1796: 	 my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Print Status','Class Print Status',$num_todo,'inline','75');
 1797: 	 my $count=0;
 1798: 	 foreach my $code (sort(@allcodes)) {
 1799: 	     my $file_num=int($count/$number_per_page);
 1800: 	     if ($code_type eq 'number') { 
 1801: 		 $moreenv{'CODE'}=$code;
 1802: 	     } else {
 1803: 		 $moreenv{'CODE'}=&num_to_letters($code);
 1804: 	     }
 1805: 	     my ($output,$fullname, $printed)=
 1806: 		 &print_resources($r,$helper,'anonymous',$type,\%moreenv,
 1807: 				  \@master_seq,$flag_latex_header_remove,
 1808: 				  $LaTeXwidth);
 1809: 	     $resources_printed .= ":";
 1810: 	     $print_array[$file_num].=$output;
 1811: 	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 1812: 				       &mt('last assignment').' '.$fullname);
 1813: 	     $flag_latex_header_remove = 'YES';
 1814: 	     $count++;
 1815: 	     if (&Apache::loncommon::connection_aborted($r)) { last; }
 1816: 	 }
 1817: 	 &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1818: 	 $result .= $print_array[0].'  \end{document}';
 1819:      } elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_from_directory') {      
 1820:     #prints selected problems from the subdirectory 
 1821: 	$selectionmade = 6;
 1822:         my @list_of_files=split /\|\|\|/, $helper->{'VARS'}->{'FILES'};
 1823: 	@list_of_files=sort @list_of_files;
 1824: 	my $flag_latex_header_remove = 'NO'; 
 1825: 	my $rndseed=time;
 1826: 	if ($helper->{'VARS'}->{'curseed'}) {
 1827: 	    $rndseed=$helper->{'VARS'}->{'curseed'};
 1828: 	}
 1829: 	for (my $i=0;$i<=$#list_of_files;$i++) {
 1830: 	    my $urlp = $list_of_files[$i];
 1831: 	    $urlp=~s|//|/|;
 1832: 	    if ($urlp=~/\//) {
 1833: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1834: 		$form{'rndseed'}=$rndseed;
 1835: 		if ($urlp =~ m|/home/([^/]+)/public_html|) {
 1836: 		    $urlp =~ s|/home/([^/]*)/public_html|/~$1|;
 1837: 		} else {
 1838: 		    $urlp =~ s|^$Apache::lonnet::perlvar{'lonDocRoot'}||;
 1839: 		}
 1840: 		$resources_printed .= $urlp.':';
 1841: 		my $texversion=&Apache::lonnet::ssi($urlp,%form);
 1842: 		if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 1843: 		   ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 1844: 		    #  Don't permanently pervert %form:
 1845: 		    my %answerform = %form;
 1846: 		    $answerform{'grade_target'}='answer';
 1847: 		    $answerform{'answer_output_mode'}='tex';
 1848: 		    $answerform{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1849: 		    $answerform{'rndseed'}=$rndseed;
 1850: 		    $resources_printed .= $urlp.':';
 1851: 		    my $answer=&Apache::lonnet::ssi($urlp,%answerform);
 1852: 		    if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 1853: 			$texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 1854: 		    } else {
 1855: 			$texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1856: 			if ($helper->{'VARS'}->{'construction'} ne '1') {
 1857: 			    $texversion.='\vskip 0 mm \noindent ';
 1858: 			    $texversion.=&path_to_problem ($urlp,$LaTeXwidth);
 1859: 			} else {
 1860: 			    $texversion.='\vskip 0 mm \noindent\textbf{Prints from construction space - there is no title.}\vskip 0 mm ';
 1861: 			    my $URLpath=$urlp;
 1862: 			    $URLpath=~s/~([^\/]+)/public_html\/$1\/$1/;
 1863: 			    $texversion.=&path_to_problem ($URLpath,$LaTeXwidth);
 1864: 			}
 1865: 			$texversion.='\vskip 1 mm '.$answer.'\end{document}';
 1866: 		    }
 1867: 		}
 1868:                 #this chunck is responsible for printing the path to problem
 1869: 		my $newurlp=$urlp;
 1870: 		if ($newurlp=~/~/) {$newurlp=~s|\/~([^\/]+)\/|\/home\/$1\/public_html\/|;}
 1871: 		$newurlp=&path_to_problem($newurlp,$LaTeXwidth);
 1872: 		$texversion =~ s/(\\begin{minipage}{\\textwidth})/$1 $newurlp/;
 1873: 		if ($flag_latex_header_remove ne 'NO') {
 1874: 		    $texversion = &latex_header_footer_remove($texversion);
 1875: 		} else {
 1876: 		    $texversion =~ s/\\end{document}//;
 1877: 		}
 1878: 		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 1879: 		    $texversion=&IndexCreation($texversion,$urlp);
 1880: 		}
 1881: 		if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 1882: 		    $texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
 1883: 		    
 1884: 		}
 1885: 		$result .= $texversion;
 1886: 	    }
 1887: 	    $flag_latex_header_remove = 'YES';  
 1888: 	}
 1889: 	if ($helper->{VARS}->{'construction'} eq '1') {$result=~s/(\\typeout)/ RANDOM SEED IS $rndseed $1/;}
 1890: 	$result .= '\end{document}';      	
 1891:     }
 1892: #-------------------------------------------------------- corrections for the different page formats
 1893: 
 1894:     # Only post process if that has not been turned off e.g. by a raw latex resource.
 1895: 
 1896:     if ($do_postprocessing) {
 1897: 	$result = &page_format_transformation($papersize,$laystyle,$numberofcolumns,$helper->{'VARS'}->{'PRINT_TYPE'},$result,$helper->{VARS}->{'assignment'},$helper->{'VARS'}->{'TABLE_CONTENTS'},$helper->{'VARS'}->{'TABLE_INDEX'},$selectionmade);
 1898: 	$result = &latex_corrections($number_of_columns,$result,$selectionmade,
 1899: 				     $helper->{'VARS'}->{'ANSWER_TYPE'});
 1900: 	#if ($numberofcolumns == 1) {
 1901: 	$result =~ s/\\textwidth\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\textwidth= $helper->{'VARS'}->{'pagesize.width'} $helper->{'VARS'}->{'pagesize.widthunit'} /;
 1902: 	$result =~ s/\\textheight\s*=?\s*-?\d*\.?\d*\s*(cm|mm|in)/\\textheight $helper->{'VARS'}->{'pagesize.height'} $helper->{'VARS'}->{'pagesize.heightunit'} /;
 1903: 	$result =~ s/\\evensidemargin\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\evensidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
 1904: 	$result =~ s/\\oddsidemargin\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\oddsidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
 1905: 	#}
 1906:     }
 1907: 
 1908: #-- writing .tex file in prtspool 
 1909:     my $temp_file;
 1910:     my $identifier = &Apache::loncommon::get_cgi_id();
 1911:     my $filename = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout_$identifier.tex";
 1912:     if (!($#print_array>0)) { 
 1913: 	unless ($temp_file = Apache::File->new('>'.$filename)) {
 1914: 	    $r->log_error("Couldn't open $filename for output $!");
 1915: 	    return SERVER_ERROR; 
 1916: 	}
 1917: 	print $temp_file $result;
 1918: 	my $begin=index($result,'\begin{document}',0);
 1919: 	my $inc=substr($result,0,$begin+16);
 1920:     } else {
 1921: 	my $begin=index($result,'\begin{document}',0);
 1922: 	my $inc=substr($result,0,$begin+16);
 1923:         for (my $i=0;$i<=$#print_array;$i++) {
 1924: 	    if ($i==0) {
 1925: 		$print_array[$i]=$result;
 1926: 	    } else {
 1927: 		$print_array[$i].='\end{document}';
 1928: 		$print_array[$i] = 
 1929: 		    &latex_corrections($number_of_columns,$print_array[$i],
 1930: 				       $selectionmade, 
 1931: 				       $helper->{'VARS'}->{'ANSWER_TYPE'});
 1932: 
 1933: 		my $anobegin=index($print_array[$i],'\setcounter{page}',0);
 1934: 		substr($print_array[$i],0,$anobegin)='';
 1935: 		$print_array[$i]=$inc.$print_array[$i];
 1936: 	    }
 1937: 	    my $temp_file;
 1938: 	    my $newfilename=$filename;
 1939: 	    my $num=$i+1;
 1940: 	    $newfilename =~s/\.tex$//; 
 1941: 	    $newfilename=sprintf("%s_%03d.tex",$newfilename, $num);
 1942: 	    unless ($temp_file = Apache::File->new('>'.$newfilename)) {
 1943: 		$r->log_error("Couldn't open $newfilename for output $!");
 1944: 		return SERVER_ERROR; 
 1945: 	    }
 1946: 	    print $temp_file $print_array[$i];
 1947: 	}
 1948:     }
 1949:     my $student_names='';
 1950:     if ($#print_array>0) {
 1951: 	for (my $i=0;$i<=$#print_array;$i++) {
 1952: 	    $student_names.=$student_names[$i].'_ENDPERSON_';
 1953: 	}
 1954:     } else {
 1955: 	if ($#student_names>-1) {
 1956: 	    $student_names=$student_names[0].'_ENDPERSON_';
 1957: 	} else {
 1958: 	    my $fullname = &get_name($env{'user.name'},$env{'user.domain'});
 1959: 	    $student_names=join(':',$env{'user.name'},$env{'user.domain'},
 1960: 				$env{'request.course.sec'},$fullname).
 1961: 				    '_ENDPERSON_'.'_END_';
 1962: 	}
 1963:     }
 1964: 
 1965:     my $URLback=''; #link to original document
 1966:     if ($helper->{'VARS'}->{'construction'} ne '1') {
 1967: 	#prints published resource
 1968: 	$URLback=&escape('/adm/flip?postdata=return:');
 1969:     } else {
 1970: 	#prints resource from the construction space
 1971: 	$URLback='/'.$helper->{'VARS'}->{'filename'};
 1972: 	if ($URLback=~/([^?]+)/) {
 1973: 	    $URLback=$1;
 1974: 	    $URLback=~s|^/~|/priv/|;
 1975: 	}
 1976:     }
 1977:     # logic for now is too complex to trace if this has been defined
 1978:     #  yet.
 1979:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1980:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1981:     &Apache::lonnet::appenv('cgi.'.$identifier.'.file'   => $filename,
 1982:                             'cgi.'.$identifier.'.layout'  => $laystyle,
 1983:                             'cgi.'.$identifier.'.numcol'  => $numberofcolumns,
 1984: 			    'cgi.'.$identifier.'.paper'  => $papersize,
 1985:                             'cgi.'.$identifier.'.selection' => $selectionmade,
 1986: 			    'cgi.'.$identifier.'.tableofcontents' => $helper->{'VARS'}->{'TABLE_CONTENTS'},
 1987: 			    'cgi.'.$identifier.'.tableofindex' => $helper->{'VARS'}->{'TABLE_INDEX'},
 1988: 			    'cgi.'.$identifier.'.role' => $perm{'pav'},
 1989:                             'cgi.'.$identifier.'.numberoffiles' => $#print_array,
 1990:                             'cgi.'.$identifier.'.studentnames' => $student_names,
 1991:                             'cgi.'.$identifier.'.backref' => $URLback,);
 1992:     &Apache::lonnet::appenv("cgi.$identifier.user"    => $env{'user.name'},
 1993: 			    "cgi.$identifier.domain"  => $env{'user.domain'},
 1994: 			    "cgi.$identifier.courseid" => $cnum, 
 1995: 			    "cgi.$identifier.coursedom" => $cdom, 
 1996: 			    "cgi.$identifier.resources" => $resources_printed);
 1997: 
 1998:     my $end_page = &Apache::loncommon::end_page();
 1999:     $r->print(<<FINALEND);
 2000: <br />
 2001: <meta http-equiv="Refresh" content="0; url=/cgi-bin/printout.pl?$identifier" />
 2002: <a href="/cgi-bin/printout.pl?$identifier">Continue</a>
 2003: $end_page
 2004: FINALEND
 2005: }
 2006: 
 2007: 
 2008: sub get_CODE {
 2009:     my ($all_codes,$num,$seed,$size,$type)=@_;
 2010:     my $max='1'.'0'x$size;
 2011:     my $newcode;
 2012:     while(1) {
 2013: 	$newcode=sprintf("%0".$size."d",int(rand($max)));
 2014: 	if (!exists($$all_codes{$newcode})) {
 2015: 	    $$all_codes{$newcode}=1;
 2016: 	    if ($type eq 'number' ) {
 2017: 		return $newcode;
 2018: 	    } else {
 2019: 		return &num_to_letters($newcode);
 2020: 	    }
 2021: 	}
 2022:     }
 2023: }
 2024: 
 2025: sub print_resources {
 2026:     my ($r,$helper,$person,$type,$moreenv,$master_seq,$remove_latex_header,
 2027: 	$LaTeXwidth)=@_;
 2028:     my $current_output = ''; 
 2029:     my $printed = '';
 2030:     my ($username,$userdomain,$usersection) = split /:/,$person;
 2031:     my $fullname = &get_name($username,$userdomain);
 2032:     my $namepostfix = "\\\\";	# Both anon and not anon should get the same vspace.
 2033:     if ($person =~ 'anon') {
 2034: 	$namepostfix .="Name: ";
 2035: 	$fullname = "CODE - ".$moreenv->{'CODE'};
 2036:     }
 2037:     #  Fullname may have special latex characters that need \ prefixing:
 2038:     #
 2039: 
 2040:     my $i           = 0;
 2041:     #goes through all resources, checks if they are available for 
 2042:     #current student, and produces output   
 2043: 
 2044:     &Apache::lonxml::clear_problem_counter();
 2045:     my %page_breaks  = &get_page_breaks($helper);
 2046:     my $columns_in_format = (split(/\|/,$helper->{'VARS'}->{'FORMAT'}))[1];
 2047:     #
 2048:     #   end each student with a 
 2049:     #   Special that allows the post processor to even out the page
 2050:     #   counts later.  Nasty problem this... it would be really
 2051:     #   nice to put the special in as a postscript comment
 2052:     #   e.g. \special{ps:\ENDOFSTUDENTSTAMP}  unfortunately,
 2053:     #   The special gets passed the \ and dvips puts it in the output file
 2054:     #   so we will just rely on prntout.pl to strip  ENDOFSTUDENTSTAMP from the
 2055:     #   postscript.  Each ENDOFSTUDENTSTAMP will go on a line by itself.
 2056:     #
 2057: 
 2058:     foreach my $curresline (@{$master_seq})  {
 2059: 	if (defined $page_breaks{$curresline}) {
 2060: 	    if($i != 0) {
 2061: 		$current_output.= "\\newpage\n";
 2062: 	    }
 2063: 	}
 2064: 	$i++;
 2065: 	if ( !($type eq 'problems' && 
 2066: 	       ($curresline!~ m/\.(problem|exam|quiz|assess|survey|form|library)$/)) ) {
 2067: 	    my ($map,$id,$res_url) = &Apache::lonnet::decode_symb($curresline);
 2068: 	    if (&Apache::lonnet::allowed('bre',$res_url)) {
 2069: 		if ($res_url!~m|^ext/|
 2070: 		    && $res_url=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 2071: 		    $printed .= $curresline.':';
 2072: 
 2073: 		    &Apache::lonxml::remember_problem_counter();    
 2074: 
 2075: 		    my $rendered = &Apache::loncommon::get_student_view($curresline,$username,$userdomain,$env{'request.course.id'},'tex',$moreenv);
 2076: 
 2077: 		    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2078: 		       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2079: 			#   Use a copy of the hash so we don't pervert it on future loop passes.
 2080: 			my %answerenv = %{$moreenv};
 2081: 			$answerenv{'answer_output_mode'}='tex';
 2082: 			$answerenv{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2083: 			
 2084: 			&Apache::lonxml::restore_problem_counter();
 2085: 
 2086: 			my $ansrendered = &Apache::loncommon::get_student_answers($curresline,$username,$userdomain,$env{'request.course.id'},%answerenv);
 2087: 
 2088: 			if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2089: 			    $rendered=~s/(\\keephidden{ENDOFPROBLEM})/$ansrendered$1/;
 2090: 			} else {
 2091: 
 2092: 			    
 2093: 			    my $header =&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2094: 			    my $title = &Apache::lonnet::gettitle($curresline);
 2095: 			    $title = &Apache::lonxml::latex_special_symbols($title);
 2096: 			    my $body   ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2097: 			    $body     .=&path_to_problem($res_url,$LaTeXwidth);
 2098: 			    $body     .='\vskip 1 mm '.$ansrendered;
 2099: 			    $body     = &encapsulate_minipage($body);
 2100: 			    $rendered = $header.$body;
 2101: 			}
 2102: 		    }
 2103: 		    if ($remove_latex_header eq 'YES') {
 2104: 			$rendered = &latex_header_footer_remove($rendered);
 2105: 		    } else {
 2106: 			$rendered =~ s/\\end{document}//;
 2107: 		    }
 2108: 		    $current_output .= $rendered;		    
 2109: 		} elsif ($res_url=~/\/(smppg|syllabus|aboutme|bulletinboard)$/) {
 2110: 		    $printed .= $curresline.':';
 2111: 		    my $rendered = &Apache::loncommon::get_student_view($curresline,$username,$userdomain,$env{'request.course.id'},'tex',$moreenv);
 2112: 
 2113: 		    if ($remove_latex_header eq 'YES') {
 2114: 			$rendered = &latex_header_footer_remove($rendered);
 2115: 		    } else {
 2116: 			$rendered =~ s/\\end{document}//;
 2117: 		    }
 2118: 		    $current_output .= $rendered.'\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\strut \vskip 0 mm \strut ';
 2119: 
 2120: 		} else {
 2121: 		    my $rendered = &unsupported($res_url,$helper->{'VARS'}->{'LATEX_TYPE'},$curresline);
 2122: 		    if ($remove_latex_header ne 'NO') {
 2123: 			$rendered = &latex_header_footer_remove($rendered);
 2124: 		    } else {
 2125: 			$rendered =~ s/\\end{document}//;
 2126: 		    }
 2127: 		    $current_output .= $rendered;
 2128: 		}
 2129: 	    }
 2130: 	    $remove_latex_header = 'YES';
 2131: 	}
 2132: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 2133:     }
 2134:     my $courseidinfo = &get_course();
 2135:     if (defined($courseidinfo)) { $courseidinfo=' - '.$courseidinfo }
 2136:     if ($usersection ne '') {$courseidinfo.=' - Sec. '.$usersection}
 2137:     my $currentassignment=&Apache::lonxml::latex_special_symbols($helper->{VARS}->{'assignment'},'header');
 2138:     my $header_line =
 2139: 	&format_page_header($LaTeXwidth, $parmhash{'print_header_format'},
 2140: 			    $currentassignment, $courseidinfo, $fullname);
 2141:     my $header_start = ($columns_in_format == 1) ? '\lhead'
 2142: 	                                         : '\fancyhead[LO]';
 2143:     $header_line = $header_start.'{'.$header_line.'}';
 2144: 
 2145:     if ($current_output=~/\\documentclass/) {
 2146: 	$current_output =~ s/\\begin{document}/\\setlength{\\topmargin}{1cm} \\begin{document}\\noindent\\parbox{\\minipagewidth}{\\noindent$header_line$namepostfix}\\vskip 5 mm /;
 2147:     } else {
 2148: 	my $blankpages = 
 2149: 	    '\clearpage\strut\clearpage'x$helper->{'VARS'}->{'EMPTY_PAGES'};
 2150: 	    
 2151: 	$current_output = '\strut\vspace*{-6 mm}\\newline'.
 2152: 	    &copyright_line().' \newpage '.$blankpages.$end_of_student.
 2153: 	    '\setcounter{page}{1}\noindent\parbox{\minipagewidth}{\noindent'.
 2154: 	    $header_line.$namepostfix.'} \vskip 5 mm '.$current_output;
 2155:     }
 2156:     #
 2157:     #  Close the student bracketing.
 2158:     #
 2159:     return ($current_output,$fullname, $printed);
 2160: 
 2161: }
 2162: 
 2163: sub handler {
 2164: 
 2165:     my $r = shift;
 2166:     
 2167:     &init_perm();
 2168: 
 2169: 
 2170: 
 2171:     my $helper = printHelper($r);
 2172:     if (!ref($helper)) {
 2173: 	return $helper;
 2174:     }
 2175:    
 2176: 
 2177:     %parmhash=&Apache::lonnet::coursedescription($env{'request.course.id'});
 2178:  
 2179: 
 2180: 
 2181: 
 2182:     #  If a figure conversion queue file exists for this user.domain
 2183:     # we delete it since it can only be bad (if it were good, printout.pl
 2184:     # would have deleted it the last time around.
 2185: 
 2186:     my $conversion_queuefile = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.dat";
 2187:     if(-e $conversion_queuefile) {
 2188: 	unlink $conversion_queuefile;
 2189:     }
 2190:     &output_data($r,$helper,\%parmhash);
 2191:     return OK;
 2192: } 
 2193: 
 2194: use Apache::lonhelper;
 2195: 
 2196: sub addMessage {
 2197:     my $text = shift;
 2198:     my $paramHash = Apache::lonhelper::getParamHash();
 2199:     $paramHash->{MESSAGE_TEXT} = $text;
 2200:     Apache::lonhelper::message->new();
 2201: }
 2202: 
 2203: 
 2204: 
 2205: sub init_perm {
 2206:     undef(%perm);
 2207:     $perm{'pav'}=&Apache::lonnet::allowed('pav',$env{'request.course.id'});
 2208:     if (!$perm{'pav'}) {
 2209: 	$perm{'pav'}=&Apache::lonnet::allowed('pav',
 2210: 		  $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 2211:     }
 2212:     $perm{'pfo'}=&Apache::lonnet::allowed('pfo',$env{'request.course.id'});
 2213:     if (!$perm{'pfo'}) {
 2214: 	$perm{'pfo'}=&Apache::lonnet::allowed('pfo',
 2215: 		  $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 2216:     }
 2217: }
 2218: 
 2219: sub printHelper {
 2220:     my $r = shift;
 2221: 
 2222:     if ($r->header_only) {
 2223:         if ($env{'browser.mathml'}) {
 2224:             &Apache::loncommon::content_type($r,'text/xml');
 2225:         } else {
 2226:             &Apache::loncommon::content_type($r,'text/html');
 2227:         }
 2228:         $r->send_http_header;
 2229:         return OK;
 2230:     }
 2231: 
 2232:     # Send header, nocache
 2233:     if ($env{'browser.mathml'}) {
 2234:         &Apache::loncommon::content_type($r,'text/xml');
 2235:     } else {
 2236:         &Apache::loncommon::content_type($r,'text/html');
 2237:     }
 2238:     &Apache::loncommon::no_cache($r);
 2239:     $r->send_http_header;
 2240:     $r->rflush();
 2241: 
 2242:     # Unfortunately, this helper is so complicated we have to
 2243:     # write it by hand
 2244: 
 2245:     Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
 2246:     
 2247:     my $helper = Apache::lonhelper::helper->new("Printing Helper");
 2248:     $helper->declareVar('symb');
 2249:     $helper->declareVar('postdata');    
 2250:     $helper->declareVar('curseed'); 
 2251:     $helper->declareVar('probstatus');   
 2252:     $helper->declareVar('filename');
 2253:     $helper->declareVar('construction');
 2254:     $helper->declareVar('assignment');
 2255:     $helper->declareVar('style_file');
 2256:     $helper->declareVar('student_sort');
 2257:     $helper->declareVar('FINISHPAGE');
 2258:     $helper->declareVar('PRINT_TYPE');
 2259:     $helper->declareVar("showallfoils");
 2260:     $helper->declareVar("STUDENTS");
 2261: 
 2262:     #  The page breaks can get loaded initially from the course environment:
 2263:     # But we only do this in the initial state so that they are allowed to change.
 2264:     #
 2265: 
 2266:     # $helper->{VARS}->{FINISHPAGE} = '';
 2267:     
 2268:     &Apache::loncommon::restore_course_settings('print',
 2269: 						{'pagebreaks'  => 'scalar',
 2270: 					         'lastprinttype' => 'scalar'});
 2271:     
 2272:     # This will persistently load in the data we want from the
 2273:     # very first screen.
 2274:     
 2275:     if($helper->{VARS}->{PRINT_TYPE} eq $env{'form.lastprinttype'}) {
 2276: 	if (!defined ($env{"form.CURRENT_STATE"})) {
 2277: 	    
 2278: 	    $helper->{VARS}->{FINISHPAGE} = $env{'form.pagebreaks'};
 2279: 	} else {
 2280: 	    my $state = $env{"form.CURRENT_STATE"};
 2281: 	    if ($state eq "START") {
 2282: 		$helper->{VARS}->{FINISHPAGE} = $env{'form.pagebreaks'};
 2283: 	    }
 2284: 	}
 2285: 	
 2286:     }
 2287: 
 2288: 
 2289:     # Detect whether we're coming from construction space
 2290:     if ($env{'form.postdata'}=~/^(?:http:\/\/[^\/]+\/|\/|)\~([^\/]+)\/(.*)$/) {
 2291:         $helper->{VARS}->{'filename'} = "~$1/$2";
 2292:         $helper->{VARS}->{'construction'} = 1;
 2293:     } else {
 2294:         if ($env{'form.postdata'}) {
 2295:             $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($env{'form.postdata'});
 2296: 	    if ( $helper->{VARS}->{'symb'} eq '') {
 2297: 		$helper->{VARS}->{'postdata'} = $env{'form.postdata'};
 2298: 	    }
 2299:         }
 2300:         if ($env{'form.symb'}) {
 2301:             $helper->{VARS}->{'symb'} = $env{'form.symb'};
 2302:         }
 2303:         if ($env{'form.url'}) {
 2304:             $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($helper->{VARS}->{'postdata'});
 2305:         }
 2306: 
 2307:     }
 2308: 
 2309:     if ($env{'form.symb'}) {
 2310:         $helper->{VARS}->{'symb'} = $env{'form.symb'};
 2311:     }
 2312:     if ($env{'form.url'}) {
 2313:         $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($helper->{VARS}->{'postdata'});
 2314: 
 2315:     }
 2316:     $helper->{VARS}->{'symb'}=
 2317: 	&Apache::lonenc::check_encrypt($helper->{VARS}->{'symb'});
 2318:     my ($resourceTitle,$sequenceTitle,$mapTitle) = &details_for_menu($helper);
 2319:     if ($sequenceTitle ne '') {$helper->{VARS}->{'assignment'}=$sequenceTitle;}
 2320: 
 2321:     
 2322:     # Extract map
 2323:     my $symb = $helper->{VARS}->{'symb'};
 2324:     my ($map, $id, $url);
 2325:     my $subdir;
 2326:     my $is_published=0;		# True when printing from resource space.
 2327: 
 2328:     # Get the resource name from construction space
 2329:     if ($helper->{VARS}->{'construction'}) {
 2330:         $resourceTitle = substr($helper->{VARS}->{'filename'}, 
 2331:                                 rindex($helper->{VARS}->{'filename'}, '/')+1);
 2332:         $subdir = substr($helper->{VARS}->{'filename'},
 2333:                          0, rindex($helper->{VARS}->{'filename'}, '/') + 1);
 2334:     } else {
 2335: 	if ($symb ne '') {
 2336: 	    ($map, $id, $url) = &Apache::lonnet::decode_symb($symb);
 2337: 	    $helper->{VARS}->{'postdata'} = 
 2338: 		&Apache::lonenc::check_encrypt(&Apache::lonnet::clutter($url));
 2339: 	} else {
 2340: 	    $url = $helper->{VARS}->{'postdata'};
 2341: 	    $is_published=1;	# From resource space.
 2342: 	}
 2343: 	$url = &Apache::lonnet::clutter($url);
 2344: 
 2345:         if (!$resourceTitle) { # if the resource doesn't have a title, use the filename
 2346:             my $postdata = $helper->{VARS}->{'postdata'};
 2347:             $resourceTitle = substr($postdata, rindex($postdata, '/') + 1);
 2348:         }
 2349:         $subdir = &Apache::lonnet::filelocation("", $url);
 2350:     }
 2351:     if (!$helper->{VARS}->{'curseed'} && $env{'form.curseed'}) {
 2352: 	$helper->{VARS}->{'curseed'}=$env{'form.curseed'};
 2353:     }
 2354:     if (!$helper->{VARS}->{'probstatus'} && $env{'form.problemtype'}) {
 2355: 	$helper->{VARS}->{'probstatus'}=$env{'form.problemtype'};
 2356:     }
 2357: 
 2358:     my $userCanSeeHidden = Apache::lonnavmaps::advancedUser();
 2359: 
 2360:     Apache::lonhelper::registerHelperTags();
 2361: 
 2362:     # "Delete everything after the last slash."
 2363:     $subdir =~ s|/[^/]+$||;
 2364: 
 2365:     # What can be printed is a very dynamic decision based on
 2366:     # lots of factors. So we need to dynamically build this list.
 2367:     # To prevent security leaks, states are only added to the wizard
 2368:     # if they can be reached, which ensures manipulating the form input
 2369:     # won't allow anyone to reach states they shouldn't have permission
 2370:     # to reach.
 2371: 
 2372:     # printChoices is tracking the kind of printing the user can
 2373:     # do, and will be used in a choices construction later.
 2374:     # In the meantime we will be adding states and elements to
 2375:     # the helper by hand.
 2376:     my $printChoices = [];
 2377:     my $paramHash;
 2378: 
 2379:     if ($resourceTitle) {
 2380:         push @{$printChoices}, ["<b><i>$resourceTitle</i></b> (".&mt('the resource you just saw on the screen').")", 'current_document', 'PAGESIZE'];
 2381:     }
 2382: 
 2383:     # Useful filter strings
 2384:     my $isProblem = '($res->is_problem()||$res->contains_problem) ';
 2385:     $isProblem .= ' && !$res->randomout()' if !$userCanSeeHidden;
 2386:     my $isProblemOrMap = '$res->is_problem() || $res->contains_problem() || $res->is_sequence()';
 2387:     my $isNotMap = '!$res->is_sequence()';
 2388:     $isNotMap .= ' && !$res->randomout()' if !$userCanSeeHidden;
 2389:     my $isMap = '$res->is_map()';
 2390:     my $symbFilter = '$res->shown_symb()';
 2391:     my $urlValue = '$res->link()';
 2392: 
 2393:     $helper->declareVar('SEQUENCE');
 2394: 
 2395:     # If we're in a sequence...
 2396: 
 2397:     my $start_new_option;
 2398:     if ($perm{'pav'}) {
 2399: 	$start_new_option = 
 2400: 	    "<option text='".&mt('Start new page<br />before selected').
 2401: 	    "' variable='FINISHPAGE' />";
 2402:     }
 2403: 
 2404:     if (($helper->{'VARS'}->{'construction'} ne '1' ) &&
 2405: 
 2406: 	$helper->{VARS}->{'postdata'} &&
 2407: 	$helper->{VARS}->{'assignment'}) {
 2408:         # Allow problems from sequence
 2409:         push @{$printChoices}, [&mt('Selected <b>Problems</b> in folder <b><i>[_1]</i></b>',$sequenceTitle), 'map_problems', 'CHOOSE_PROBLEMS'];
 2410:         # Allow all resources from sequence
 2411:         push @{$printChoices}, [&mt('Selected <b>Resources</b> in folder <b><i>[_1]</i></b>',$sequenceTitle), 'map_problems_pages', 'CHOOSE_PROBLEMS_HTML'];
 2412: 
 2413:         my $helperFragment = <<HELPERFRAGMENT;
 2414:   <state name="CHOOSE_PROBLEMS" title="Select Problem(s) to print">
 2415:     <resource variable="RESOURCES" multichoice="1" toponly='1' addstatus="1"
 2416:               closeallpages="1">
 2417:       <nextstate>PAGESIZE</nextstate>
 2418:       <filterfunc>return $isProblem;</filterfunc>
 2419:       <mapurl>$map</mapurl>
 2420:       <valuefunc>return $symbFilter;</valuefunc>
 2421:       $start_new_option
 2422:       </resource>
 2423:     </state>
 2424: 
 2425:   <state name="CHOOSE_PROBLEMS_HTML" title="Select Resource(s) to print">
 2426:     <resource variable="RESOURCES" multichoice="1" toponly='1' addstatus="1"
 2427:               closeallpages="1">
 2428:       <nextstate>PAGESIZE</nextstate>
 2429:       <filterfunc>return $isNotMap;</filterfunc>
 2430:       <mapurl>$map</mapurl>
 2431:       <valuefunc>return $symbFilter;</valuefunc>
 2432:       $start_new_option
 2433:       </resource>
 2434:     </state>
 2435: HELPERFRAGMENT
 2436: 
 2437: 	&Apache::lonxml::xmlparse($r, 'helper', $helperFragment);
 2438:     }
 2439: 
 2440:     # If the user has pfo (print for otheres) allow them to print all 
 2441:     # problems and resources  in the entier course, optionally for selected students
 2442:     if ($perm{'pfo'} &&  !$is_published  &&
 2443:         ($helper->{VARS}->{'postdata'}=~/\/res\// || $helper->{VARS}->{'postdata'}=~/\/(syllabus|smppg|aboutme|bulletinboard)$/)) { 
 2444: 
 2445:         push @{$printChoices}, ['Selected <b>Problems</b> from <b>entire course</b>', 'all_problems', 'ALL_PROBLEMS'];
 2446: 	push @{$printChoices}, ['Selected <b>Resources</b> from <b>entire course</b>', 'all_resources', 'ALL_RESOURCES'];
 2447:          &Apache::lonxml::xmlparse($r, 'helper', <<ALL_PROBLEMS);
 2448:   <state name="ALL_PROBLEMS" title="Select Problem(s) to print">
 2449:     <resource variable="RESOURCES" toponly='0' multichoice="1"
 2450: 	suppressEmptySequences='0' addstatus="1" closeallpages="1">
 2451:       <nextstate>PAGESIZE</nextstate>
 2452:       <filterfunc>return $isProblemOrMap;</filterfunc>
 2453:       <choicefunc>return $isNotMap;</choicefunc>
 2454:       <valuefunc>return $symbFilter;</valuefunc>
 2455:       $start_new_option
 2456:     </resource>
 2457:   </state>
 2458:   <state name="ALL_RESOURCES" title="Select Resource(s) to print">
 2459:     <resource variable="RESOURCES" toponly='0' multichoice='1'
 2460:               suppressEmptySequences='0' addstatus='1' closeallpages='1'>
 2461:       <nextstate>PAGESIZE</nextstate>
 2462:       <filterfunc>return $isNotMap; </filterfunc>
 2463:       <valuefunc>return $symbFilter;</valuefunc>
 2464:       $start_new_option
 2465:     </resource>
 2466:   </state>
 2467: ALL_PROBLEMS
 2468: 
 2469: 	if ($helper->{VARS}->{'assignment'}) {
 2470: 	    push @{$printChoices}, [&mt("Selected <b>Problems</b> from folder <b><i>[_1]</i></b> for <b>selected people</b>",$sequenceTitle), 'problems_for_students', 'CHOOSE_STUDENTS'];
 2471: 	    push @{$printChoices}, [&mt("Selected <b>Problems</b> from folder <b><i>[_1]</i></b> for <b>CODEd assignments</b>",$sequenceTitle), 'problems_for_anon', 'CHOOSE_ANON1'];
 2472: 	}
 2473: 
 2474: 	# resource_selector will hold a few states that:
 2475: 	#   - Allow resources to be selected for printing.
 2476: 	#   - Determine pagination between assignments.
 2477: 	#   - Determine how many assignments should be bundled into a single PDF.
 2478:         # TODO:
 2479: 	#    Probably good to do things like separate this up into several vars, each
 2480: 	#    with one state, and use REGEXPs at inclusion time to set state names
 2481: 	#    and next states for better mix and match capability
 2482: 	#
 2483: 	my $resource_selector=<<RESOURCE_SELECTOR;
 2484:     <state name="SELECT_PROBLEMS" title="Select resources to print">
 2485:    <nextstate>PRINT_FORMATTING</nextstate> 
 2486:    <message><br /><big><i><b>Select resources for the assignment</b></i></big><br /></message>
 2487:     <resource variable="RESOURCES" multichoice="1" addstatus="1" 
 2488:               closeallpages="1">
 2489:       <filterfunc>return $isProblem;</filterfunc>
 2490:       <mapurl>$map</mapurl>
 2491:       <valuefunc>return $symbFilter;</valuefunc>
 2492:       $start_new_option
 2493:       </resource>
 2494:     </state>
 2495:     <state name="PRINT_FORMATTING" title="How should results be printed?">
 2496:     <message><br /><big><i><b>How should the results be printed?</b></i></big><br /></message>
 2497:     <choices variable="EMPTY_PAGES">
 2498:       <choice computer='0'>Start each student\'s assignment on a new page/column (add a pagefeed after each assignment)</choice>
 2499:       <choice computer='1'>Add one empty page/column after each student\'s assignment</choice>
 2500:       <choice computer='2'>Add two empty pages/column after each student\'s assignment</choice>
 2501:       <choice computer='3'>Add three empty pages/column after each student\'s assignment</choice>
 2502:     </choices>
 2503:     <nextstate>PAGESIZE</nextstate>
 2504:     <message><hr width='33%' /><b>How do you want assignments split into PDF files? </b></message>
 2505:     <choices variable="SPLIT_PDFS">
 2506:        <choice computer="all">All assignments in a single PDF file</choice>
 2507:        <choice computer="sections">Each PDF contains exactly one section</choice>
 2508:        <choice computer="oneper">Each PDF contains exactly one assignment</choice>
 2509:        <choice computer="usenumber" relatedvalue="NUMBER_TO_PRINT">
 2510:             Specify the number of assignments per PDF:</choice>
 2511:     </choices>
 2512:     </state>
 2513: RESOURCE_SELECTOR
 2514: 
 2515:         &Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_STUDENTS);
 2516:   <state name="CHOOSE_STUDENTS" title="Select Students and Resources">
 2517:       <message><b>Select sorting order of printout</b> </message>
 2518:     <choices variable='student_sort'>
 2519:       <choice computer='0'>Sort by section then student</choice>
 2520:       <choice computer='1'>Sort by students across sections.</choice>
 2521:     </choices>
 2522:       <message><br /><hr /><br /> </message>
 2523:       <student multichoice='1' variable="STUDENTS" nextstate="SELECT_PROBLEMS" coursepersonnel="1"/>
 2524:   </state>
 2525:     $resource_selector
 2526: CHOOSE_STUDENTS
 2527: 
 2528: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2529: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2530:         my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 2531: 	my $namechoice='<choice></choice>';
 2532: 	foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 2533: 	    if ($name =~ /^error: 2 /) { next; }
 2534: 	    if ($name =~ /^type\0/) { next; }
 2535: 	    $namechoice.='<choice computer="'.$name.'">'.$name.'</choice>';
 2536: 	}
 2537: 
 2538: 
 2539: 	my %code_values;
 2540: 	my %codes_to_print;
 2541: 	foreach my $key (@names) {
 2542: 	    %code_values = &Apache::grades::get_codes($key, $cdom, $cnum);
 2543: 	    foreach my $key (keys(%code_values)) {
 2544: 		$codes_to_print{$key} = 1;
 2545: 	    }
 2546: 	}
 2547: 
 2548: 	my $code_selection;
 2549: 	foreach my $code (sort {uc($a) cmp uc($b)} (keys(%codes_to_print))) {
 2550: 	    my $choice  = $code;
 2551: 	    if ($code =~ /^[A-Z]+$/) { # Alpha code
 2552: 		$choice = &letters_to_num($code);
 2553: 	    }
 2554: 	    push(@{$helper->{DATA}{ALL_CODE_CHOICES}},[$code,$choice]);
 2555: 	}
 2556: 	if (%codes_to_print) {
 2557: 	    $code_selection .='   
 2558: 	    <message><b>Choose single CODE from list:</b></message>
 2559: 		<message></td><td></message>
 2560: 		<dropdown variable="CODE_SELECTED_FROM_LIST" multichoice="0" allowempty="0">
 2561:                   <choice></choice>
 2562:                   <exec>
 2563:                      push(@{$state->{CHOICES}},@{$helper->{DATA}{ALL_CODE_CHOICES}});
 2564:                   </exec>
 2565: 		</dropdown>
 2566: 	    <message></td></tr><tr><td></message>
 2567:             '.$/;
 2568: 
 2569: 	}
 2570: 
 2571: 	
 2572: 	open(FH,$Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 2573: 	my $codechoice='';
 2574: 	foreach my $line (<FH>) {
 2575: 	    my ($name,$description,$code_type,$code_length)=
 2576: 		(split(/:/,$line))[0,1,2,4];
 2577: 	    if ($code_length > 0 && 
 2578: 		$code_type =~/^(letter|number|-1)/) {
 2579: 		$codechoice.='<choice computer="'.$name.'">'.$description.'</choice>';
 2580: 	    }
 2581: 	}
 2582: 	if ($codechoice eq '') {
 2583: 	    $codechoice='<choice computer="default">Default</choice>';
 2584: 	}
 2585:         &Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_ANON1);
 2586:   <state name="CHOOSE_ANON1" title="Specify CODEd Assignments">
 2587:     <nextstate>SELECT_PROBLEMS</nextstate>
 2588:     <message><h4>Fill out one of the forms below</h4></message>
 2589:     <message><br /><hr /> <br /></message>
 2590:     <message><h3>Generate new CODEd Assignments</h3></message>
 2591:     <message><table><tr><td><b>Number of CODEd assignments to print:</b></td><td></message>
 2592:     <string variable="NUMBER_TO_PRINT_TOTAL" maxlength="5" size="5">
 2593:        <validator>
 2594: 	if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) < 1) &&
 2595: 	    !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                &&
 2596:             !\$helper->{'VARS'}{'SINGLE_CODE'}                    &&
 2597: 	    !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 2598: 	    return "You need to specify the number of assignments to print";
 2599: 	}
 2600: 	return undef;
 2601:        </validator>
 2602:     </string>
 2603:     <message></td></tr><tr><td></message>
 2604:     <message><b>Names to save the CODEs under for later:</b></message>
 2605:     <message></td><td></message>
 2606:     <string variable="ANON_CODE_STORAGE_NAME" maxlength="50" size="20" />
 2607:     <message></td></tr><tr><td></message>
 2608:     <message><b>Bubble sheet type:</b></message>
 2609:     <message></td><td></message>
 2610:     <dropdown variable="CODE_OPTION" multichoice="0" allowempty="0">
 2611:     $codechoice
 2612:     </dropdown>
 2613:     <message></td></tr><tr><td colspan="2"></td></tr><tr><td></message>
 2614:     <message></td></tr><tr><td></table></message>
 2615:     <message><br /><hr /><h3>Print a Specific CODE </h3><br /><table></message>
 2616:     <message><tr><td><b>Enter a CODE to print:</b></td><td></message>
 2617:     <string variable="SINGLE_CODE" size="10">
 2618:         <validator>
 2619: 	   if(!\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}           &&
 2620: 	      !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                 &&
 2621: 	      !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 2622: 	      return &Apache::lonprintout::is_code_valid(\$helper->{'VARS'}{'SINGLE_CODE'},
 2623: 						      \$helper->{'VARS'}{'CODE_OPTION'});
 2624: 	   } else {
 2625: 	       return undef;	# Other forces control us.
 2626: 	   }
 2627:         </validator>
 2628:     </string>
 2629:     <message></td></tr><tr><td></message>
 2630:         $code_selection
 2631:     <message></td></tr></table></message>
 2632:     <message><hr /><h3>Reprint a Set of Saved CODEs</h3><table><tr><td></message>
 2633:     <message><b>Select saved CODEs:</b></message>
 2634:     <message></td><td></message>
 2635:     <dropdown variable="REUSE_OLD_CODES">
 2636:         $namechoice
 2637:     </dropdown>
 2638:     <message></td></tr></table></message>
 2639:   </state>
 2640:   $resource_selector
 2641: CHOOSE_ANON1
 2642: 
 2643: 
 2644: 	if ($helper->{VARS}->{'assignment'}) {
 2645: 	    push @{$printChoices}, [&mt("Selected <b>Resources</b> from folder <b><i>[_1]</i></b> for <b>selected people</b>",$sequenceTitle), 'resources_for_students', 'CHOOSE_STUDENTS1'];
 2646: 	    push @{$printChoices}, [&mt("Selected <b>Resources</b> from folder <b><i>[_1]</i></b> for <b>CODEd assignments</b>",$sequenceTitle), 'resources_for_anon', 'CHOOSE_ANON2'];
 2647: 	}
 2648: 	    
 2649: 
 2650: 	$resource_selector=<<RESOURCE_SELECTOR;
 2651:     <state name="SELECT_RESOURCES" title="Select Resources">
 2652:     <nextstate>PRINT_FORMATTING</nextstate>
 2653:     <message><br /><big><i><b>Select resources for the assignment</b></i></big><br /></message>
 2654:     <resource variable="RESOURCES" multichoice="1" addstatus="1" 
 2655:               closeallpages="1">
 2656:       <filterfunc>return $isNotMap;</filterfunc>
 2657:       <mapurl>$map</mapurl>
 2658:       <valuefunc>return $symbFilter;</valuefunc>
 2659:       $start_new_option
 2660:       </resource>
 2661:     </state>
 2662:     <state name="PRINT_FORMATTING" title="Format of the print job">
 2663:     <nextstate>NUMBER_PER_PDF</nextstate>
 2664:     <message><br /><big><i><b>How should the results be printed?</b></i></big><br /></message>
 2665:     <choices variable="EMPTY_PAGES">
 2666:       <choice computer='0'>Start each student\'s assignment on a new page/column (add a pagefeed after each assignment)</choice>
 2667:       <choice computer='1'>Add one empty page/column after each student\'s assignment</choice>
 2668:       <choice computer='2'>Add two empty pages/column after each student\'s assignment</choice>
 2669:       <choice computer='3'>Add three empty pages/column after each student\'s assignment</choice>
 2670:     </choices>
 2671:     <nextstate>PAGESIZE</nextstate>
 2672:     <message><hr width='33%' /><b>How do you want assignments split into PDF files? </b></message>
 2673:     <choices variable="SPLIT_PDFS">
 2674:        <choice computer="all">All assignments in a single PDF file</choice>
 2675:        <choice computer="sections">Each PDF contains exactly one section</choice>
 2676:        <choice computer="oneper">Each PDF contains exactly one assignment</choice>
 2677:        <choice computer="usenumber" relatedvalue="NUMBER_TO_PRINT">
 2678:            Specify the number of assignments per PDF:</choice>
 2679:     </choices>
 2680:     </state>
 2681: RESOURCE_SELECTOR
 2682: 
 2683: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_STUDENTS1);
 2684:   <state name="CHOOSE_STUDENTS1" title="Select Students and Resources">
 2685:     <choices variable='student_sort'>
 2686:       <choice computer='0'>Sort by section then student</choice>
 2687:       <choice computer='1'>Sort by students across sections.</choice>
 2688:     </choices>
 2689:     <message><br /><hr /><br /></message>
 2690:     <student multichoice='1' variable="STUDENTS" nextstate="SELECT_RESOURCES" coursepersonnel="1" />
 2691: 
 2692:     </state>
 2693:     $resource_selector
 2694: CHOOSE_STUDENTS1
 2695: 
 2696: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_ANON2);
 2697:   <state name="CHOOSE_ANON2" title="Select CODEd Assignments">
 2698:     <nextstate>SELECT_RESOURCES</nextstate>
 2699:     <message><h4>Fill out one of the forms below</h4></message>
 2700:     <message><br /><hr /> <br /></message>
 2701:     <message><h3>Generate new CODEd Assignments</h3></message>
 2702:     <message><table><tr><td><b>Number of CODEd assignments to print:</b></td><td></message>
 2703:     <string variable="NUMBER_TO_PRINT_TOTAL" maxlength="5" size="5">
 2704:        <validator>
 2705: 	if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) < 1) &&
 2706: 	    !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                &&
 2707: 	    !\$helper->{'VARS'}{'SINGLE_CODE'}                   &&
 2708: 	    !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 2709: 	    return "You need to specify the number of assignments to print";
 2710: 	}
 2711: 	return undef;
 2712:        </validator>
 2713:     </string>
 2714:     <message></td></tr><tr><td></message>
 2715:     <message><b>Names to save the CODEs under for later:</b></message>
 2716:     <message></td><td></message>
 2717:     <string variable="ANON_CODE_STORAGE_NAME" maxlength="50" size="20" />
 2718:     <message></td></tr><tr><td></message>
 2719:     <message><b>Bubble sheet type:</b></message>
 2720:     <message></td><td></message>
 2721:     <dropdown variable="CODE_OPTION" multichoice="0" allowempty="0">
 2722:     $codechoice
 2723:     </dropdown>
 2724:     <message></td></tr><tr><td></table></message>
 2725:     <message><br /><hr /><h3>Print a Specific CODE </h3><br /><table></message>
 2726:     <message><tr><td><b>Enter a CODE to print:</b></td><td></message>
 2727:     <string variable="SINGLE_CODE" size="10">
 2728:         <validator>
 2729: 	   if(!\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}           &&
 2730: 	      !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                 &&
 2731: 	      !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 2732: 	      return &Apache::lonprintout::is_code_valid(\$helper->{'VARS'}{'SINGLE_CODE'},
 2733: 						      \$helper->{'VARS'}{'CODE_OPTION'});
 2734: 	   } else {
 2735: 	       return undef;	# Other forces control us.
 2736: 	   }
 2737:         </validator>
 2738:     </string>
 2739:     <message></td></tr><tr><td></message>
 2740:         $code_selection
 2741:     <message></td></tr></table></message>
 2742:     <message><hr /><h3>Reprint a Set of Saved CODEs</h3><table><tr><td></message>
 2743:     <message><b>Select saved CODEs:</b></message>
 2744:     <message></td><td></message>
 2745:     <dropdown variable="REUSE_OLD_CODES">
 2746:         $namechoice
 2747:     </dropdown>
 2748:     <message></td></tr></table></message>
 2749:   </state>
 2750:     $resource_selector
 2751: CHOOSE_ANON2
 2752:     }
 2753: 
 2754:     # FIXME: That RE should come from a library somewhere.
 2755:     if (($perm{'pav'} 
 2756: 	&& $subdir ne $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'
 2757: 	&& (defined($helper->{'VARS'}->{'construction'})
 2758: 	    ||
 2759: 	    (&Apache::lonnet::allowed('bre',$subdir) eq 'F'
 2760: 	     && 
 2761: 	     $helper->{VARS}->{'postdata'}=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)/)
 2762: 	    )) 
 2763: 	&& $helper->{VARS}->{'assignment'} eq ""
 2764: 	) {
 2765: 
 2766: 	my $pretty_dir = &Apache::lonnet::hreflocation($subdir);
 2767:         push @{$printChoices}, [&mt("Selected <b>Problems</b> from current subdirectory <b><i>[_1]</i></b>",$pretty_dir), 'problems_from_directory', 'CHOOSE_FROM_SUBDIR'];
 2768:         my $xmlfrag = <<CHOOSE_FROM_SUBDIR;
 2769:   <state name="CHOOSE_FROM_SUBDIR" title="Select File(s) from <b><small>$pretty_dir</small></b> to print">
 2770: 
 2771:     <files variable="FILES" multichoice='1'>
 2772:       <nextstate>PAGESIZE</nextstate>
 2773:       <filechoice>return '$subdir';</filechoice>
 2774: CHOOSE_FROM_SUBDIR
 2775:         
 2776:         # this is broken up because I really want interpolation above,
 2777:         # and I really DON'T want it below
 2778:         $xmlfrag .= <<'CHOOSE_FROM_SUBDIR';
 2779:       <filefilter>return Apache::lonhelper::files::not_old_version($filename) &&
 2780: 	  $filename =~ m/\.(problem|exam|quiz|assess|survey|form|library)$/;
 2781:       </filefilter>
 2782:       </files>
 2783:     </state>
 2784: CHOOSE_FROM_SUBDIR
 2785:         &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 2786:     }
 2787: 
 2788:     # Allow the user to select any sequence in the course, feed it to
 2789:     # another resource selector for that sequence
 2790:     if (!$helper->{VARS}->{'construction'} && !$is_published) {
 2791: 	push @$printChoices, ["Selected <b>Resources</b> from <b>selected folder</b> in course",
 2792: 			      'select_sequences', 'CHOOSE_SEQUENCE'];
 2793: 	my $escapedSequenceName = $helper->{VARS}->{'SEQUENCE'};
 2794: 	#Escape apostrophes and backslashes for Perl
 2795: 	$escapedSequenceName =~ s/\\/\\\\/g;
 2796: 	$escapedSequenceName =~ s/'/\\'/g;
 2797: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_FROM_ANY_SEQUENCE);
 2798:   <state name="CHOOSE_SEQUENCE" title="Select Sequence To Print From">
 2799:     <message>Select the sequence to print resources from:</message>
 2800:     <resource variable="SEQUENCE">
 2801:       <nextstate>CHOOSE_FROM_ANY_SEQUENCE</nextstate>
 2802:       <filterfunc>return \$res->is_sequence;</filterfunc>
 2803:       <valuefunc>return $urlValue;</valuefunc>
 2804:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 2805: 	</choicefunc>
 2806:       </resource>
 2807:     </state>
 2808:   <state name="CHOOSE_FROM_ANY_SEQUENCE" title="Select Resources To Print">
 2809:     <message>(mark desired resources then click "next" button) <br /></message>
 2810:     <resource variable="RESOURCES" multichoice="1" toponly='1' addstatus="1"
 2811:               closeallpages="1">
 2812:       <nextstate>PAGESIZE</nextstate>
 2813:       <filterfunc>return $isNotMap</filterfunc>
 2814:       <mapurl evaluate='1'>return '$escapedSequenceName';</mapurl>
 2815:       <valuefunc>return $symbFilter;</valuefunc>
 2816:       $start_new_option
 2817:       </resource>
 2818:     </state>
 2819: CHOOSE_FROM_ANY_SEQUENCE
 2820: }
 2821: 
 2822:     # Generate the first state, to select which resources get printed.
 2823:     Apache::lonhelper::state->new("START", "Select Printing Options:");
 2824:     $paramHash = Apache::lonhelper::getParamHash();
 2825:     $paramHash->{MESSAGE_TEXT} = "";
 2826:     Apache::lonhelper::message->new();
 2827:     $paramHash = Apache::lonhelper::getParamHash();
 2828:     $paramHash->{'variable'} = 'PRINT_TYPE';
 2829:     $paramHash->{CHOICES} = $printChoices;
 2830:     Apache::lonhelper::choices->new();
 2831: 
 2832:     my $startedTable = 0; # have we started an HTML table yet? (need
 2833:                           # to close it later)
 2834: 
 2835:     if (($perm{'pav'} and &Apache::lonnet::allowed('vgr',$env{'request.course.id'})) or 
 2836: 	($helper->{VARS}->{'construction'} eq '1')) {
 2837: 	addMessage("<hr width='33%' /><table><tr><td align='right'>".
 2838:                    '<label for="ANSWER_TYPE_forminput">'.
 2839:                    &mt('Print').
 2840:                    "</label>: </td><td>");
 2841:         $paramHash = Apache::lonhelper::getParamHash();
 2842: 	$paramHash->{'variable'} = 'ANSWER_TYPE';   
 2843: 	$helper->declareVar('ANSWER_TYPE');         
 2844:         $paramHash->{CHOICES} = [
 2845:                                    ['Without Answers', 'yes'],
 2846:                                    ['With Answers', 'no'],
 2847:                                    ['Only Answers', 'only']
 2848:                                 ];
 2849:         Apache::lonhelper::dropdown->new();
 2850: 	addMessage("</td></tr>");
 2851: 	$startedTable = 1;
 2852:     }
 2853: 
 2854:     if ($perm{'pav'}) {
 2855: 	if (!$startedTable) {
 2856: 	    addMessage("<hr width='33%' /><table><tr><td align='right'>".
 2857:                        '<label for="LATEX_TYPE_forminput">'.
 2858:                        &mt('LaTeX mode').
 2859:                        "</label>: </td><td>");
 2860: 	    $startedTable = 1;
 2861: 	} else {
 2862: 	    addMessage("<tr><td align='right'>".
 2863:                        '<label for="LATEX_TYPE_forminput">'.
 2864:                         &mt('LaTeX mode').
 2865:                        "</label>: </td><td>");
 2866: 	}
 2867:         $paramHash = Apache::lonhelper::getParamHash();
 2868: 	$paramHash->{'variable'} = 'LATEX_TYPE';   
 2869: 	$helper->declareVar('LATEX_TYPE');  
 2870: 	if ($helper->{VARS}->{'construction'} eq '1') {       
 2871: 	    $paramHash->{CHOICES} = [
 2872: 				     ['standard LaTeX mode', 'standard'], 
 2873: 				     ['LaTeX batchmode', 'batchmode'], ];
 2874: 	} else {
 2875: 	    $paramHash->{CHOICES} = [
 2876: 				     ['LaTeX batchmode', 'batchmode'],
 2877: 				     ['standard LaTeX mode', 'standard'] ];
 2878: 	}
 2879:         Apache::lonhelper::dropdown->new();
 2880:  
 2881: 	addMessage("</td></tr><tr><td align='right'>".
 2882:                    '<label="TABLE_CONTENTS_forminput">'.
 2883:                    &mt('Print Table of Contents').
 2884:                    "</label>: </td><td>");
 2885:         $paramHash = Apache::lonhelper::getParamHash();
 2886: 	$paramHash->{'variable'} = 'TABLE_CONTENTS';   
 2887: 	$helper->declareVar('TABLE_CONTENTS');         
 2888:         $paramHash->{CHOICES} = [
 2889:                                    ['No', 'no'],
 2890:                                    ['Yes', 'yes'] ];
 2891:         Apache::lonhelper::dropdown->new();
 2892: 	addMessage("</td></tr>");
 2893:         
 2894: 	if (not $helper->{VARS}->{'construction'}) {
 2895: 	    addMessage("<tr><td align='right'>".
 2896:                        '<label for="TABLE_INDEX_forminput">'.
 2897:                        &mt('Print Index').
 2898:                        "</label>: </td><td>");
 2899: 	    $paramHash = Apache::lonhelper::getParamHash();
 2900: 	    $paramHash->{'variable'} = 'TABLE_INDEX';   
 2901: 	    $helper->declareVar('TABLE_INDEX');         
 2902: 	    $paramHash->{CHOICES} = [
 2903: 				     ['No', 'no'],
 2904: 				     ['Yes', 'yes'] ];
 2905: 	    Apache::lonhelper::dropdown->new();
 2906: 	    addMessage("</td></tr>");
 2907: 	    addMessage("<tr><td align='right'>".
 2908:                        '<label for="PRINT_DISCUSSIONS_forminput">'.
 2909:                        &mt('Print Discussions').
 2910:                        "</label>: </td><td>");
 2911: 	    $paramHash = Apache::lonhelper::getParamHash();
 2912: 	    $paramHash->{'variable'} = 'PRINT_DISCUSSIONS';   
 2913: 	    $helper->declareVar('PRINT_DISCUSSIONS');         
 2914: 	    $paramHash->{CHOICES} = [
 2915: 				     ['No', 'no'],
 2916: 				     ['Yes', 'yes'] ];
 2917: 	    Apache::lonhelper::dropdown->new();
 2918: 	    addMessage("</td></tr>");
 2919: 
 2920: 	    addMessage("<tr><td align = 'right'>  </td><td>");
 2921: 	    $paramHash = Apache::lonhelper::getParamHash();
 2922: 	    $paramHash->{'multichoice'} = "true";
 2923: 	    $paramHash->{'allowempty'}  = "true";
 2924: 	    $paramHash->{'variable'}   = "showallfoils";
 2925: 	    $paramHash->{'CHOICES'} = [ ["Show all foils", "1"] ];
 2926: 	    Apache::lonhelper::choices->new();
 2927: 	    addMessage("</td></tr>");
 2928: 	}
 2929: 
 2930: 	if ($helper->{'VARS'}->{'construction'}) { 
 2931: 	    my $stylevalue=$env{'construct.style'};
 2932:             my $randseedtext=&mt("Use random seed");
 2933:             my $stylefiletext=&mt("Use style file");
 2934: 
 2935: 	    my $xmlfrag .= <<"RNDSEED";
 2936: 	    <message><tr><td align='right'>
 2937:             <label for="curseed_forminput">$randseedtext</label>:
 2938:             </td><td></message>
 2939: 	    <string variable="curseed" size="15" maxlength="15">
 2940: 		<defaultvalue>
 2941: 	            return $helper->{VARS}->{'curseed'};
 2942: 	        </defaultvalue>
 2943: 	    </string>
 2944: 	     <message></td></tr><tr><td align="right">
 2945:              <label for="style_file_value">$stylefiletext</label>:
 2946:              </td><td></message>
 2947:              <message><input type="text" size="40" name="style_file_value" value="$stylevalue"  />&nbsp; <a href="javascript:openbrowser('helpform','style_file_value','sty')">Select style file</a> </td><tr><td></message>
 2948: 	     <choices allowempty="1" multichoice="true" variable="showallfoils">
 2949:                 <choice computer="1">Show all foils?</choice>
 2950:              </choices>
 2951: 	     <message></td></tr></message>
 2952: RNDSEED
 2953:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 2954: 	    $helper->{'VARS'}->{'style_file'}=$env{'form.style_file_value'};
 2955: 	    
 2956: 	} 
 2957:     }
 2958: 
 2959: 
 2960: 
 2961: 
 2962:     if ($startedTable) {
 2963: 	addMessage("</table>");
 2964:     }
 2965: 
 2966:     Apache::lonprintout::page_format_state->new("FORMAT");
 2967: 
 2968:     # Generate the PAGESIZE state which will offer the user the margin
 2969:     # choices if they select one column
 2970:     Apache::lonhelper::state->new("PAGESIZE", "Set Margins");
 2971:     Apache::lonprintout::page_size_state->new('pagesize', 'FORMAT', 'FINAL');
 2972: 
 2973: 
 2974:     $helper->process();
 2975: 
 2976: 
 2977:     # MANUAL BAILOUT CONDITION:
 2978:     # If we're in the "final" state, bailout and return to handler
 2979:     if ($helper->{STATE} eq 'FINAL') {
 2980:         return $helper;
 2981:     }    
 2982: 
 2983:     $r->print($helper->display());
 2984:     if ($helper->{STATE} eq 'START') {
 2985: 	&recently_generated($r);
 2986:     }
 2987:     &Apache::lonhelper::unregisterHelperTags();
 2988: 
 2989:     return OK;
 2990: }
 2991: 
 2992: 
 2993: 1;
 2994: 
 2995: package Apache::lonprintout::page_format_state;
 2996: 
 2997: =pod
 2998: 
 2999: =head1 Helper element: page_format_state
 3000: 
 3001: See lonhelper.pm documentation for discussion of the helper framework.
 3002: 
 3003: Apache::lonprintout::page_format_state is an element that gives the 
 3004: user an opportunity to select the page layout they wish to print 
 3005: with: Number of columns, portrait/landscape, and paper size. If you 
 3006: want to change the paper size choices, change the @paperSize array 
 3007: contents in this package.
 3008: 
 3009: page_format_state is always directly invoked in lonprintout.pm, so there
 3010: is no tag interface. You actually pass parameters to the constructor.
 3011: 
 3012: =over 4
 3013: 
 3014: =item * B<new>(varName): varName is where the print information will be stored in the format FIXME.
 3015: 
 3016: =back
 3017: 
 3018: =cut
 3019: 
 3020: use Apache::lonhelper;
 3021: 
 3022: no strict;
 3023: @ISA = ("Apache::lonhelper::element");
 3024: use strict;
 3025: use Apache::lonlocal;
 3026: use Apache::lonnet;
 3027: 
 3028: my $maxColumns = 2;
 3029: # it'd be nice if these all worked
 3030: #my @paperSize = ("letter [8 1/2x11 in]", "legal [8 1/2x14 in]", 
 3031: #                 "tabloid (ledger) [11x17 in]", "executive [7 1/2x10 in]",
 3032: #                 "a2 [420x594 mm]", "a3 [297x420 mm]", "a4 [210x297 mm]", 
 3033: #                 "a5 [148x210 mm]", "a6 [105x148 mm]" );
 3034: my @paperSize = ("letter [8 1/2x11 in]", "legal [8 1/2x14 in]", 
 3035: 		 "a4 [210x297 mm]");
 3036: 
 3037: # Tentative format: Orientation (L = Landscape, P = portrait) | Colnum |
 3038: #                   Paper type
 3039: 
 3040: sub new { 
 3041:     my $self = Apache::lonhelper::element->new();
 3042: 
 3043:     shift;
 3044: 
 3045:     $self->{'variable'} = shift;
 3046:     my $helper = Apache::lonhelper::getHelper();
 3047:     $helper->declareVar($self->{'variable'});
 3048:     bless($self);
 3049:     return $self;
 3050: }
 3051: 
 3052: sub render {
 3053:     my $self = shift;
 3054:     my $helper = Apache::lonhelper::getHelper();
 3055:     my $result = '';
 3056:     my $var = $self->{'variable'};
 3057:     my $PageLayout=&mt('Page layout');
 3058:     my $NumberOfColumns=&mt('Number of columns');
 3059:     my $PaperType=&mt('Paper type');
 3060:     $result .= <<STATEHTML;
 3061: 
 3062: <hr width="33%" />
 3063: <table cellpadding="3">
 3064:   <tr>
 3065:     <td align="center"><b>$PageLayout</b></td>
 3066:     <td align="center"><b>$NumberOfColumns</b></td>
 3067:     <td align="center"><b>$PaperType</b></td>
 3068:   </tr>
 3069:   <tr>
 3070:     <td>
 3071:       <label><input type="radio" name="${var}.layout" value="L" /> Landscape </label><br />
 3072:       <label><input type="radio" name="${var}.layout" value="P" checked='1'  /> Portrait </label>
 3073:     </td>
 3074:     <td align="center">
 3075:       <select name="${var}.cols">
 3076: STATEHTML
 3077: 
 3078:     my $i;
 3079:     for ($i = 1; $i <= $maxColumns; $i++) {
 3080:         if ($i == 2) {
 3081:             $result .= "<option value='$i' selected>$i</option>\n";
 3082:         } else {
 3083:             $result .= "<option value='$i'>$i</option>\n";
 3084:         }
 3085:     }
 3086: 
 3087:     $result .= "</select></td><td>\n";
 3088:     $result .= "<select name='${var}.paper'>\n";
 3089: 
 3090:     my %parmhash=&Apache::lonnet::coursedescription($env{'request.course.id'});
 3091:     my $DefaultPaperSize=lc($parmhash{'default_paper_size'});
 3092:     $DefaultPaperSize=~s/\s//g;
 3093:     if ($DefaultPaperSize eq '') {$DefaultPaperSize='letter';}
 3094:     $i = 0;
 3095:     foreach (@paperSize) {
 3096: 	$_=~/(\w+)/;
 3097: 	my $papersize=$1;
 3098:         if ($paperSize[$i]=~/$DefaultPaperSize/) {
 3099:             $result .= "<option selected value='$papersize'>" . $paperSize[$i] . "</option>\n";
 3100:         } else {
 3101:             $result .= "<option value='$papersize'>" . $paperSize[$i] . "</option>\n";
 3102:         }
 3103:         $i++;
 3104:     }
 3105:     $result .= "</select></td></tr></table>";
 3106:     return $result;
 3107: }
 3108: 
 3109: sub postprocess {
 3110:     my $self = shift;
 3111: 
 3112:     my $var = $self->{'variable'};
 3113:     my $helper = Apache::lonhelper->getHelper();
 3114:     $helper->{VARS}->{$var} = 
 3115:         $env{"form.$var.layout"} . '|' . $env{"form.$var.cols"} . '|' .
 3116:         $env{"form.$var.paper"};
 3117:     return 1;
 3118: }
 3119: 
 3120: 1;
 3121: 
 3122: package Apache::lonprintout::page_size_state;
 3123: 
 3124: =pod
 3125: 
 3126: =head1 Helper element: page_size_state
 3127: 
 3128: See lonhelper.pm documentation for discussion of the helper framework.
 3129: 
 3130: Apache::lonprintout::page_size_state is an element that gives the 
 3131: user the opportunity to further refine the page settings if they
 3132: select a single-column page.
 3133: 
 3134: page_size_state is always directly invoked in lonprintout.pm, so there
 3135: is no tag interface. You actually pass parameters to the constructor.
 3136: 
 3137: =over 4
 3138: 
 3139: =item * B<new>(varName): varName is where the print information will be stored in the format FIXME.
 3140: 
 3141: =back
 3142: 
 3143: =cut
 3144: 
 3145: use Apache::lonhelper;
 3146: use Apache::lonnet;
 3147: no strict;
 3148: @ISA = ("Apache::lonhelper::element");
 3149: use strict;
 3150: 
 3151: 
 3152: 
 3153: sub new { 
 3154:     my $self = Apache::lonhelper::element->new();
 3155: 
 3156:     shift; # disturbs me (probably prevents subclassing) but works (drops
 3157:            # package descriptor)... - Jeremy
 3158: 
 3159:     $self->{'variable'} = shift;
 3160:     my $helper = Apache::lonhelper::getHelper();
 3161:     $helper->declareVar($self->{'variable'});
 3162: 
 3163:     # The variable name of the format element, so we can look into 
 3164:     # $helper->{VARS} to figure out whether the columns are one or two
 3165:     $self->{'formatvar'} = shift;
 3166: 
 3167: 
 3168:     $self->{NEXTSTATE} = shift;
 3169:     bless($self);
 3170: 
 3171:     return $self;
 3172: }
 3173: 
 3174: sub render {
 3175:     my $self = shift;
 3176:     my $helper = Apache::lonhelper::getHelper();
 3177:     my $result = '';
 3178:     my $var = $self->{'variable'};
 3179: 
 3180: 
 3181: 
 3182:     if (defined $self->{ERROR_MSG}) {
 3183:         $result .= '<br /><span class="LC_error">' . $self->{ERROR_MSG} . '</span><br />';
 3184:     }
 3185: 
 3186:     my $format = $helper->{VARS}->{$self->{'formatvar'}};
 3187: 
 3188:     # Use format to get sensible defaults for the margins:
 3189: 
 3190: 
 3191:     my ($laystyle, $cols, $papersize) = split(/\|/, $format);
 3192:     ($papersize)                      = split(/ /, $papersize);
 3193: 
 3194: 
 3195:     if ($laystyle eq 'L') {
 3196: 	$laystyle = 'album';
 3197:     } else {
 3198: 	$laystyle = 'book';
 3199:     }
 3200: 
 3201: 
 3202:     my %size;
 3203:     ($size{'width_and_units'},
 3204:      $size{'height_and_units'},
 3205:      $size{'margin_and_units'})=
 3206: 	 &Apache::lonprintout::page_format($papersize, $laystyle, $cols);
 3207:     
 3208:     foreach my $dimension ('width','height','margin') {
 3209: 	($size{$dimension},$size{$dimension.'_unit'}) =
 3210: 	    split(/ +/, $size{$dimension.'_and_units'},2);
 3211:        	
 3212: 	foreach my $unit ('cm','in') {
 3213: 	    $size{$dimension.'_options'} .= '<option ';
 3214: 	    if ($size{$dimension.'_unit'} eq $unit) {
 3215: 		$size{$dimension.'_options'} .= 'selected="selected" ';
 3216: 	    }
 3217: 	    $size{$dimension.'_options'} .= '>'.$unit.'</option>';
 3218: 	}
 3219:     }
 3220: 
 3221:     # Adjust margin for LaTeX margin: .. requires units == cm or in.
 3222: 
 3223:     if ($size{'margin_unit'} eq 'in') {
 3224: 	$size{'margin'} += 1;
 3225:     }  else {
 3226: 	$size{'margin'} += 2.54;
 3227:     }
 3228:     $result .= <<ELEMENTHTML;
 3229: 
 3230:   
 3231: 
 3232: <p>How should each column be formatted?</p>
 3233: 
 3234: <table cellpadding='3'>
 3235:   <tr>
 3236:     <td align='right'><b>Width</b>:</td>
 3237:     <td align='left'><input type='text' name='$var.width' value="$size{'width'}" size='4' /></td>
 3238:     <td align='left'>
 3239:       <select name='$var.widthunit'>
 3240:       $size{'width_options'}
 3241:       </select>
 3242:     </td>
 3243:   </tr>
 3244:   <tr>
 3245:     <td align='right'><b>Height</b>:</td>
 3246:     <td align='left'><input type='text' name="$var.height" value="$size{'height'}" size='4' /></td>
 3247:     <td align='left'>
 3248:       <select name='$var.heightunit'>
 3249:       $size{'height_options'}
 3250:       </select>
 3251:     </td>
 3252:   </tr>
 3253:   <tr>
 3254:     <td align='right'><b>Left margin</b>:</td>
 3255:     <td align='left'><input type='text' name='$var.lmargin' value="$size{'margin'}" size='4' /></td>
 3256:     <td align='left'>
 3257:       <select name='$var.lmarginunit'>
 3258:       $size{'margin_options'}
 3259:       </select>
 3260:     </td>
 3261:   </tr>
 3262: </table>
 3263: 
 3264: <!--<p>Hint: Some instructors like to leave scratch space for the student by
 3265: making the width much smaller than the width of the page.</p>-->
 3266: 
 3267: ELEMENTHTML
 3268: 
 3269:     return $result;
 3270: }
 3271: 
 3272: 
 3273: sub preprocess {
 3274:     my $self = shift;
 3275:     my $helper = Apache::lonhelper::getHelper();
 3276: 
 3277:     my $format = $helper->{VARS}->{$self->{'formatvar'}};
 3278: 
 3279:     #  If the user does not have 'pav' privilege, set default widths and
 3280:     #  on to the next state right away.
 3281:     #
 3282:     if (!$perm{'pav'}) {
 3283: 	my $var = $self->{'variable'};
 3284: 	my $format = $helper->{VARS}->{$self->{'formatvar'}};
 3285: 	
 3286: 	my ($laystyle, $cols, $papersize) = split(/\|/, $format);
 3287: 	($papersize)                      = split(/ /, $papersize);
 3288: 	
 3289: 	
 3290: 	if ($laystyle eq 'L') {
 3291: 	    $laystyle = 'album';
 3292: 	} else {
 3293: 	    $laystyle = 'book';
 3294: 	}
 3295: 	#  Figure out some good defaults for the print out and set them:
 3296: 	
 3297: 	my %size;
 3298: 	($size{'width'},
 3299: 	 $size{'height'},
 3300: 	 $size{'lmargin'})=
 3301: 	     &Apache::lonprintout::page_format($papersize, $laystyle, $cols);
 3302: 	
 3303: 	foreach my $dim ('width', 'height', 'lmargin') {
 3304: 	    my ($value, $units) = split(/ /, $size{$dim});
 3305: 	    	    
 3306: 	    $helper->{VARS}->{"$var.".$dim}      = $value;
 3307: 	    $helper->{VARS}->{"$var.".$dim.'unit'} = $units;
 3308: 	    
 3309: 	}
 3310: 	
 3311: 
 3312: 	# Transition to the next state
 3313: 
 3314: 	$helper->changeState($self->{NEXTSTATE});
 3315:     }
 3316:    
 3317:     return 1;
 3318: }
 3319: 
 3320: sub postprocess {
 3321:     my $self = shift;
 3322: 
 3323:     my $var = $self->{'variable'};
 3324:     my $helper = Apache::lonhelper->getHelper();
 3325:     my $width = $helper->{VARS}->{$var .'.width'} = $env{"form.${var}.width"}; 
 3326:     my $height = $helper->{VARS}->{$var .'.height'} = $env{"form.${var}.height"}; 
 3327:     my $lmargin = $helper->{VARS}->{$var .'.lmargin'} = $env{"form.${var}.lmargin"}; 
 3328:     $helper->{VARS}->{$var .'.widthunit'} = $env{"form.${var}.widthunit"}; 
 3329:     $helper->{VARS}->{$var .'.heightunit'} = $env{"form.${var}.heightunit"}; 
 3330:     $helper->{VARS}->{$var .'.lmarginunit'} = $env{"form.${var}.lmarginunit"}; 
 3331: 
 3332:     my $error = '';
 3333: 
 3334:     # /^-?[0-9]+(\.[0-9]*)?$/ -> optional minus, at least on digit, followed 
 3335:     # by an optional period, followed by digits, ending the string
 3336: 
 3337:     if ($width !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 3338:         $error .= "Invalid width; please type only a number.<br />\n";
 3339:     }
 3340:     if ($height !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 3341:         $error .= "Invalid height; please type only a number.<br />\n";
 3342:     }
 3343:     if ($lmargin !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 3344:         $error .= "Invalid left margin; please type only a number.<br />\n";
 3345:     } else {
 3346: 	# Adjust for LaTeX 1.0 inch margin:
 3347: 
 3348: 	if ($env{"form.${var}.lmarginunit"} eq "in") {
 3349: 	    $helper->{VARS}->{$var.'.lmargin'} = $lmargin - 1;
 3350: 	} else {
 3351: 	    $helper->{VARS}->{$var.'.lmargin'} = $lmargin - 2.54;
 3352: 	}
 3353:     }
 3354: 
 3355:     if (!$error) {
 3356:         Apache::lonhelper::getHelper()->changeState($self->{NEXTSTATE});
 3357:         return 1;
 3358:     } else {
 3359:         $self->{ERROR_MSG} = $error;
 3360:         return 0;
 3361:     }
 3362: }
 3363: 
 3364: 
 3365: 
 3366: __END__
 3367: 

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