File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.496: download - view: text, annotated - select for diffs
Mon Jan 22 10:38:32 2007 UTC (17 years, 4 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Fix some serious measurement typos and calcos.

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

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