File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.455: download - view: text, annotated - select for diffs
Mon Jul 3 13:48:41 2006 UTC (17 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- style police

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

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