File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.428: download - view: text, annotated - select for diffs
Wed Mar 8 22:32:11 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- use the new form.counter helpers

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

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