File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.459: download - view: text, annotated - select for diffs
Mon Jul 17 09:38:09 2006 UTC (17 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Defect 4374 - subsequences of sequences don't print... fixed for
the construction space case.  Other casees alread fixed back in 1.434

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

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