File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.383: download - view: text, annotated - select for diffs
Mon Aug 15 22:39:43 2005 UTC (18 years, 9 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add validation for user typed codes (support is still latent).

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

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