File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.489: download - view: text, annotated - select for diffs
Mon Oct 23 10:40:09 2006 UTC (17 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Prior change seemed not to be able to substitute for all
the actual %letter strings in  a format string like e.g.:
Name: %10n \\ Sequence: %10c  \\ Resource: %10a Done
leaving % format strings hanging.  The correct thing
to do is to do all the format replacements and >then<
go back and escape any remaining %'s the user may have
pathalogically left in the format string.  The
current version has been tested on a nasty format
string that looks like:
Name: %10n \\ Sequence: %10c  \\ Resource: %10a Done % 10% done %10  %b done
and not only does not loop, but produces LaTeX output that can print.

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

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