File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.384: download - view: text, annotated - select for diffs
Tue Aug 16 03:34:34 2005 UTC (18 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- it's not a max it's an exact amount required

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

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