File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.480: download - view: text, annotated - select for diffs
Mon Aug 21 22:53:19 2006 UTC (17 years, 9 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Support printing a directory of resource space.. need work now back on
directory of course.

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

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