File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.490: download - view: text, annotated - select for diffs
Tue Oct 24 10:37:58 2006 UTC (17 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Think that this now does title substitution correctly in all cases..or
at least won't cause failures:
- Use format string chopping to do multiple substitutions since I'm not
  smart enoug to get \G to work the way I want.
- deal with a nasty edge case.. where the substitution string was trimeed
  in the middle of a LaTeX escaped character sequence (e.g. after \ in \%).

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

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