File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.485: download - view: text, annotated - select for diffs
Tue Oct 10 02:18:50 2006 UTC (17 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#5045

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

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