File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.564: download - view: text, annotated - select for diffs
Mon Nov 16 11:13:24 2009 UTC (14 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Fix last? slip up with .page printing.

    1: #
    2: # The LearningOnline Network
    3: # Printout
    4: #
    5: # $Id: lonprintout.pm,v 1.564 2009/11/16 11:13:24 foxr Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: package Apache::lonprintout;
   30: use strict;
   31: use Apache::Constants qw(:common :http);
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::inputtags;
   36: use Apache::grades;
   37: use Apache::edit;
   38: use Apache::File();
   39: use Apache::lonnavmaps;
   40: use Apache::admannotations;
   41: use Apache::lonenc;
   42: use Apache::entities;
   43: use Apache::londefdef;
   44: 
   45: use File::Basename;
   46: 
   47: use HTTP::Response;
   48: 
   49: use LONCAPA::map();
   50: use POSIX qw(strftime);
   51: use Apache::lonlocal;
   52: use Carp;
   53: use LONCAPA;
   54: 
   55: my %perm;
   56: my %parmhash;
   57: my $resources_printed;
   58: 
   59: # Global variables that describe errors in ssi calls detected  by ssi_with_retries.
   60: #
   61: 
   62: my $ssi_error;			# True if there was an ssi error.
   63: my $ssi_last_error_resource;	# The resource URI that could not be fetched.
   64: my $ssi_last_error;		# The error text from the server. (e.g. 500 Server timed out).
   65: 
   66: #
   67: #  Our ssi max retry count.
   68: #
   69: 
   70: my $ssi_retry_count = 5;	# Some arbitrary value.
   71: 
   72: 
   73: #  Font size:
   74: 
   75: my $font_size = 'normalsize';	# Default is normalsize...
   76: 
   77: #----------------------------  Helper helpers. -------------------------
   78: 
   79: #  Returns the text needd for a student chooser.
   80: #  that text must still be parsed by the helper xml parser.
   81: # Parameters:
   82: #   this_state   - State name of the chooser.
   83: #   sort_choice  - variable to hold the sorting choice.
   84: #   variable     - Name of variable to hold students.
   85: #   next_state   - State after chooser.
   86: 
   87: 
   88: sub generate_student_chooser {
   89:     my ($this_state, 
   90: 	$sort_choice, 
   91: 	$variable, 
   92: 	$next_state) = @_;
   93:     my $result = <<CHOOSE_STUDENTS;
   94:   <state name="$this_state" title="Select Students and Resources">
   95:       <message><b>Select sorting order of printout</b> </message>
   96: 
   97:     <choices variable="$sort_choice">
   98:       <choice computer='0'>Sort by section then student</choice>
   99:       <choice computer='1'>Sort by students across sections.</choice>
  100:     </choices>
  101: 
  102:       <message><br /><hr /><br /> </message>
  103:       <student multichoice='1' 
  104:                variable="$variable" 
  105:                nextstate="$next_state" 
  106:                coursepersonnel="1" />
  107:   </state>
  108: 
  109: CHOOSE_STUDENTS
  110: 
  111:   return $result;
  112: }
  113: 
  114: # Generate the text needed for a resource chooser given the top level of
  115: # the sequence/page
  116: #
  117: # Parameters:
  118: #     this_state    - State name of the chooser.
  119: #     prompt_text   - Text to use to prompt user.
  120: #     resource_options - Resource tag options e.g.
  121: #                        "multichoice='1', toponly='1', addstatus='1'"
  122: #                     that control the selection and appearance of the
  123: #                     resource selector.
  124: #     variable      - Name of the variable to hold the choice
  125: #     next_state    - Name of the next state the helper should transition
  126: #                     to
  127: #     top_url       - Top level URL within which to make the selector.
  128: #                     If empty the top level sequence is shown.
  129: #     filter        - How to filter the resources.
  130: #     value_func    - <valuefunc> function.
  131: #     choice_func   - If not empty generates a <choicefunc> with this function.
  132: #     start_new_option 
  133: #                   - Fragment appended after valuefunc.
  134: #
  135: #
  136: sub generate_resource_chooser {
  137:     my ($this_state,
  138: 	$prompt_text,
  139: 	$resource_options,
  140: 	$variable,
  141: 	$next_state,
  142: 	$top_url,
  143: 	$filter,
  144: 	$choice_func,
  145: 	$value_func,
  146: 	$start_new_option)  = @_;
  147: 
  148:     my $result = <<CHOOSE_RESOURCES;
  149: <state name="$this_state" title="$prompt_text">
  150:     <resource variable="$variable" $resource_options
  151:               closeallpages="1">
  152:       <nextstate>$next_state</nextstate>
  153:       <filterfunc>return $filter;</filterfunc>
  154: CHOOSE_RESOURCES
  155:     if ($choice_func ne '') {
  156: 	$result .= "<choicefunc>return $choice_func;</choicefunc>";
  157:     }
  158:     if ($top_url ne '') {
  159: 	$result .=  "<mapurl>$top_url</mapurl>";
  160:     }
  161:     $result .= <<CHOOSE_RESOURCES;
  162:       <valuefunc>return $value_func;</valuefunc>
  163:       $start_new_option
  164:       </resource>
  165:     </state>
  166: CHOOSE_RESOURCES
  167: 
  168:     return $result;
  169: }
  170: #
  171: #   Generate the helper XML for a code choice helper dialog:
  172: #
  173: # Paramters:
  174: #   $helper       - Reference to the helper.
  175: #   $state        - Name of the state for the chooser.
  176: #   $next_state   - Name fo the state to follow the chooser.
  177: #   $bubble_types - Populates the bubble sheet type dropt down.
  178: #   $code_selections - Provides set of code choices that have been used
  179: #   $saved_codes  - Provides the list of saved codes.
  180: #
  181: # Returns;
  182: #   The Xml of the code chooser.
  183: #
  184: sub generate_code_selector {
  185:     my ($helper,
  186: 	$state,
  187: 	$next_state,
  188: 	$bubble_types,
  189: 	$code_selections,
  190: 	$saved_codes) = @_;	# Unpack the parameters.
  191: 
  192:     my $result = <<CHOOSE_ANON1;
  193:   <state name="$state" title="Specify CODEd Assignments">
  194:     <nextstate>$next_state</nextstate>
  195:     <message><h4>Fill out one of the forms below</h4></message>
  196:     <message><br /><hr /> <br /></message>
  197:     <message><h3>Generate new CODEd Assignments</h3></message>
  198:     <message><table><tr><td><b>Number of CODEd assignments to print:</b></td><td></message>
  199:     <string variable="NUMBER_TO_PRINT_TOTAL" maxlength="5" size="5">
  200:        <validator>
  201: 	if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) < 1) &&
  202: 	    !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                &&
  203:             !\$helper->{'VARS'}{'SINGLE_CODE'}                    &&
  204: 	    !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
  205: 	    return "You need to specify the number of assignments to print";
  206: 	}
  207: 	return undef;
  208:        </validator>
  209:     </string>
  210:     <message></td></tr><tr><td></message>
  211:     <message><b>Names to save the CODEs under for later:</b></message>
  212:     <message></td><td></message>
  213:     <string variable="ANON_CODE_STORAGE_NAME" maxlength="50" size="20" />
  214:     <message></td></tr><tr><td></message>
  215:     <message><b>Bubble sheet type:</b></message>
  216:     <message></td><td></message>
  217:     <dropdown variable="CODE_OPTION" multichoice="0" allowempty="0">
  218:     $bubble_types
  219:     </dropdown>
  220:     <message></td></tr><tr><td colspan="2"></td></tr><tr><td></message>
  221:     <message></td></tr><tr><td></table></message>
  222:     <message><br /><hr /><h3>Print a Specific CODE </h3><br /><table></message>
  223:     <message><tr><td><b>Enter a CODE to print:</b></td><td></message>
  224:     <string variable="SINGLE_CODE" size="10">
  225:         <validator>
  226: 	   if(!\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}           &&
  227: 	      !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                 &&
  228: 	      !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
  229: 	      return &Apache::lonprintout::is_code_valid(\$helper->{'VARS'}{'SINGLE_CODE'},
  230: 						      \$helper->{'VARS'}{'CODE_OPTION'});
  231: 	   } else {
  232: 	       return undef;	# Other forces control us.
  233: 	   }
  234:         </validator>
  235:     </string>
  236:     <message></td></tr><tr><td></message>
  237:         $code_selections
  238:     <message></td></tr></table></message>
  239:     <message><hr /><h3>Reprint a Set of Saved CODEs</h3><table><tr><td></message>
  240:     <message><b>Select saved CODEs:</b></message>
  241:     <message></td><td></message>
  242:     <dropdown variable="REUSE_OLD_CODES">
  243:         $saved_codes
  244:     </dropdown>
  245:     <message></td></tr></table></message>
  246:   </state>
  247: CHOOSE_ANON1
  248: 
  249:    return $result;
  250: }
  251: 
  252: #-----------------------------------------------------------------------
  253: 
  254: 
  255: # Fetch the contents of a resource, uninterpreted.
  256: # This is used here to fetch a latex file to be included
  257: # verbatim into the printout<
  258: # NOTE: Ask Guy if there is a lonnet function similar to this?
  259: #
  260: # Parameters:
  261: #   URL of the file
  262: #
  263: sub fetch_raw_resource {
  264:     my ($url) = @_;
  265: 
  266:     my $filename  = &Apache::lonnet::filelocation("", $url);
  267:     my $contents  = &Apache::lonnet::getfile($filename);
  268: 
  269:     if ($contents == -1) {
  270: 	return "File open failed for $filename";      # This will bomb the print.
  271:     }
  272:     return $contents;
  273: 
  274:     
  275: }
  276: 
  277: #  Fetch the annotations associated with a URL and 
  278: #  put a centered 'annotations:' title.
  279: #  This is all suppressed if the annotations are empty.
  280: #
  281: sub annotate {
  282:     my ($symb) = @_;
  283: 
  284:     my $annotation_text = &Apache::loncommon::get_annotation($symb, 1);
  285: 
  286: 
  287:     my $result = "";
  288: 
  289:     if (length($annotation_text) > 0) {
  290: 	$result .= '\\hspace*{\\fill} \\\\[\\baselineskip] \textbf{Annotations:} \\\\ ';
  291: 	$result .= "\n";
  292: 	$result .= &Apache::lonxml::latex_special_symbols($annotation_text,"");	# Escape latex.
  293: 	$result .= "\n\n";
  294:     }
  295:     return $result;
  296: }
  297: 
  298: #
  299: #   Set a global document font size:
  300: #   This is done by replacing \begin{document}
  301: #   with \begin{document}{\some-font-directive
  302: #   and \end{document} with
  303: #   }\end{document
  304: #
  305: sub set_font_size {
  306: 
  307:     my ($text) = @_;
  308: 
  309:     $text =~ s/\\begin{document}/\\begin{document}{\\$font_size/;
  310:     $text =~ s/\\end{document}/}\\end{document}/;
  311:     return $text;
  312: 
  313: 
  314: }
  315: 
  316: # include_pdf - PDF files are included into the 
  317: # output as follows:
  318: #  - The PDF, if necessary, is replicated.
  319: #  - The PDF is added to the list of files to convert to postscript (along with the images).
  320: #  - The LaTeX is added to include the final converted postscript in the file as an included
  321: #    job.  The assumption is that the includedpsheader.ps header will be included.
  322: #
  323: # Parameters:
  324: #   pdf_uri   - URI of the PDF file to include.
  325: #   
  326: # Returns:
  327: #  The LaTeX to include.
  328: #
  329: # Assumptions:
  330: #    The uri is actually a PDF file
  331: #    The postscript will have the includepsheader.ps included.
  332: #
  333: #
  334: sub include_pdf {
  335:     my ($pdf_uri) = @_;
  336: 
  337:     # Where is the file? If not local we'll need to repcopy it:'
  338: 
  339:     my $file = &Apache::lonnet::filelocation('', $pdf_uri);
  340:     if (! -e $file) {
  341: 	&Apache::lonnet::repcopy($file);
  342: 	$file = &Apache::lonnet::filelocation('',$pdf_uri);
  343:     }
  344: 
  345:     #  The file isn ow replicated locally.. or it did not exist in the first place
  346:     # (unlikely).  If it did exist, add the pdf to the set of files/images that
  347:     # need tob e converted for this print job:
  348: 
  349:     $file =~ s|(.*)/res/|/home/httpd/html/res/|;
  350: 
  351:     open(FILE,">>/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.dat");
  352:     print FILE ("$file\n");
  353:     close (FILE);
  354: 
  355:     # Construct the special to put out.  To do this we need to get the
  356:     # resulting filename after conversion.  The file will have the same name
  357:     # but will be in the user's spool directory with converted images.
  358: 
  359:     my $dirname = "/home/httpd/prtspool/$env{'user.name'}/";
  360:     my ( $base, $path,  $ext) = &fileparse($file, '.pdf');
  361: #    my $destname = $dirname.'/'.$base.'.eps'; # Not really an eps but easier in printout.pl
  362:     $base =~ s/ /\_/g;
  363: 
  364: 
  365:     my $output = &print_latex_header();
  366:     $output    .= '\special{ps: _begin_job_ ('
  367: 	.$base.'.pdf.eps'.
  368: 	')run _end_job_}';
  369: 
  370:     return $output;
  371: 
  372: 
  373: }
  374: 
  375: 
  376: #
  377: #   ssi_with_retries- Does the server side include of a resource.
  378: #                      if the ssi call returns an error we'll retry it up to
  379: #                      the number of times requested by the caller.
  380: #                      If we still have a proble, no text is appended to the
  381: #                      output and we set some global variables.
  382: #                      to indicate to the caller an SSI error occurred.  
  383: #                      All of this is supposed to deal with the issues described
  384: #                      in LonCAPA BZ 5631 see:
  385: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
  386: #                      by informing the user that this happened.
  387: #
  388: # Parameters:
  389: #   resource   - The resource to include.  This is passed directly, without
  390: #                interpretation to lonnet::ssi.
  391: #   form       - The form hash parameters that guide the interpretation of the resource
  392: #                
  393: #   retries    - Number of retries allowed before giving up completely.
  394: # Returns:
  395: #   On success, returns the rendered resource identified by the resource parameter.
  396: # Side Effects:
  397: #   The following global variables can be set:
  398: #    ssi_error                - If an unrecoverable error occurred this becomes true.
  399: #                               It is up to the caller to initialize this to false
  400: #                               if desired.
  401: #    ssi_last_error_resource  - If an unrecoverable error occurred, this is the value
  402: #                               of the resource that could not be rendered by the ssi
  403: #                               call.
  404: #    ssi_last_error           - The error string fetched from the ssi response
  405: #                               in the event of an error.
  406: #
  407: sub ssi_with_retries {
  408:     my ($resource, $retries, %form) = @_;
  409: 
  410:     my $target = $form{'grade_target'};
  411:     my $aom    = $form{'answer_output_mode'};
  412: 
  413: 
  414: 
  415:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
  416:     if (!$response->is_success) {
  417: 	$ssi_error               = 1;
  418: 	$ssi_last_error_resource = $resource;
  419: 	$ssi_last_error          = $response->code . " " . $response->message;
  420:         $content='\section*{!!! An error occurred !!!}';	
  421: 	&Apache::lonnet::logthis("Error in SSI resource: $resource Error: $ssi_last_error");
  422:     }
  423: 
  424:     return $content;
  425: 
  426: }
  427: 
  428: sub get_student_view_with_retries {
  429:     my ($curresline,$retries,$username,$userdomain,$courseid,$target,$moreenv)=@_;
  430: 
  431:     my ($content, $response) = &Apache::loncommon::get_student_view_with_retries($curresline,$retries,$username,$userdomain,$courseid,$target,$moreenv);
  432:     if (!$response->is_success) {
  433:         $ssi_error               = 1;
  434:         $ssi_last_error_resource = $curresline.' for user '.$username.':'.$userdomain;
  435:         $ssi_last_error          = $response->code . " " . $response->message;
  436:         $content='\section*{!!! An error occurred !!!}';
  437:         &Apache::lonnet::logthis("Error in SSI (student view) resource: $curresline Error: $ssi_last_error User: $username:$userdomain");
  438:     }
  439:     return $content;
  440: 
  441: }
  442: 
  443: #
  444: #   printf_style_subst  item format_string repl
  445: #  
  446: # Does printf style substitution for a format string that
  447: # can have %[n]item in it.. wherever, %[n]item occurs,
  448: # rep is substituted in format_string.  Note that
  449: # [n] is an optional integer length.  If provided,
  450: # repl is truncated to at most [n] characters prior to 
  451: # substitution.
  452: #
  453: sub printf_style_subst {
  454:     my ($item, $format_string, $repl) = @_;
  455:     my $result = "";
  456:     while ($format_string =~ /(%)(\d*)\Q$item\E/g ) {
  457: 	my $fmt = $1;
  458: 	my $size = $2;
  459: 	my $subst = $repl;
  460: 	if ($size ne "") {
  461: 	    $subst = substr($subst, 0, $size);
  462: 	    
  463: 	    #  Here's a nice edge case.. supose the end of the
  464: 	    #  substring is a \.  In that case may have  just
  465: 	    #  chopped off a TeX escape... in that case, we append
  466: 	    #   " " for the trailing character, and let the field 
  467: 	    #  spill over a bit (sigh).
  468: 	    #  We don't just chop off the last character in order to deal
  469: 	    #  with one last pathology, and that would be if substr had
  470: 	    #  trimmed us to e.g. \\\  
  471: 
  472: 
  473: 	    if ($subst =~ /\\$/) {
  474: 		$subst .= " ";
  475: 	    }
  476: 	}
  477: 	my $item_pos = pos($format_string);
  478: 	$result .= substr($format_string, 0, $item_pos - length($size) -2) . $subst;
  479:         $format_string = substr($format_string, pos($format_string));
  480:     }
  481: 
  482:     # Put the residual format string into the result:
  483: 
  484:     $result .= $format_string;
  485: 
  486:     return $result;
  487: }
  488: 
  489: 
  490: # Format a header according to a format.  
  491: # 
  492: 
  493: # Substitutions:
  494: #     %a    - Assignment name.
  495: #     %c    - Course name.
  496: #     %n    - Student name.
  497: #     %s    - The section if it is supplied.
  498: #
  499: sub format_page_header {
  500:     my ($width, $format, $assignment, $course, $student, $section) = @_;
  501: 
  502:     
  503:     $width = &recalcto_mm($width); # Get width in mm.
  504:     #  Default format?
  505: 
  506:     if ($format eq '') {
  507: 	# For the default format, we may need to truncate
  508: 	# elements..  To do this we need to get the page width.
  509: 	# we assume that each character is about 2mm in width.
  510: 	# (correct for the header text size??).  We ignore
  511: 	# any formatting (e.g. boldfacing in this).
  512: 	# 
  513: 	# - Allow the student/course to be one line.
  514: 	#   but only truncate the course.
  515: 	# - Allow the assignment to be 2 lines (wrapped).
  516: 	#
  517: 	my $chars_per_line = $width/2; # Character/textline.
  518: 	
  519: 
  520: 
  521: 	my $name_length    = int($chars_per_line *3 /4);
  522: 	my $sec_length     = int($chars_per_line / 5);
  523: 
  524: 	$format  = "%$name_length".'n';
  525: 
  526: 	if ($section) {
  527: 	    $format .=  ' - Sec: '."%$sec_length".'s';
  528: 	}
  529: 
  530: 	$format .= '\\\\%c \\\\ %a';
  531:         
  532: 
  533:     }
  534:     # An open question is how to handle long user formatted page headers...
  535:     # A possible future is to support e.g. %na so that the user can control
  536:     # the truncation of the elements that can appear in the header.
  537:     #
  538:     $format =  &printf_style_subst("a", $format, $assignment);
  539:     $format =  &printf_style_subst("c", $format, $course);
  540:     $format =  &printf_style_subst("n", $format, $student);
  541:     $format =  &printf_style_subst("s", $format, $section);
  542:     
  543:     
  544:     # If the user put %'s in the format string, they  must be escaped
  545:     # to \% else LaTeX will think they are comments and terminate
  546:     # the line.. which is bad!!!
  547:     
  548:     # If the user has role author, $course and $assignment are empty so
  549:     # there is '\\ \\ ' in the page header. That's cause a error in LaTeX
  550:     if($format =~ /\\\\\s\\\\\s/) {
  551:         #TODO find sensible caption for page header
  552:         my $testPrintout = '\\\\'.&mt('Construction Space').' \\\\'.&mt('Test-Printout ');
  553:         $format =~ s/\\\\\s\\\\\s/$testPrintout/;
  554:     }
  555:     
  556: 
  557:     return $format;
  558:     
  559: }
  560: 
  561: #
  562: #   Convert a numeric code to letters
  563: #
  564: sub num_to_letters {
  565:     my ($num) = @_;
  566:     my @nums= split('',$num);
  567:     my @num_to_let=('A'..'Z');
  568:     my $word;
  569:     foreach my $digit (@nums) { $word.=$num_to_let[$digit]; }
  570:     return $word;
  571: }
  572: #   Convert a letter code to numeric.
  573: #
  574: sub letters_to_num {
  575:     my ($letters) = @_;
  576:     my @letters = split('', uc($letters));
  577:    my %substitution;
  578:     my $digit = 0;
  579:     foreach my $letter ('A'..'J') {
  580: 	$substitution{$letter} = $digit;
  581: 	$digit++;
  582:     }
  583:     #  The substitution is done as below to preserve leading
  584:     #  zeroes which are needed to keep the code size exact
  585:     #
  586:     my $result ="";
  587:     foreach my $letter (@letters) {
  588: 	$result.=$substitution{$letter};
  589:     }
  590:     return $result;
  591: }
  592: 
  593: #  Determine if a code is a valid numeric code.  Valid
  594: #  numeric codes must be comprised entirely of digits and
  595: #  have a correct number of digits.
  596: #
  597: #  Parameters:
  598: #     value      - proposed code value.
  599: #     num_digits - Number of digits required.
  600: #
  601: sub is_valid_numeric_code {
  602:     my ($value, $num_digits) = @_;
  603:     #   Remove leading/trailing whitespace;
  604:     $value =~ s/^\s*//g;
  605:     $value =~ s/\s*$//g;
  606:     
  607:     #  All digits?
  608:     if ($value !~ /^[0-9]+$/) {
  609: 	return "Numeric code $value has invalid characters - must only be digits";
  610:     }
  611:     if (length($value) != $num_digits) {
  612: 	return "Numeric code $value incorrect number of digits (correct = $num_digits)";
  613:     }
  614:     return undef;
  615: }
  616: #   Determines if a code is a valid alhpa code.  Alpha codes
  617: #   are ciphers that map  [A-J,a-j] -> 0..9 0..9.
  618: #   They also have a correct digit count.
  619: # Parameters:
  620: #     value          - Proposed code value.
  621: #     num_letters    - correct number of letters.
  622: # Note:
  623: #    leading and trailing whitespace are ignored.
  624: #
  625: sub is_valid_alpha_code {
  626:     my ($value, $num_letters) = @_;
  627:     
  628:      # strip leading and trailing spaces.
  629: 
  630:     $value =~ s/^\s*//g;
  631:     $value =~ s/\s*$//g;
  632: 
  633:     #  All alphas in the right range?
  634:     if ($value !~ /^[A-J,a-j]+$/) {
  635: 	return "Invalid letter code $value must only contain A-J";
  636:     }
  637:     if (length($value) != $num_letters) {
  638: 	return "Letter code $value has incorrect number of letters (correct = $num_letters)";
  639:     }
  640:     return undef;
  641: }
  642: 
  643: #   Determine if a code entered by the user in a helper is valid.
  644: #   valid depends on the code type and the type of code selected.
  645: #   The type of code selected can either be numeric or 
  646: #   Alphabetic.  If alphabetic, the code, in fact is a simple
  647: #   substitution cipher for the actual numeric code: 0->A, 1->B ...
  648: #   We'll be nice and be case insensitive for alpha codes.
  649: # Parameters:
  650: #    code_value    - the value of the code the user typed in.
  651: #    code_option   - The code type selected from the set in the scantron format
  652: #                    table.
  653: # Returns:
  654: #    undef         - The code is valid.
  655: #    other         - An error message indicating what's wrong.
  656: #
  657: sub is_code_valid {
  658:     my ($code_value, $code_option) = @_;
  659:     my ($code_type, $code_length) = ('letter', 6);	# defaults.
  660:     my @lines = &Apache::grades::get_scantronformat_file();
  661:     foreach my $line (@lines) {
  662: 	my ($name, $type, $length) = (split(/:/, $line))[0,2,4];
  663: 	if($name eq $code_option) {
  664: 	    $code_length = $length;
  665: 	    if($type eq 'number') {
  666: 		$code_type = 'number';
  667: 	    }
  668: 	}
  669:     }
  670:     my $valid;
  671:     if ($code_type eq 'number') {
  672: 	return &is_valid_numeric_code($code_value, $code_length);
  673:     } else {
  674: 	return &is_valid_alpha_code($code_value, $code_length);
  675:     }
  676: 
  677: }
  678: 
  679: #   Compare two students by name.  The students are in the form
  680: #   returned by the helper:
  681: #      user:domain:section:last,   first:status
  682: #   This is a helper function for the perl sort built-in  therefore:
  683: # Implicit Inputs:
  684: #    $a     - The first element to compare (global)
  685: #    $b     - The second element to compare (global)
  686: # Returns:
  687: #   -1   - $a < $b
  688: #    0   - $a == $b
  689: #   +1   - $a > $b
  690: #   Note that the initial comparison is done on the last names with the
  691: #   first names only used to break the tie.
  692: #
  693: #
  694: sub compare_names {
  695:     #  First split the names up into the primary fields.
  696: 
  697:     my ($u1, $d1, $s1, $n1, $stat1) = split(/:/, $a);
  698:     my ($u2, $d2, $s2, $n2, $stat2) = split(/:/, $b);
  699: 
  700:     # Now split the last name and first name of each n:
  701:     #
  702: 
  703:     my ($l1,$f1) = split(/,/, $n1);
  704:     my ($l2,$f2) = split(/,/, $n2);
  705: 
  706:     # We don't bother to remove the leading/trailing whitespace from the
  707:     # firstname, unless the last names compare identical.
  708: 
  709:     if($l1 lt $l2) {
  710: 	return -1;
  711:     }
  712:     if($l1 gt $l2) {
  713: 	return  1;
  714:     }
  715: 
  716:     # Break the tie on the first name, but there are leading (possibly trailing
  717:     # whitespaces to get rid of first 
  718:     #
  719:     $f1 =~ s/^\s+//;		# Remove leading...
  720:     $f1 =~ s/\s+$//;		# Trailing spaces from first 1...
  721:     
  722:     $f2 =~ s/^\s+//;
  723:     $f2 =~ s/\s+$//;		# And the same for first 2...
  724: 
  725:     if($f1 lt $f2) {
  726: 	return -1;
  727:     }
  728:     if($f1 gt $f2) {
  729: 	return 1;
  730:     }
  731:     
  732:     #  Must be the same name.
  733: 
  734:     return 0;
  735: }
  736: 
  737: sub latex_header_footer_remove {
  738:     my $text = shift;
  739:     $text =~ s/\\end{document}//;
  740:     $text =~ s/\\documentclass([^&]*)\\begin{document}//;
  741:     return $text;
  742: }
  743: #
  744: #  If necessary, encapsulate text inside 
  745: #  a minipage env.
  746: #  necessity is determined by the problem_split param.
  747: #
  748: sub encapsulate_minipage {
  749:     my ($text) = @_;
  750:     if (!($env{'form.problem.split'} =~ /yes/i)) {
  751: 	$text = '\begin{minipage}{\textwidth}'.$text.'\end{minipage}';
  752:     }
  753:     return $text;
  754: }
  755: #
  756: #  The NUMBER_TO_PRINT and SPLIT_PDFS
  757: #  variables interact, this sub looks at these two parameters
  758: #  and comes up with a final value for NUMBER_TO_PRINT which can be:
  759: #     all     - if SPLIT_PDFS eq 'all'.
  760: #     1       - if SPLIT_PDFS eq 'oneper'
  761: #     section - if SPLIT_PDFS eq 'sections'
  762: #     <unchanged> - if SPLIT_PDFS eq 'usenumber'
  763: #
  764: sub adjust_number_to_print {
  765:     my $helper = shift;
  766: 
  767:     my $split_pdf = $helper->{'VARS'}->{'SPLIT_PDFS'};
  768:     
  769:     if ($split_pdf eq 'all') {
  770: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 'all';
  771:     } elsif ($split_pdf eq 'oneper') {
  772: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 1;
  773:     } elsif ($split_pdf eq 'sections') {
  774: 	$helper->{'VARS'}->{'NUMBER_TO_PRINT'} = 'section';
  775:     } elsif ($split_pdf eq 'usenumber') {
  776: 	#  Unmodified.
  777:     } else {
  778: 	# Error!!!!
  779: 	
  780: 	croak "bad SPLIT_PDFS: $split_pdf in lonprintout::adjust_number_to_print";
  781: 
  782:     }
  783: }
  784: 
  785: 
  786: sub character_chart {
  787:     my $result = shift;
  788:     return  &Apache::entities::replace_entities($result);
  789: }
  790: 
  791: sub old_character_chart {
  792:     my $result = shift;	
  793:     $result =~ s/&\#0?0?(7|9);//g;
  794:     $result =~ s/&\#0?(10|13);//g;
  795:     $result =~ s/&\#0?32;/ /g;
  796:     $result =~ s/&\#0?33;/!/g;
  797:     $result =~ s/&(\#0?34|quot);/\"/g;
  798:     $result =~ s/&\#0?35;/\\\#/g;
  799:     $result =~ s/&\#0?36;/\\\$/g;
  800:     $result =~ s/&\#0?37;/\\%/g; 
  801:     $result =~ s/&(\#0?38|amp);/\\&/g; 
  802:     $result =~ s/&\#(0?39|146);/\'/g;
  803:     $result =~ s/&\#0?40;/(/g;
  804:     $result =~ s/&\#0?41;/)/g;
  805:     $result =~ s/&\#0?42;/\*/g;
  806:     $result =~ s/&\#0?43;/\+/g;
  807:     $result =~ s/&\#(0?44|130);/,/g;
  808:     $result =~ s/&\#0?45;/-/g;
  809:     $result =~ s/&\#0?46;/\./g;
  810:     $result =~ s/&\#0?47;/\//g;
  811:     $result =~ s/&\#0?48;/0/g;
  812:     $result =~ s/&\#0?49;/1/g;
  813:     $result =~ s/&\#0?50;/2/g;
  814:     $result =~ s/&\#0?51;/3/g;
  815:     $result =~ s/&\#0?52;/4/g;
  816:     $result =~ s/&\#0?53;/5/g;
  817:     $result =~ s/&\#0?54;/6/g;
  818:     $result =~ s/&\#0?55;/7/g;
  819:     $result =~ s/&\#0?56;/8/g;
  820:     $result =~ s/&\#0?57;/9/g;
  821:     $result =~ s/&\#0?58;/:/g;
  822:     $result =~ s/&\#0?59;/;/g;
  823:     $result =~ s/&(\#0?60|lt|\#139);/\$<\$/g;
  824:     $result =~ s/&\#0?61;/\\ensuremath\{=\}/g;
  825:     $result =~ s/&(\#0?62|gt|\#155);/\\ensuremath\{>\}/g;
  826:     $result =~ s/&\#0?63;/\?/g;
  827:     $result =~ s/&\#0?65;/A/g;
  828:     $result =~ s/&\#0?66;/B/g;
  829:     $result =~ s/&\#0?67;/C/g;
  830:     $result =~ s/&\#0?68;/D/g;
  831:     $result =~ s/&\#0?69;/E/g;
  832:     $result =~ s/&\#0?70;/F/g;
  833:     $result =~ s/&\#0?71;/G/g;
  834:     $result =~ s/&\#0?72;/H/g;
  835:     $result =~ s/&\#0?73;/I/g;
  836:     $result =~ s/&\#0?74;/J/g;
  837:     $result =~ s/&\#0?75;/K/g;
  838:     $result =~ s/&\#0?76;/L/g;
  839:     $result =~ s/&\#0?77;/M/g;
  840:     $result =~ s/&\#0?78;/N/g;
  841:     $result =~ s/&\#0?79;/O/g;
  842:     $result =~ s/&\#0?80;/P/g;
  843:     $result =~ s/&\#0?81;/Q/g;
  844:     $result =~ s/&\#0?82;/R/g;
  845:     $result =~ s/&\#0?83;/S/g;
  846:     $result =~ s/&\#0?84;/T/g;
  847:     $result =~ s/&\#0?85;/U/g;
  848:     $result =~ s/&\#0?86;/V/g;
  849:     $result =~ s/&\#0?87;/W/g;
  850:     $result =~ s/&\#0?88;/X/g;
  851:     $result =~ s/&\#0?89;/Y/g;
  852:     $result =~ s/&\#0?90;/Z/g;
  853:     $result =~ s/&\#0?91;/[/g;
  854:     $result =~ s/&\#0?92;/\\ensuremath\{\\setminus\}/g;
  855:     $result =~ s/&\#0?93;/]/g;
  856:     $result =~ s/&\#(0?94|136);/\\ensuremath\{\\wedge\}/g;
  857:     $result =~ s/&\#(0?95|138|154);/\\underline{\\makebox[2mm]{\\strut}}/g;
  858:     $result =~ s/&\#(0?96|145);/\`/g;
  859:     $result =~ s/&\#0?97;/a/g;
  860:     $result =~ s/&\#0?98;/b/g;
  861:     $result =~ s/&\#0?99;/c/g;
  862:     $result =~ s/&\#100;/d/g;
  863:     $result =~ s/&\#101;/e/g;
  864:     $result =~ s/&\#102;/f/g;
  865:     $result =~ s/&\#103;/g/g;
  866:     $result =~ s/&\#104;/h/g;
  867:     $result =~ s/&\#105;/i/g;
  868:     $result =~ s/&\#106;/j/g;
  869:     $result =~ s/&\#107;/k/g;
  870:     $result =~ s/&\#108;/l/g;
  871:     $result =~ s/&\#109;/m/g;
  872:     $result =~ s/&\#110;/n/g;
  873:     $result =~ s/&\#111;/o/g;
  874:     $result =~ s/&\#112;/p/g;
  875:     $result =~ s/&\#113;/q/g;
  876:     $result =~ s/&\#114;/r/g;
  877:     $result =~ s/&\#115;/s/g;
  878:     $result =~ s/&\#116;/t/g;
  879:     $result =~ s/&\#117;/u/g;
  880:     $result =~ s/&\#118;/v/g;
  881:     $result =~ s/&\#119;/w/g;
  882:     $result =~ s/&\#120;/x/g;
  883:     $result =~ s/&\#121;/y/g;
  884:     $result =~ s/&\#122;/z/g;
  885:     $result =~ s/&\#123;/\\{/g;
  886:     $result =~ s/&\#124;/\|/g;
  887:     $result =~ s/&\#125;/\\}/g;
  888:     $result =~ s/&\#126;/\~/g;
  889:     $result =~ s/&\#131;/\\textflorin /g;
  890:     $result =~ s/&\#132;/\"/g;
  891:     $result =~ s/&\#133;/\\ensuremath\{\\ldots\}/g;
  892:     $result =~ s/&\#134;/\\ensuremath\{\\dagger\}/g;
  893:     $result =~ s/&\#135;/\\ensuremath\{\\ddagger\}/g;
  894:     $result =~ s/&\#137;/\\textperthousand /g;
  895:     $result =~ s/&\#140;/{\\OE}/g;
  896:     $result =~ s/&\#147;/\`\`/g;
  897:     $result =~ s/&\#148;/\'\'/g;
  898:     $result =~ s/&\#149;/\\ensuremath\{\\bullet\}/g;
  899:     $result =~ s/&(\#150|\#8211);/--/g;
  900:     $result =~ s/&\#151;/---/g;
  901:     $result =~ s/&\#152;/\\ensuremath\{\\sim\}/g;
  902:     $result =~ s/&\#153;/\\texttrademark /g;
  903:     $result =~ s/&\#156;/\\oe/g;
  904:     $result =~ s/&\#159;/\\\"Y/g;
  905:     $result =~ s/&(\#160|nbsp);/~/g;
  906:     $result =~ s/&(\#161|iexcl);/!\`/g;
  907:     $result =~ s/&(\#162|cent);/\\textcent /g;
  908:     $result =~ s/&(\#163|pound);/\\pounds /g; 
  909:     $result =~ s/&(\#164|curren);/\\textcurrency /g;
  910:     $result =~ s/&(\#165|yen);/\\textyen /g;
  911:     $result =~ s/&(\#166|brvbar);/\\textbrokenbar /g;
  912:     $result =~ s/&(\#167|sect);/\\textsection /g;
  913:     $result =~ s/&(\#168|uml);/\\"\{\} /g;
  914:     $result =~ s/&(\#169|copy);/\\copyright /g;
  915:     $result =~ s/&(\#170|ordf);/\\textordfeminine /g;
  916:     $result =~ s/&(\#172|not);/\\ensuremath\{\\neg\}/g;
  917:     $result =~ s/&(\#173|shy);/ - /g;
  918:     $result =~ s/&(\#174|reg);/\\textregistered /g;
  919:     $result =~ s/&(\#175|macr);/\\ensuremath\{^{-}\}/g;
  920:     $result =~ s/&(\#176|deg);/\\ensuremath\{^{\\circ}\}/g;
  921:     $result =~ s/&(\#177|plusmn);/\\ensuremath\{\\pm\}/g;
  922:     $result =~ s/&(\#178|sup2);/\\ensuremath\{^2\}/g;
  923:     $result =~ s/&(\#179|sup3);/\\ensuremath\{^3\}/g;
  924:     $result =~ s/&(\#180|acute);/\\'\{\} /g;
  925:     $result =~ s/&(\#181|micro);/\\ensuremath\{\\mu\}/g;
  926:     $result =~ s/&(\#182|para);/\\P/g;
  927:     $result =~ s/&(\#183|middot);/\\ensuremath\{\\cdot\}/g;
  928:     $result =~ s/&(\#184|cedil);/\\c{\\strut}/g;
  929:     $result =~ s/&(\#185|sup1);/\\ensuremath\{^1\}/g;
  930:     $result =~ s/&(\#186|ordm);/\\textordmasculine /g;
  931:     $result =~ s/&(\#188|frac14);/\\textonequarter /g;
  932:     $result =~ s/&(\#189|frac12);/\\textonehalf /g;
  933:     $result =~ s/&(\#190|frac34);/\\textthreequarters /g;
  934:     $result =~ s/&(\#191|iquest);/?\`/g;   
  935:     $result =~ s/&(\#192|Agrave);/\\\`{A}/g;  
  936:     $result =~ s/&(\#193|Aacute);/\\\'{A}/g; 
  937:     $result =~ s/&(\#194|Acirc);/\\^{A}/g;
  938:     $result =~ s/&(\#195|Atilde);/\\~{A}/g;
  939:     $result =~ s/&(\#196|Auml);/\\\"{A}/g; 
  940:     $result =~ s/&(\#197|Aring);/{\\AA}/g;
  941:     $result =~ s/&(\#198|AElig);/{\\AE}/g;
  942:     $result =~ s/&(\#199|Ccedil);/\\c{c}/g;
  943:     $result =~ s/&(\#200|Egrave);/\\\`{E}/g;  
  944:     $result =~ s/&(\#201|Eacute);/\\\'{E}/g;    
  945:     $result =~ s/&(\#202|Ecirc);/\\^{E}/g;
  946:     $result =~ s/&(\#203|Euml);/\\\"{E}/g;
  947:     $result =~ s/&(\#204|Igrave);/\\\`{I}/g;
  948:     $result =~ s/&(\#205|Iacute);/\\\'{I}/g;    
  949:     $result =~ s/&(\#206|Icirc);/\\^{I}/g;
  950:     $result =~ s/&(\#207|Iuml);/\\\"{I}/g;    
  951:     $result =~ s/&(\#209|Ntilde);/\\~{N}/g;
  952:     $result =~ s/&(\#210|Ograve);/\\\`{O}/g;
  953:     $result =~ s/&(\#211|Oacute);/\\\'{O}/g;
  954:     $result =~ s/&(\#212|Ocirc);/\\^{O}/g;
  955:     $result =~ s/&(\#213|Otilde);/\\~{O}/g;
  956:     $result =~ s/&(\#214|Ouml);/\\\"{O}/g;    
  957:     $result =~ s/&(\#215|times);/\\ensuremath\{\\times\}/g;
  958:     $result =~ s/&(\#216|Oslash);/{\\O}/g;
  959:     $result =~ s/&(\#217|Ugrave);/\\\`{U}/g;    
  960:     $result =~ s/&(\#218|Uacute);/\\\'{U}/g;
  961:     $result =~ s/&(\#219|Ucirc);/\\^{U}/g;
  962:     $result =~ s/&(\#220|Uuml);/\\\"{U}/g;
  963:     $result =~ s/&(\#221|Yacute);/\\\'{Y}/g;
  964:     $result =~ s/&(\#223|szlig);/{\\ss}/g;
  965:     $result =~ s/&(\#224|agrave);/\\\`{a}/g;
  966:     $result =~ s/&(\#225|aacute);/\\\'{a}/g;
  967:     $result =~ s/&(\#226|acirc);/\\^{a}/g;
  968:     $result =~ s/&(\#227|atilde);/\\~{a}/g;
  969:     $result =~ s/&(\#228|auml);/\\\"{a}/g;
  970:     $result =~ s/&(\#229|aring);/{\\aa}/g;
  971:     $result =~ s/&(\#230|aelig);/{\\ae}/g;
  972:     $result =~ s/&(\#231|ccedil);/\\c{c}/g;
  973:     $result =~ s/&(\#232|egrave);/\\\`{e}/g;
  974:     $result =~ s/&(\#233|eacute);/\\\'{e}/g;
  975:     $result =~ s/&(\#234|ecirc);/\\^{e}/g;
  976:     $result =~ s/&(\#235|euml);/\\\"{e}/g;
  977:     $result =~ s/&(\#236|igrave);/\\\`{i}/g;
  978:     $result =~ s/&(\#237|iacute);/\\\'{i}/g;
  979:     $result =~ s/&(\#238|icirc);/\\^{i}/g;
  980:     $result =~ s/&(\#239|iuml);/\\\"{i}/g;
  981:     $result =~ s/&(\#240|eth);/\\ensuremath\{\\partial\}/g;
  982:     $result =~ s/&(\#241|ntilde);/\\~{n}/g;
  983:     $result =~ s/&(\#242|ograve);/\\\`{o}/g;
  984:     $result =~ s/&(\#243|oacute);/\\\'{o}/g;
  985:     $result =~ s/&(\#244|ocirc);/\\^{o}/g;
  986:     $result =~ s/&(\#245|otilde);/\\~{o}/g;
  987:     $result =~ s/&(\#246|ouml);/\\\"{o}/g;
  988:     $result =~ s/&(\#247|divide);/\\ensuremath\{\\div\}/g;
  989:     $result =~ s/&(\#248|oslash);/{\\o}/g;
  990:     $result =~ s/&(\#249|ugrave);/\\\`{u}/g; 
  991:     $result =~ s/&(\#250|uacute);/\\\'{u}/g;
  992:     $result =~ s/&(\#251|ucirc);/\\^{u}/g;
  993:     $result =~ s/&(\#252|uuml);/\\\"{u}/g;
  994:     $result =~ s/&(\#253|yacute);/\\\'{y}/g;
  995:     $result =~ s/&(\#255|yuml);/\\\"{y}/g;
  996:     $result =~ s/&\#295;/\\ensuremath\{\\hbar\}/g;
  997:     $result =~ s/&\#952;/\\ensuremath\{\\theta\}/g;
  998: #Greek Alphabet
  999:     $result =~ s/&(alpha|\#945);/\\ensuremath\{\\alpha\}/g;
 1000:     $result =~ s/&(beta|\#946);/\\ensuremath\{\\beta\}/g;
 1001:     $result =~ s/&(gamma|\#947);/\\ensuremath\{\\gamma\}/g;
 1002:     $result =~ s/&(delta|\#948);/\\ensuremath\{\\delta\}/g;
 1003:     $result =~ s/&(epsilon|\#949);/\\ensuremath\{\\epsilon\}/g;
 1004:     $result =~ s/&(zeta|\#950);/\\ensuremath\{\\zeta\}/g;
 1005:     $result =~ s/&(eta|\#951);/\\ensuremath\{\\eta\}/g;
 1006:     $result =~ s/&(theta|\#952);/\\ensuremath\{\\theta\}/g;
 1007:     $result =~ s/&(iota|\#953);/\\ensuremath\{\\iota\}/g;
 1008:     $result =~ s/&(kappa|\#954);/\\ensuremath\{\\kappa\}/g;
 1009:     $result =~ s/&(lambda|\#955);/\\ensuremath\{\\lambda\}/g;
 1010:     $result =~ s/&(mu|\#956);/\\ensuremath\{\\mu\}/g;
 1011:     $result =~ s/&(nu|\#957);/\\ensuremath\{\\nu\}/g;
 1012:     $result =~ s/&(xi|\#958);/\\ensuremath\{\\xi\}/g;
 1013:     $result =~ s/&(omicron|\#959);/o/g;
 1014:     $result =~ s/&(pi|\#960);/\\ensuremath\{\\pi\}/g;
 1015:     $result =~ s/&(rho|\#961);/\\ensuremath\{\\rho\}/g;
 1016:     $result =~ s/&(sigma|\#963);/\\ensuremath\{\\sigma\}/g;
 1017:     $result =~ s/&(tau|\#964);/\\ensuremath\{\\tau\}/g;
 1018:     $result =~ s/&(upsilon|\#965);/\\ensuremath\{\\upsilon\}/g;
 1019:     $result =~ s/&(phi|\#966);/\\ensuremath\{\\phi\}/g;
 1020:     $result =~ s/&(chi|\#967);/\\ensuremath\{\\chi\}/g;
 1021:     $result =~ s/&(psi|\#968);/\\ensuremath\{\\psi\}/g;
 1022:     $result =~ s/&(omega|\#969);/\\ensuremath\{\\omega\}/g;
 1023:     $result =~ s/&(thetasym|\#977);/\\ensuremath\{\\vartheta\}/g;
 1024:     $result =~ s/&(piv|\#982);/\\ensuremath\{\\varpi\}/g;
 1025:     $result =~ s/&(Alpha|\#913);/A/g;
 1026:     $result =~ s/&(Beta|\#914);/B/g;
 1027:     $result =~ s/&(Gamma|\#915);/\\ensuremath\{\\Gamma\}/g;
 1028:     $result =~ s/&(Delta|\#916);/\\ensuremath\{\\Delta\}/g;
 1029:     $result =~ s/&(Epsilon|\#917);/E/g;
 1030:     $result =~ s/&(Zeta|\#918);/Z/g;
 1031:     $result =~ s/&(Eta|\#919);/H/g;
 1032:     $result =~ s/&(Theta|\#920);/\\ensuremath\{\\Theta\}/g;
 1033:     $result =~ s/&(Iota|\#921);/I/g;
 1034:     $result =~ s/&(Kappa|\#922);/K/g;
 1035:     $result =~ s/&(Lambda|\#923);/\\ensuremath\{\\Lambda\}/g;
 1036:     $result =~ s/&(Mu|\#924);/M/g;
 1037:     $result =~ s/&(Nu|\#925);/N/g;
 1038:     $result =~ s/&(Xi|\#926);/\\ensuremath\{\\Xi\}/g;
 1039:     $result =~ s/&(Omicron|\#927);/O/g;
 1040:     $result =~ s/&(Pi|\#928);/\\ensuremath\{\\Pi\}/g;
 1041:     $result =~ s/&(Rho|\#929);/P/g;
 1042:     $result =~ s/&(Sigma|\#931);/\\ensuremath\{\\Sigma\}/g;
 1043:     $result =~ s/&(Tau|\#932);/T/g;
 1044:     $result =~ s/&(Upsilon|\#933);/\\ensuremath\{\\Upsilon\}/g;
 1045:     $result =~ s/&(Phi|\#934);/\\ensuremath\{\\Phi\}/g;
 1046:     $result =~ s/&(Chi|\#935);/X/g;
 1047:     $result =~ s/&(Psi|\#936);/\\ensuremath\{\\Psi\}/g;
 1048:     $result =~ s/&(Omega|\#937);/\\ensuremath\{\\Omega\}/g;
 1049: #Arrows (extended HTML 4.01)
 1050:     $result =~ s/&(larr|\#8592);/\\ensuremath\{\\leftarrow\}/g;
 1051:     $result =~ s/&(uarr|\#8593);/\\ensuremath\{\\uparrow\}/g;
 1052:     $result =~ s/&(rarr|\#8594);/\\ensuremath\{\\rightarrow\}/g;
 1053:     $result =~ s/&(darr|\#8595);/\\ensuremath\{\\downarrow\}/g;
 1054:     $result =~ s/&(harr|\#8596);/\\ensuremath\{\\leftrightarrow\}/g;
 1055:     $result =~ s/&(lArr|\#8656);/\\ensuremath\{\\Leftarrow\}/g;
 1056:     $result =~ s/&(uArr|\#8657);/\\ensuremath\{\\Uparrow\}/g;
 1057:     $result =~ s/&(rArr|\#8658);/\\ensuremath\{\\Rightarrow\}/g;
 1058:     $result =~ s/&(dArr|\#8659);/\\ensuremath\{\\Downarrow\}/g;
 1059:     $result =~ s/&(hArr|\#8660);/\\ensuremath\{\\Leftrightarrow\}/g;
 1060: #Mathematical Operators (extended HTML 4.01)
 1061:     $result =~ s/&(forall|\#8704);/\\ensuremath\{\\forall\}/g;
 1062:     $result =~ s/&(part|\#8706);/\\ensuremath\{\\partial\}/g;
 1063:     $result =~ s/&(exist|\#8707);/\\ensuremath\{\\exists\}/g;
 1064:     $result =~ s/&(empty|\#8709);/\\ensuremath\{\\emptyset\}/g;
 1065:     $result =~ s/&(nabla|\#8711);/\\ensuremath\{\\nabla\}/g;
 1066:     $result =~ s/&(isin|\#8712);/\\ensuremath\{\\in\}/g;
 1067:     $result =~ s/&(notin|\#8713);/\\ensuremath\{\\notin\}/g;
 1068:     $result =~ s/&(ni|\#8715);/\\ensuremath\{\\ni\}/g;
 1069:     $result =~ s/&(prod|\#8719);/\\ensuremath\{\\prod\}/g;
 1070:     $result =~ s/&(sum|\#8721);/\\ensuremath\{\\sum\}/g;
 1071:     $result =~ s/&(minus|\#8722);/\\ensuremath\{-\}/g;
 1072:     $result =~ s/–/\\ensuremath\{-\}/g;
 1073:     $result =~ s/&(lowast|\#8727);/\\ensuremath\{*\}/g;
 1074:     $result =~ s/&(radic|\#8730);/\\ensuremath\{\\surd\}/g;
 1075:     $result =~ s/&(prop|\#8733);/\\ensuremath\{\\propto\}/g;
 1076:     $result =~ s/&(infin|\#8734);/\\ensuremath\{\\infty\}/g;
 1077:     $result =~ s/&(ang|\#8736);/\\ensuremath\{\\angle\}/g;
 1078:     $result =~ s/&(and|\#8743);/\\ensuremath\{\\wedge\}/g;
 1079:     $result =~ s/&(or|\#8744);/\\ensuremath\{\\vee\}/g;
 1080:     $result =~ s/&(cap|\#8745);/\\ensuremath\{\\cap\}/g;
 1081:     $result =~ s/&(cup|\#8746);/\\ensuremath\{\\cup\}/g;
 1082:     $result =~ s/&(int|\#8747);/\\ensuremath\{\\int\}/g;
 1083:     $result =~ s/&(sim|\#8764);/\\ensuremath\{\\sim\}/g;
 1084:     $result =~ s/&(cong|\#8773);/\\ensuremath\{\\cong\}/g;
 1085:     $result =~ s/&(asymp|\#8776);/\\ensuremath\{\\approx\}/g;
 1086:     $result =~ s/&(ne|\#8800);/\\ensuremath\{\\not=\}/g;
 1087:     $result =~ s/&(equiv|\#8801);/\\ensuremath\{\\equiv\}/g;
 1088:     $result =~ s/&(le|\#8804);/\\ensuremath\{\\leq\}/g;
 1089:     $result =~ s/&(ge|\#8805);/\\ensuremath\{\\geq\}/g;
 1090:     $result =~ s/&(sub|\#8834);/\\ensuremath\{\\subset\}/g;
 1091:     $result =~ s/&(sup|\#8835);/\\ensuremath\{\\supset\}/g;
 1092:     $result =~ s/&(nsub|\#8836);/\\ensuremath\{\\not\\subset\}/g;
 1093:     $result =~ s/&(sube|\#8838);/\\ensuremath\{\\subseteq\}/g;
 1094:     $result =~ s/&(supe|\#8839);/\\ensuremath\{\\supseteq\}/g;
 1095:     $result =~ s/&(oplus|\#8853);/\\ensuremath\{\\oplus\}/g;
 1096:     $result =~ s/&(otimes|\#8855);/\\ensuremath\{\\otimes\}/g;
 1097:     $result =~ s/&(perp|\#8869);/\\ensuremath\{\\perp\}/g;
 1098:     $result =~ s/&(sdot|\#8901);/\\ensuremath\{\\cdot\}/g;
 1099: #Geometric Shapes (extended HTML 4.01)
 1100:     $result =~ s/&(loz|\#9674);/\\ensuremath\{\\Diamond\}/g;
 1101: #Miscellaneous Symbols (extended HTML 4.01)
 1102:     $result =~ s/&(spades|\#9824);/\\ensuremath\{\\spadesuit\}/g;
 1103:     $result =~ s/&(clubs|\#9827);/\\ensuremath\{\\clubsuit\}/g;
 1104:     $result =~ s/&(hearts|\#9829);/\\ensuremath\{\\heartsuit\}/g;
 1105:     $result =~ s/&(diams|\#9830);/\\ensuremath\{\\diamondsuit\}/g;
 1106: #   Chemically useful 'things' contributed by Hon Kie (bug 4652).
 1107: 
 1108:     $result =~ s/&\#8636;/\\ensuremath\{\\leftharpoonup\}/g;
 1109:     $result =~ s/&\#8637;/\\ensuremath\{\\leftharpoondown\}/g;
 1110:     $result =~ s/&\#8640;/\\ensuremath\{\\rightharpoonup\}/g;
 1111:     $result =~ s/&\#8641;/\\ensuremath\{\\rightharpoondown\}/g;
 1112:     $result =~ s/&\#8652;/\\ensuremath\{\\rightleftharpoons\}/g;
 1113:     $result =~ s/&\#8605;/\\ensuremath\{\\leadsto\}/g;
 1114:     $result =~ s/&\#8617;/\\ensuremath\{\\hookleftarrow\}/g;
 1115:     $result =~ s/&\#8618;/\\ensuremath\{\\hookrightarrow\}/g;
 1116:     $result =~ s/&\#8614;/\\ensuremath\{\\mapsto\}/g;
 1117:     $result =~ s/&\#8599;/\\ensuremath\{\\nearrow\}/g;
 1118:     $result =~ s/&\#8600;/\\ensuremath\{\\searrow\}/g;
 1119:     $result =~ s/&\#8601;/\\ensuremath\{\\swarrow\}/g;
 1120:     $result =~ s/&\#8598;/\\ensuremath\{\\nwarrow\}/g;
 1121: 
 1122:     # Left/right quotations:
 1123: 
 1124:     $result =~ s/&(ldquo|#8220);/\`\`/g;
 1125:     $result =~ s/&(rdquo|#8221);/\'\'/g;
 1126: 
 1127: 
 1128: 
 1129:     return $result;
 1130: }
 1131: 
 1132: 
 1133:                   #width, height, oddsidemargin, evensidemargin, topmargin
 1134: my %page_formats=
 1135:     ('letter' => {
 1136: 	 'book' => {
 1137: 	     '1' => [ '7.1 in','9.8 in', '-0.57 in','-0.57 in','0.275 in'],
 1138: 	     '2' => ['3.66 in','9.8 in', '-0.57 in','-0.57 in','0.275 in']
 1139: 	 },
 1140: 	 'album' => {
 1141: 	     '1' => [ '8.8 in', '6.8 in','-0.55 in',  '-0.55 in','0.394 in'],
 1142: 	     '2' => [ '4.8 in', '6.8 in','-0.5 in', '-1.0 in','3.5 in']
 1143: 	 },
 1144:      },
 1145:      'legal' => {
 1146: 	 'book' => {
 1147: 	     '1' => ['7.1 in','13 in',,'-0.57 in','-0.57 in','-0.5 in'],
 1148: 	     '2' => ['3.66 in','13 in','-0.57 in','-0.57 in','-0.5 in']
 1149: 	 },
 1150: 	 'album' => {
 1151: 	     '1' => ['12 in','7.1 in',,'-0.57 in','-0.57 in','-0.5 in'],
 1152:              '2' => ['6.0 in','7.1 in','-1 in','-1 in','5 in']
 1153:           },
 1154:      },
 1155:      'tabloid' => {
 1156: 	 'book' => {
 1157: 	     '1' => ['9.8 in','16 in','-0.57 in','-0.57 in','-0.5 in'],
 1158: 	     '2' => ['4.9 in','16 in','-0.57 in','-0.57 in','-0.5 in']
 1159: 	 },
 1160: 	 'album' => {
 1161: 	     '1' => ['16 in','9.8 in','-0.57 in','-0.57 in','-0.5 in'],
 1162: 	     '2' => ['16 in','4.9 in','-0.57 in','-0.57 in','-0.5 in']
 1163:           },
 1164:      },
 1165:      'executive' => {
 1166: 	 'book' => {
 1167: 	     '1' => ['6.8 in','9 in','-0.57 in','-0.57 in','1.2 in'],
 1168: 	     '2' => ['3.1 in','9 in','-0.57 in','-0.57 in','1.2 in']
 1169: 	 },
 1170: 	 'album' => {
 1171: 	     '1' => [],
 1172: 	     '2' => []
 1173:           },
 1174:      },
 1175:      'a2' => {
 1176: 	 'book' => {
 1177: 	     '1' => [],
 1178: 	     '2' => []
 1179: 	 },
 1180: 	 'album' => {
 1181: 	     '1' => [],
 1182: 	     '2' => []
 1183:           },
 1184:      },
 1185:      'a3' => {
 1186: 	 'book' => {
 1187: 	     '1' => [],
 1188: 	     '2' => []
 1189: 	 },
 1190: 	 'album' => {
 1191: 	     '1' => [],
 1192: 	     '2' => []
 1193:           },
 1194:      },
 1195:      'a4' => {
 1196: 	 'book' => {
 1197: 	     '1' => ['17.6 cm','27.2 cm','-1.397 cm','-2.11 cm','-1.27 cm'],
 1198: 	     '2' => [ '9.1 cm','27.2 cm','-1.397 cm','-2.11 cm','-1.27 cm']
 1199: 	 },
 1200: 	 'album' => {
 1201: 	     '1' => ['21.59 cm','19.558 cm','-1.397cm','-2.11 cm','0 cm'],
 1202: 	     '2' => ['9.91 cm','19.558 cm','-1.397 cm','-2.11 cm','0 cm']
 1203: 	 },
 1204:      },
 1205:      'a5' => {
 1206: 	 'book' => {
 1207: 	     '1' => [],
 1208: 	     '2' => []
 1209: 	 },
 1210: 	 'album' => {
 1211: 	     '1' => [],
 1212: 	     '2' => []
 1213:           },
 1214:      },
 1215:      'a6' => {
 1216: 	 'book' => {
 1217: 	     '1' => [],
 1218: 	     '2' => []
 1219: 	 },
 1220: 	 'album' => {
 1221: 	     '1' => [],
 1222: 	     '2' => []
 1223:           },
 1224:      },
 1225:      );
 1226: 
 1227: sub page_format {
 1228: #
 1229: #Supported paper format: "Letter [8 1/2x11 in]",      "Legal [8 1/2x14 in]",
 1230: #                        "Ledger/Tabloid [11x17 in]", "Executive [7 1/2x10 in]",
 1231: #                        "A2 [420x594 mm]",           "A3 [297x420 mm]",
 1232: #                        "A4 [210x297 mm]",           "A5 [148x210 mm]",
 1233: #                        "A6 [105x148 mm]"
 1234: # 
 1235:     my ($papersize,$layout,$numberofcolumns) = @_; 
 1236:     return @{$page_formats{$papersize}->{$layout}->{$numberofcolumns}};
 1237: }
 1238: 
 1239: 
 1240: sub get_name {
 1241:     my ($uname,$udom)=@_;
 1242:     if (!defined($uname)) { $uname=$env{'user.name'}; }
 1243:     if (!defined($udom)) { $udom=$env{'user.domain'}; }
 1244:     my $plainname=&Apache::loncommon::plainname($uname,$udom);
 1245:     if ($plainname=~/^\s*$/) { $plainname=$uname.'@'.$udom; }
 1246:    $plainname=&Apache::lonxml::latex_special_symbols($plainname,'header');
 1247:     return $plainname;
 1248: }
 1249: 
 1250: sub get_course {
 1251:     my $courseidinfo;
 1252:     if (defined($env{'request.course.id'})) {
 1253: 	$courseidinfo = &Apache::lonxml::latex_special_symbols(&unescape($env{'course.'.$env{'request.course.id'}.'.description'}),'header');
 1254: 	my $sec = $env{'request.course.sec'};
 1255: 	    
 1256:     }
 1257:     return $courseidinfo;
 1258: }
 1259: 
 1260: sub page_format_transformation {
 1261:     my ($papersize,$layout,$numberofcolumns,$choice,$text,$assignment,$tableofcontents,$indexlist,$selectionmade) = @_; 
 1262:     my ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin);
 1263: 
 1264:     if ($selectionmade eq '4') {
 1265: 	if ($choice eq 'all_problems') {
 1266:             $assignment=&mt('Problems from the Whole Course');
 1267: 	} else {
 1268:             $assignment=&mt('Resources from the Whole Course');
 1269: 	}
 1270:     } else {
 1271: 	$assignment=&Apache::lonxml::latex_special_symbols($assignment,'header');
 1272:     }
 1273:     ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin) = &page_format($papersize,$layout,$numberofcolumns,$topmargin);
 1274: 
 1275: 
 1276:     my $name = &get_name();
 1277:     my $courseidinfo = &get_course();
 1278:     my $header_text  = $parmhash{'print_header_format'};
 1279:     $header_text     = &format_page_header($textwidth, $header_text, $assignment,
 1280: 					   $courseidinfo, $name);
 1281:     my $topmargintoinsert = '';
 1282:     if ($topmargin ne '0') {$topmargintoinsert='\setlength{\topmargin}{'.$topmargin.'}';}
 1283:     my $fancypagestatement='';
 1284:     if ($numberofcolumns eq '2') {
 1285: 	$fancypagestatement="\\fancyhead{}\\fancyhead[LO]{$header_text}";
 1286:     } else {
 1287: 	$fancypagestatement="\\rhead{}\\chead{}\\lhead{$header_text}";
 1288:     }
 1289:     if ($layout eq 'album') {
 1290: 	    $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\\usepackage{booktabs}\\begin{document}\\voffset=-0\.8 cm\\setcounter{page}{1}\n /;
 1291:     } elsif ($layout eq 'book') {
 1292: 	if ($choice ne 'All class print') { 
 1293: 	    $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\\usepackage{booktabs}\\begin{document}\n\\voffset=-0\.8 cm\\setcounter{page}{1}\n/;
 1294: 	} else {
 1295: 	    $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{}\\usepackage{booktabs}\\begin{document}\\voffset=-0\.8cm\n\\setcounter{page}{1}  \\vskip 5 mm\n /;
 1296: 	}
 1297: 	if ($papersize eq 'a4') {
 1298: 	    $text =~ s/(\\begin{document})/$1\\special{papersize=210mm,297mm}/;
 1299: 	}
 1300:     }
 1301:     if ($tableofcontents eq 'yes') {$text=~s/(\\setcounter\{page\}\{1\})/$1 \\tableofcontents\\newpage /;}
 1302:     if ($indexlist eq 'yes') {
 1303: 	$text=~s/(\\begin{document})/\\makeindex $1/;
 1304: 	$text=~s/(\\end{document})/\\strut\\\\\\strut\\printindex $1/;
 1305:     }
 1306:     return $text;
 1307: }
 1308: 
 1309: 
 1310: sub page_cleanup {
 1311:     my $result = shift;	
 1312:  
 1313:     $result =~ m/\\end{document}(\d*)$/;
 1314:     my $number_of_columns = $1;
 1315:     my $insert = '{';
 1316:     for (my $id=1;$id<=$number_of_columns;$id++) { $insert .='l'; }
 1317:     $insert .= '}';
 1318:     $result =~ s/(\\begin{longtable})INSERTTHEHEADOFLONGTABLE\\endfirsthead\\endhead/$1$insert/g;
 1319:     $result =~ s/&\s*REMOVETHEHEADOFLONGTABLE\\\\/\\\\/g;
 1320:     return $result,$number_of_columns;
 1321: }
 1322: 
 1323: 
 1324: sub details_for_menu {
 1325:     my ($helper)=@_;
 1326:     my $postdata=$env{'form.postdata'};
 1327:     if (!$postdata) { $postdata=$helper->{VARS}{'postdata'}; }
 1328:     my $name_of_resource = &Apache::lonnet::gettitle($postdata);
 1329:     my $symbolic = &Apache::lonnet::symbread($postdata);
 1330:     return if ( $symbolic eq '');
 1331: 
 1332:     my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symbolic);
 1333:     $map=&Apache::lonnet::clutter($map);
 1334:     my $name_of_sequence = &Apache::lonnet::gettitle($map);
 1335:     if ($name_of_sequence =~ /^\s*$/) {
 1336: 	$map =~ m|([^/]+)$|;
 1337: 	$name_of_sequence = $1;
 1338:     }
 1339:     my $name_of_map = &Apache::lonnet::gettitle($env{'request.course.uri'});
 1340:     if ($name_of_map =~ /^\s*$/) {
 1341: 	$env{'request.course.uri'} =~ m|([^/]+)$|;
 1342: 	$name_of_map = $1;
 1343:     }
 1344:     return ($name_of_resource,$name_of_sequence,$name_of_map);
 1345: }
 1346: 
 1347: sub copyright_line {
 1348:     return '\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\vspace*{-2 mm}\newline\noindent{\tiny Printed from LON-CAPA\copyright MSU{\hfill} Licensed under GNU General Public License } ';
 1349: }
 1350: my $end_of_student = "\n".'\special{ps:ENDOFSTUDENTSTAMP}'."\n";
 1351: 
 1352: sub latex_corrections {
 1353:     my ($number_of_columns,$result,$selectionmade,$answer_mode) = @_;
 1354: #    $result =~ s/\\includegraphics{/\\includegraphics\[width=\\minipagewidth\]{/g;
 1355:     my $copyright = &copyright_line();
 1356:     if ($selectionmade eq '1' || $answer_mode eq 'only') {
 1357: 	$result =~ s/(\\end{document})/\\strut\\vskip 0 mm $copyright $end_of_student $1/;
 1358:     } else {
 1359: 	$result =~ s/(\\end{document})/\\strut\\vspace\*{-4 mm}\\newline $copyright $end_of_student $1/;
 1360:     }
 1361:     $result =~ s/\$number_of_columns/$number_of_columns/g;
 1362:     $result =~ s/(\\end{longtable}\s*)(\\strut\\newline\\noindent\\makebox\[\\textwidth\/$number_of_columns\]\[b\]{\\hrulefill})/$2$1/g;
 1363:     $result =~ s/(\\end{longtable}\s*)\\strut\\newline/$1/g;
 1364: #-- LaTeX corrections     
 1365:     my $first_comment = index($result,'<!--',0);
 1366:     while ($first_comment != -1) {
 1367: 	my $end_comment = index($result,'-->',$first_comment);
 1368: 	substr($result,$first_comment,$end_comment-$first_comment+3) = '';
 1369: 	$first_comment = index($result,'<!--',$first_comment);
 1370:     }
 1371:     $result =~ s/^\s+$//gm; #remove empty lines
 1372:     #removes more than one empty space
 1373:     $result =~ s|(\s\s+)|($1=~/[\n\r]/)?"\n":" "|ge;
 1374:     $result =~ s/\\\\\s*\\vskip/\\vskip/gm;
 1375:     $result =~ s/\\\\\s*\\noindent\s*(\\\\)+/\\\\\\noindent /g;
 1376:     $result =~ s/{\\par }\s*\\\\/\\\\/gm;
 1377:     $result =~ s/\\\\\s+\[/ \[/g;
 1378:     #conversion of html characters to LaTeX equivalents
 1379:     if ($result =~ m/&(\w+|#\d+);/) {
 1380: 	$result = &character_chart($result);
 1381:     }
 1382:     $result =~ s/(\\end{tabular})\s*\\vskip 0 mm/$1/g;
 1383:     $result =~ s/(\\begin{enumerate})\s*\\noindent/$1/g;
 1384:     return $result;
 1385: }
 1386: 
 1387: 
 1388: sub index_table {
 1389:     my $currentURL = shift;
 1390:     my $insex_string='';
 1391:     $currentURL=~s/\.([^\/+])$/\.$1\.meta/;
 1392:     $insex_string=&Apache::lonnet::metadata($currentURL,'keywords');
 1393:     return $insex_string;
 1394: }
 1395: 
 1396: 
 1397: sub IndexCreation {
 1398:     my ($texversion,$currentURL)=@_;
 1399:     my @key_words=split(/,/,&index_table($currentURL));
 1400:     my $chunk='';
 1401:     my $st=index $texversion,'\addcontentsline{toc}{subsection}{';
 1402:     if ($st>0) {
 1403: 	for (my $i=0;$i<3;$i++) {$st=(index $texversion,'}',$st+1);}
 1404: 	$chunk=substr($texversion,0,$st+1);
 1405: 	substr($texversion,0,$st+1)=' ';
 1406:     }
 1407:     foreach my $key_word (@key_words) {
 1408: 	if ($key_word=~/\S+/) {
 1409: 	    $texversion=~s/\b($key_word)\b/$1 \\index{$key_word} /i;
 1410: 	}
 1411:     }			
 1412:     if ($st>0) {substr($texversion,0,1)=$chunk;}
 1413:     return $texversion;
 1414: }
 1415: 
 1416: sub print_latex_header {
 1417:     my $mode=shift;
 1418: 
 1419:     return &Apache::londefdef::latex_header($mode);
 1420: }
 1421: 
 1422: sub path_to_problem {
 1423:     my ($urlp,$colwidth)=@_;
 1424:     $urlp=&Apache::lonnet::clutter($urlp);
 1425: 
 1426:     my $newurlp = '';
 1427:     $colwidth=~s/\s*mm\s*$//;
 1428: #characters average about 2 mm in width
 1429:     if (length($urlp)*2 > $colwidth) {
 1430: 	my @elements = split('/',$urlp);
 1431: 	my $curlength=0;
 1432: 	foreach my $element (@elements) {
 1433: 	    if ($element eq '') { next; }
 1434: 	    if ($curlength+(length($element)*2) > $colwidth) {
 1435: 		$newurlp .=  '|\vskip -1 mm \verb|';
 1436: 		$curlength=length($element)*2;
 1437: 	    } else {
 1438: 		$curlength+=length($element)*2;
 1439: 	    }
 1440: 	    $newurlp.='/'.$element;
 1441: 	}
 1442:     } else {
 1443: 	$newurlp=$urlp;
 1444:     }
 1445:     return '{\small\noindent\verb|'.$newurlp.'|\vskip 0 mm}';
 1446: }
 1447: 
 1448: sub recalcto_mm {
 1449:     my $textwidth=shift;
 1450:     my $LaTeXwidth;
 1451:     if ($textwidth=~/(-?\d+\.?\d*)\s*cm/) {
 1452: 	$LaTeXwidth = $1*10;
 1453:     } elsif ($textwidth=~/(-?\d+\.?\d*)\s*mm/) {
 1454: 	$LaTeXwidth = $1;
 1455:     } elsif ($textwidth=~/(-?\d+\.?\d*)\s*in/) {
 1456: 	$LaTeXwidth = $1*25.4;
 1457:     }
 1458:     $LaTeXwidth.=' mm';
 1459:     return $LaTeXwidth;
 1460: }
 1461: 
 1462: sub get_textwidth {
 1463:     my ($helper,$LaTeXwidth)=@_;
 1464:     my $textwidth=$LaTeXwidth;
 1465:     if ($helper->{'VARS'}->{'pagesize.width'}=~/\d+/ &&
 1466: 	$helper->{'VARS'}->{'pagesize.widthunit'}=~/\w+/) {
 1467: 	$textwidth=&recalcto_mm($helper->{'VARS'}->{'pagesize.width'}.' '.
 1468: 				$helper->{'VARS'}->{'pagesize.widthunit'});
 1469:     }
 1470:     return $textwidth;
 1471: }
 1472: 
 1473: 
 1474: sub unsupported {
 1475:     my ($currentURL,$mode,$symb)=@_;
 1476:     if ($mode ne '') {$mode='\\'.$mode}
 1477:     my $result.= &print_latex_header($mode);
 1478:     if ($currentURL=~m|^(/adm/wrapper/)?ext/|) {
 1479: 	$currentURL=~s|^(/adm/wrapper/)?ext/|http://|;
 1480: 	my $title=&Apache::lonnet::gettitle($symb);
 1481: 	$title = &Apache::lonxml::latex_special_symbols($title);
 1482: 	$result.=' \strut \\\\ '.$title.' \strut \\\\ '.$currentURL.' ';
 1483:     } else {
 1484: 	$result.=$currentURL;
 1485:     }
 1486:     $result.= '\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill} \end{document}';
 1487:     return $result;
 1488: }
 1489: 
 1490: #
 1491: #  Map from helper layout style to the book/album:
 1492: #
 1493: sub map_laystyle {
 1494:     my ($laystyle) = @_;
 1495:     if ($laystyle eq 'L') {
 1496: 	$laystyle='album';
 1497:     } else {
 1498: 	$laystyle='book';
 1499:     }
 1500:     return $laystyle;
 1501: }
 1502: 
 1503: sub print_page_in_course {
 1504:     my ($helper, $rparmhash, $currentURL, $resources) = @_;
 1505:     my %parmhash       = %$rparmhash;
 1506:     my @page_resources = @$resources;
 1507:     my $mode = $helper->{'VARS'}->{'LATEX_TYPE'};
 1508:     my $symb = $helper->{'VARS'}->{'symb'};
 1509: 
 1510: 
 1511:     my $format_from_helper = $helper->{'VARS'}->{'FORMAT'};
 1512: 
 1513: 
 1514:     my @temporary_array=split /\|/,$format_from_helper;
 1515:     my ($laystyle,$numberofcolumns,$papersize,$pdfFormFields)=@temporary_array;
 1516:     $laystyle = &map_laystyle($laystyle);
 1517:     my ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$laystyle,
 1518: 								      $numberofcolumns);
 1519:     my $LaTeXwidth=&recalcto_mm($textwidth); 
 1520: 
 1521: 
 1522:     if ($mode ne '') {$mode='\\'.$mode}
 1523:     my $result   =    &print_latex_header($mode);
 1524:     if ($currentURL=~m|^(/adm/wrapper/)?ext/|) {
 1525: 	$currentURL=~s|^(/adm/wrapper/)?ext/|http://|;
 1526: 	my $title=&Apache::lonnet::gettitle($symb);
 1527: 	$title = &Apache::lonxml::latex_special_symbols($title);
 1528:     } else {
 1529: 	$result.=$currentURL;
 1530:     }
 1531:     $result .= '\\\\';
 1532: 
 1533:     if ($helper->{'VARS'}->{'style_file'}=~/\w/) {
 1534: 	&Apache::lonnet::appenv({'construct.style' =>
 1535: 				$helper->{'VARS'}->{'style_file'}});
 1536:     } elsif ($env{'construct.style'}) {
 1537: 	&Apache::lonnet::delenv('construct.style');
 1538:     }
 1539: 
 1540:     # First is the overall page description.  This is then followed by the 
 1541:     # components of the page. Each of which must be printed independently.
 1542:     my $the_page = shift(@page_resources); 
 1543: 
 1544: 
 1545:     foreach my $resource (@page_resources) {
 1546: 	my $resource_src   = $resource->src(); # Essentially the URL of the resource.
 1547: 	$result           .= $resource->title() . '\\\\';
 1548: 
 1549: 	# Recurse if a .page:
 1550: 
 1551: 	if ($resource_src =~ /.page$/i) {
 1552: 	    my $navmap         = Apache::lonnavmaps::navmap->new();
 1553: 	    my @page_resources = $navmap->retrieveResources($resource_src);
 1554: 	    $result           .= &print_page_in_course($helper, $rparmhash, 
 1555: 						       $resource_src, \@page_resources);
 1556: 	}
 1557: 	# these resources go through the XML transformer:
 1558: 
 1559: 	elsif ($resource_src =~ /\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm\xhtml|xhtm)$/)  {		
 1560: 	    my $urlp = &Apache::lonnet::clutter($resource_src);
 1561: 	    my %form;
 1562: 	    my %moreenv;
 1563: 
 1564: 	    &Apache::lonxml::remember_problem_counter();
 1565: 	    $moreenv{'request.filename'}=$urlp;
 1566: 	    if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {$form{'problemtype'}='exam';}
 1567: 
 1568: 	    $form{'grade_target'}  = 'tex';
 1569: 	    $form{'textwidth'}    = &get_textwidth($helper, $LaTeXwidth);
 1570: 	    $form{'pdfFormFiels'} = $pdfFormFields; # 
 1571: 	    $form{'showallfoils'} = $helper->{'VARS'}->{'showallfoils'};    
 1572: 	    
 1573: 	    $form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1574: 	    $form{'suppress_tries'}=$parmhash{'suppress_tries'};
 1575: 	    $form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1576: 	    $form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 1577: 	    $form{'print_annotations'}=$helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 1578: 	    if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') ||
 1579: 		($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes')) {
 1580: 		$form{'problem_split'}='yes';
 1581: 	    }
 1582: 	    my $rndseed = time;
 1583: 	    if ($helper->{'VARS'}->{'curseed'}) {
 1584: 		$rndseed=$helper->{'VARS'}->{'curseed'};
 1585: 	    }
 1586: 	    $form{'rndseed'}=$rndseed;
 1587: 	    &Apache::lonnet::appenv(\%moreenv);
 1588: 	    
 1589: 	    &Apache::lonxml::clear_problem_counter();
 1590: 
 1591: 	    my $texversion = &ssi_with_retries($urlp, $ssi_retry_count, %form);
 1592: 
 1593: 
 1594: 	    # current document with answers.. no need to encap in minipage
 1595: 	    #  since there's only one answer.
 1596: 
 1597: 	    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 1598: 	       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 1599: 		my %answerform = %form;
 1600: 
 1601: 
 1602: 		$answerform{'problem_split'}=$parmhash{'problem_stream_switch'};
 1603: 		$answerform{'grade_target'}='answer';
 1604: 		$answerform{'answer_output_mode'}='tex';
 1605: 		$answerform{'rndseed'}=$rndseed;
 1606:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {
 1607: 		    $answerform{'problemtype'}='exam';
 1608: 		}
 1609: 		$resources_printed .= $urlp.':';
 1610: 		my $answer=&ssi_with_retries($urlp,$ssi_retry_count, %answerform);
 1611: 
 1612: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 1613: 		    $texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 1614: 		} else {
 1615: 		    $texversion= &print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1616: 		    if ($helper->{'VARS'}->{'construction'} ne '1') {
 1617: 			my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 1618: 			$title = &Apache::lonxml::latex_special_symbols($title);
 1619: 			$texversion.='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 1620: 			$texversion.=&path_to_problem($urlp,$LaTeXwidth);
 1621: 		    } else {
 1622: 			$texversion.='\vskip 0 mm \noindent\textbf{Prints from construction space - there is no title.}\vskip 0 mm ';
 1623: 			my $URLpath=$urlp;
 1624: 			$URLpath=~s/~([^\/]+)/public_html\/$1\/$1/;
 1625: 			$texversion.=&path_to_problem($URLpath,$LaTeXwidth);
 1626: 		    }
 1627: 		    $texversion.='\vskip 1 mm '.$answer.'\end{document}';
 1628: 		}
 1629: 
 1630: 
 1631: 		
 1632: 
 1633: 	    
 1634: 	    }
 1635: 	    # Print annotations.
 1636: 
 1637: 
 1638: 	    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 1639: 		my $annotation .= &annotate($currentURL);
 1640: 		$texversion =~ s/(\\keephidden{ENDOFPROBLEM})/$annotation$1/;
 1641: 	    }
 1642: 	    
 1643: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 1644: 		$texversion=&IndexCreation($texversion,$currentURL);
 1645: 	    }
 1646: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 1647: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$currentURL| \\strut\\\\\\strut /;
 1648: 
 1649: 	    }
 1650: 	    $texversion = &latex_header_footer_remove($texversion);
 1651: 
 1652: 	    # the first remaining line is a comment from londefdef the second
 1653: 	    # line  seems to be an extraneous \vskip 1mm \\\\ :
 1654:             # (imperfect removal from header_footer_remove?
 1655: 
 1656: 	    $texversion =~ s/\\vskip 1mm \\\\\\\\//;
 1657: 
 1658: 	    $result .= $texversion;
 1659: 	    if ($currentURL=~m/\.page\s*$/) {
 1660: 		($result,$numberofcolumns) = &page_cleanup($result);
 1661: 	    }
 1662: 	}
 1663:     }
 1664: 
 1665:     $result.= '\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill} \end{document}';
 1666:     return $result;
 1667: }
 1668: 
 1669: 
 1670: #
 1671: # List of recently generated print files
 1672: #
 1673: sub recently_generated {
 1674:     my $r=shift;
 1675:     my $prtspool=$r->dir_config('lonPrtDir');
 1676:     my $zip_result;
 1677:     my $pdf_result;
 1678:     opendir(DIR,$prtspool);
 1679: 
 1680:     my @files = 
 1681: 	grep(/^$env{'user.name'}_$env{'user.domain'}_printout_(\d+)_.*\.(pdf|zip)$/,readdir(DIR));
 1682:     closedir(DIR);
 1683: 
 1684:     @files = sort {
 1685: 	my ($actime) = (stat($prtspool.'/'.$a))[10];
 1686: 	my ($bctime) = (stat($prtspool.'/'.$b))[10];
 1687: 	return $bctime <=> $actime;
 1688:     } (@files);
 1689: 
 1690:     foreach my $filename (@files) {
 1691: 	my ($ext) = ($filename =~ m/(pdf|zip)$/);
 1692: 	my ($cdev,$cino,$cmode,$cnlink,
 1693: 	    $cuid,$cgid,$crdev,$csize,
 1694: 	    $catime,$cmtime,$cctime,
 1695: 	    $cblksize,$cblocks)=stat($prtspool.'/'.$filename);
 1696:         my $ext_text = 'pdf' ? &mt('PDF File'):&mt('Zip File');
 1697: 	my $result=&Apache::loncommon::start_data_table_row()
 1698:                   .'<td>'
 1699:                   .'<a href="/prtspool/'.$filename.'">'.$ext_text.'</a>'
 1700:                   .'</td>'
 1701:                   .'<td>'.&Apache::lonlocal::locallocaltime($cctime).'</td>'
 1702:                   .'<td align="right">'.$csize.'</td>'
 1703:                   .&Apache::loncommon::end_data_table_row();
 1704: 	if ($ext eq 'pdf') { $pdf_result .= $result; }
 1705: 	if ($ext eq 'zip') { $zip_result .= $result; }
 1706:     }
 1707:     if ($zip_result || $pdf_result) {
 1708:         $r->print('<hr />');
 1709:     }
 1710:     if ($zip_result) {
 1711: 	$r->print('<h3>'.&mt('Recently generated printout zip files')."</h3>\n"
 1712:                   .&Apache::loncommon::start_data_table()
 1713:                   .&Apache::loncommon::start_data_table_header_row()
 1714:                   .'<th>'.&mt('Download').'</th>'
 1715:                   .'<th>'.&mt('Creation Date').'</th>'
 1716:                   .'<th>'.&mt('File Size (Bytes)').'</th>'
 1717:                   .&Apache::loncommon::end_data_table_header_row()
 1718:                   .$zip_result
 1719:                   .&Apache::loncommon::end_data_table()
 1720:         );
 1721:     }
 1722:     if ($pdf_result) {
 1723: 	$r->print('<h3>'.&mt('Recently generated printouts')."</h3>\n"
 1724:                   .&Apache::loncommon::start_data_table()
 1725:                   .&Apache::loncommon::start_data_table_header_row()
 1726:                   .'<th>'.&mt('Download').'</th>'
 1727:                   .'<th>'.&mt('Creation Date').'</th>'
 1728:                   .'<th>'.&mt('File Size (Bytes)').'</th>'
 1729:                   .&Apache::loncommon::end_data_table_header_row()
 1730:                   .$pdf_result
 1731:                   .&Apache::loncommon::end_data_table()
 1732:         );
 1733:     }
 1734: }
 1735: 
 1736: #
 1737: #   Retrieve the hash of page breaks.
 1738: #
 1739: #  Inputs:
 1740: #    helper   - reference to helper object.
 1741: #  Outputs
 1742: #    A reference to a page break hash.
 1743: #
 1744: #
 1745: # use Data::Dumper;
 1746: #sub dump_helper_vars {
 1747: #    my ($helper) = @_;
 1748: #    my $helpervars = Dumper($helper->{'VARS'});
 1749: #    &Apache::lonnet::logthis("Dump of helper vars:\n $helpervars");
 1750: #}
 1751: 
 1752: sub get_page_breaks  {
 1753:     my ($helper) = @_;
 1754:     my %page_breaks;
 1755: 
 1756:     foreach my $break (split /\|\|\|/, $helper->{'VARS'}->{'FINISHPAGE'}) {
 1757: 	$page_breaks{$break} = 1;
 1758:     }
 1759:     return %page_breaks;
 1760: }
 1761: 
 1762: #  Output a sequence (recursively if neeed)
 1763: #  from construction space.
 1764: # Parameters:
 1765: #    url     = URL of the sequence to print.
 1766: #    helper  - Reference to the helper hash.
 1767: #    form    - Copy of the format hash.
 1768: #    LaTeXWidth
 1769: # Returns:
 1770: #   Text to add to the printout.
 1771: #   NOTE if the first element of the outermost sequence
 1772: #   is itself a sequence, the outermost caller may need to
 1773: #   prefix the latex with the page headers stuff.
 1774: #
 1775: sub print_construction_sequence {
 1776:     my ($currentURL, $helper, %form, $LaTeXwidth) = @_;
 1777:     my $result;
 1778:     my $rndseed=time;
 1779:     if ($helper->{'VARS'}->{'curseed'}) {
 1780: 	$rndseed=$helper->{'VARS'}->{'curseed'};
 1781:     }
 1782:     my $errtext=&LONCAPA::map::mapread($currentURL);
 1783:     # 
 1784:     #  These make this all support recursing for subsequences.
 1785:     #
 1786:     my @order    = @LONCAPA::map::order;
 1787:     my @resources = @LONCAPA::map::resources; 
 1788:     for (my $member=0;$member<=$#order;$member++) {
 1789: 	$resources[$order[$member]]=~/^([^:]*):([^:]*):/;
 1790: 	my $urlp=$2;
 1791: 	if ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm)$/) {
 1792: 	    my $texversion='';
 1793: 	    if ($helper->{'VARS'}->{'ANSWER_TYPE'} ne 'only') {
 1794: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 1795: 		$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 1796: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 1797: 		$form{'rndseed'}=$rndseed;
 1798: 		$resources_printed .=$urlp.':';
 1799: 		$texversion=&ssi_with_retries($urlp, $ssi_retry_count, %form);
 1800: 	    }
 1801: 	    if((($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 1802: 		($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) && 
 1803: 	       ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library|page)$/)) {
 1804: 		#  Don't permanently modify %$form...
 1805: 		my %answerform = %form;
 1806: 		$answerform{'grade_target'}='answer';
 1807: 		$answerform{'answer_output_mode'}='tex';
 1808: 		$answerform{'rndseed'}=$rndseed;
 1809: 		$answerform{'problem_split'}=$parmhash{'problem_stream_switch'};
 1810: 		if ($urlp=~/\/res\//) {$env{'request.state'}='published';}
 1811: 		$resources_printed .= $urlp.':';
 1812: 		my $answer=&ssi_with_retries($urlp, $ssi_retry_count, %answerform);
 1813: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 1814: 		    $texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 1815: 		} else {
 1816: 		    # If necessary, encapsulate answer in minipage:
 1817: 		    
 1818: 		    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 1819: 		    my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 1820: 		    $title = &Apache::lonxml::latex_special_symbols($title);
 1821: 		    my $body ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 1822: 		    $body.=&path_to_problem($urlp,$LaTeXwidth);
 1823: 		    $body.='\vskip 1 mm '.$answer.'\end{document}';
 1824: 		    $body = &encapsulate_minipage($body);
 1825: 		    $texversion.=$body;
 1826: 		}
 1827: 	    }
 1828: 	    $texversion = &latex_header_footer_remove($texversion);
 1829: 
 1830: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 1831: 		$texversion=&IndexCreation($texversion,$urlp);
 1832: 	    }
 1833: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 1834: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
 1835: 	    }
 1836: 	    $result.=$texversion;
 1837: 
 1838: 	} elsif ($urlp=~/\.(sequence|page)$/) {
 1839:  
 1840: 	    # header:
 1841: 
 1842: 	    $result.='\strut\newline\noindent Sequence/page '.$urlp.'\strut\newline\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\newline\noindent ';
 1843: 
 1844: 	    # IF sequence, recurse:
 1845: 	    
 1846: 	    if ($urlp =~ /\.sequence$/) {
 1847: 		my $sequence_url = $urlp;
 1848: 		my $domain       = $env{'user.domain'};	# Constr. space only on local
 1849: 		my $user         = $env{'user.name'};
 1850: 
 1851: 		$sequence_url    =~ s/^\/res\/$domain/\/home/;
 1852: 		$sequence_url    =~ s/^(\/home\/$user)/$1\/public_html/;
 1853: #		$sequence_url    =~ s|\/~([^\/]+)\/|\/home\/$1\/public_html\/|;
 1854: 		$result .= &print_construction_sequence($sequence_url, 
 1855: 							$helper, %form, 
 1856: 							$LaTeXwidth);
 1857: 	    }
 1858: 	}
 1859: 	elsif ($urlp =~ /\.pdf$/i) {
 1860: 	    my $texversion;
 1861: 	    if ($member != 0) {
 1862: 		$texversion .= '\cleardoublepage';
 1863: 	    }
 1864: 
 1865: 	    $texversion .= &include_pdf($urlp);
 1866: 	    $texversion = &latex_header_footer_remove($texversion);
 1867: 	    if ($member != $#order) {
 1868: 		$texversion .= '\\ \cleardoublepage';
 1869: 	    }
 1870: 	    
 1871: 	    $result .= $texversion;
 1872: 	}
 1873:     }
 1874:     if ($helper->{VARS}->{'construction'} eq '1') {$result=~s/(\\begin{document})/$1 \\fbox\{RANDOM SEED IS $rndseed\} /;}
 1875:     return $result;
 1876: }
 1877: 
 1878: sub output_data {
 1879:     my ($r,$helper,$rparmhash) = @_;
 1880:     my %parmhash = %$rparmhash;
 1881:     $ssi_error = 0;		# This will be set nonzero by failing ssi's.
 1882:     $resources_printed = '';
 1883:     $font_size = $helper->{'VARS'}->{'fontsize'};
 1884:     my $do_postprocessing = 1;
 1885:     my $js = <<ENDPART;
 1886: <script type="text/javascript">
 1887:     var editbrowser;
 1888:     function openbrowser(formname,elementname,only,omit) {
 1889:         var url = '/res/?';
 1890:         if (editbrowser == null) {
 1891:             url += 'launch=1&';
 1892:         }
 1893:         url += 'catalogmode=interactive&';
 1894:         url += 'mode=parmset&';
 1895:         url += 'form=' + formname + '&';
 1896:         if (only != null) {
 1897:             url += 'only=' + only + '&';
 1898:         } 
 1899:         if (omit != null) {
 1900:             url += 'omit=' + omit + '&';
 1901:         }
 1902:         url += 'element=' + elementname + '';
 1903:         var title = 'Browser';
 1904:         var options = 'scrollbars=1,resizable=1,menubar=0';
 1905:         options += ',width=700,height=600';
 1906:         editbrowser = open(url,title,options,'1');
 1907:         editbrowser.focus();
 1908:     }
 1909: </script>
 1910: ENDPART
 1911: 
 1912: 
 1913:     # Breadcrumbs
 1914:     #FIXME: Choose better/different breadcrumbs?!? Links?
 1915:     my $brcrum = [{'href' => '',
 1916:                    'text' => 'Helper'}, #FIXME: Different origin possible than print out helper?
 1917:                   {'href' => '',
 1918:                    'text' => 'Preparing Printout'}];
 1919: 
 1920:     my $start_page  = &Apache::loncommon::start_page('Preparing Printout',
 1921:                                                      $js,
 1922:                                                      {'bread_crumbs' => $brcrum,});
 1923:     my $msg = &mt('Please stand by while processing your print request, this may take some time ...');
 1924: 
 1925:     $r->print($start_page."\n<p>\n$msg\n</p>\n");
 1926: 
 1927:     # fetch the pagebreaks and store them in the course environment
 1928:     # The page breaks will be pulled into the hash %page_breaks which is
 1929:     # indexed by symb and contains 1's for each break.
 1930: 
 1931:     $env{'form.pagebreaks'}  = $helper->{'VARS'}->{'FINISHPAGE'};
 1932:     $env{'form.lastprinttype'} = $helper->{'VARS'}->{'PRINT_TYPE'}; 
 1933:     &Apache::loncommon::store_course_settings('print',
 1934: 					      {'pagebreaks'    => 'scalar',
 1935: 					       'lastprinttype' => 'scalar'});
 1936: 
 1937:     my %page_breaks  = &get_page_breaks($helper);
 1938: 
 1939:     my $format_from_helper = $helper->{'VARS'}->{'FORMAT'};
 1940:     my ($result,$selectionmade) = ('','');
 1941:     my $number_of_columns = 1; #used only for pages to determine the width of the cell
 1942:     my @temporary_array=split /\|/,$format_from_helper;
 1943:     my ($laystyle,$numberofcolumns,$papersize,$pdfFormFields)=@temporary_array;
 1944: 
 1945:     $laystyle = &map_laystyle($laystyle);
 1946:     my ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$laystyle,$numberofcolumns);
 1947:     my $assignment =  $env{'form.assignment'};
 1948:     my $LaTeXwidth=&recalcto_mm($textwidth); 
 1949:     my @print_array=();
 1950:     my @student_names=();
 1951: 
 1952:      
 1953:     #  Common settings for the %form has:
 1954:     # In some cases these settings get overriddent by specific cases, but the
 1955:     # settings are common enough to make it worthwhile factoring them out
 1956:     # here.
 1957:     #
 1958:     my %form;
 1959:     $form{'grade_target'} = 'tex';
 1960:     $form{'textwidth'}    = &get_textwidth($helper, $LaTeXwidth);
 1961:     $form{'pdfFormFields'} = $pdfFormFields;
 1962: 
 1963:     # If form.showallfoils is set, then request all foils be shown:
 1964:     # privilege will be enforced both by not allowing the 
 1965:     # check box selecting this option to be presnt unless it's ok,
 1966:     # and by lonresponse's priv. check.
 1967:     # The if is here because lonresponse.pm only cares that
 1968:     # showallfoils is defined, not what the value is.
 1969: 
 1970:     if ($helper->{'VARS'}->{'showallfoils'} eq "1") { 
 1971: 	$form{'showallfoils'} = $helper->{'VARS'}->{'showallfoils'};
 1972:     }
 1973:     
 1974:     if ($helper->{'VARS'}->{'style_file'}=~/\w/) {
 1975: 	&Apache::lonnet::appenv({'construct.style' =>
 1976: 				$helper->{'VARS'}->{'style_file'}});
 1977:     } elsif ($env{'construct.style'}) {
 1978: 	&Apache::lonnet::delenv('construct.style');
 1979:     }
 1980: 
 1981: 
 1982:     if ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'current_document') {
 1983:       #-- single document - problem, page, html, xml, ...
 1984: 	my ($currentURL,$cleanURL);
 1985: 
 1986: 	if ($helper->{'VARS'}->{'construction'} ne '1') {
 1987:             #prints published resource
 1988: 	    $currentURL=$helper->{'VARS'}->{'postdata'};
 1989: 	    $cleanURL=&Apache::lonenc::check_decrypt($currentURL);
 1990: 	} else {
 1991: 
 1992:             #prints resource from the construction space
 1993: 	    $currentURL='/'.$helper->{'VARS'}->{'filename'};
 1994: 	    if ($currentURL=~/([^?]+)/) {$currentURL=$1;}
 1995: 	    $cleanURL=$currentURL;
 1996: 	}
 1997: 	$selectionmade = 1;
 1998: 	if ($cleanURL!~m|^/adm/|
 1999: 	    && $cleanURL=~/\.(problem|exam|quiz|assess|survey|form|library|xml|html|htm|xhtml|xhtm)$/) {
 2000: 	    my $rndseed=time;
 2001: 	    my $texversion='';
 2002: 	    if ($helper->{'VARS'}->{'ANSWER_TYPE'} ne 'only') {
 2003: 		my %moreenv;
 2004: 		$moreenv{'request.filename'}=$cleanURL;
 2005:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {$form{'problemtype'}='exam';}
 2006: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2007: 		$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 2008: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2009: 		$form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 2010: 		$form{'print_annotations'}=$helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 2011: 		if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes') ||
 2012: 		    ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes')) {
 2013: 		    $form{'problem_split'}='yes';
 2014: 		}
 2015: 		if ($helper->{'VARS'}->{'curseed'}) {
 2016: 		    $rndseed=$helper->{'VARS'}->{'curseed'};
 2017: 		}
 2018: 		$form{'rndseed'}=$rndseed;
 2019: 		&Apache::lonnet::appenv(\%moreenv);
 2020: 
 2021: 		&Apache::lonxml::clear_problem_counter();
 2022: 
 2023: 		$resources_printed .= $currentURL.':';
 2024: 		$texversion.=&ssi_with_retries($currentURL,$ssi_retry_count, %form);
 2025: 
 2026: 		#  Add annotations if required:
 2027: 	    
 2028: 		&Apache::lonxml::clear_problem_counter();
 2029: 
 2030: 		&Apache::lonnet::delenv('request.filename');
 2031: 	    }
 2032: 	    # current document with answers.. no need to encap in minipage
 2033: 	    #  since there's only one answer.
 2034: 
 2035: 	    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2036: 	       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2037: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2038: 		$form{'grade_target'}='answer';
 2039: 		$form{'answer_output_mode'}='tex';
 2040: 		$form{'rndseed'}=$rndseed;
 2041:                 if ($helper->{'VARS'}->{'probstatus'} eq 'exam') {
 2042: 		    $form{'problemtype'}='exam';
 2043: 		}
 2044: 		$resources_printed .= $currentURL.':';
 2045: 		my $answer=&ssi_with_retries($currentURL,$ssi_retry_count, %form);
 2046: 		
 2047: 
 2048: 		if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2049: 		    $texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 2050: 		} else {
 2051: 		    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2052: 		    if ($helper->{'VARS'}->{'construction'} ne '1') {
 2053: 			my $title = &Apache::lonnet::gettitle($helper->{'VARS'}->{'symb'});
 2054: 			$title = &Apache::lonxml::latex_special_symbols($title);
 2055: 			$texversion.='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2056: 			$texversion.=&path_to_problem($cleanURL,$LaTeXwidth);
 2057: 		    } else {
 2058: 			$texversion.='\vskip 0 mm \noindent\textbf{Prints from construction space - there is no title.}\vskip 0 mm ';
 2059: 			my $URLpath=$cleanURL;
 2060: 			$URLpath=~s/~([^\/]+)/public_html\/$1\/$1/;
 2061: 			$texversion.=&path_to_problem($URLpath,$LaTeXwidth);
 2062: 		    }
 2063: 		    $texversion.='\vskip 1 mm '.$answer.'\end{document}';
 2064: 		}
 2065: 
 2066: 
 2067: 		
 2068: 
 2069: 	    
 2070: 	    }
 2071: 	    # Print annotations.
 2072: 
 2073: 
 2074: 	    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2075: 		my $annotation .= &annotate($currentURL);
 2076: 		$texversion =~ s/(\\keephidden{ENDOFPROBLEM})/$annotation$1/;
 2077: 	    }
 2078: 
 2079: 
 2080: 	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 2081: 		$texversion=&IndexCreation($texversion,$currentURL);
 2082: 	    }
 2083: 	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 2084: 		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$currentURL| \\strut\\\\\\strut /;
 2085: 
 2086: 	    }
 2087: 	    $result .= $texversion;
 2088: 	    if ($currentURL=~m/\.page\s*$/) {
 2089: 		($result,$number_of_columns) = &page_cleanup($result);
 2090: 	    }
 2091:         } elsif ($cleanURL!~m|^/adm/|
 2092: 		 && $currentURL=~/\.(sequence|page)$/ && $helper->{'VARS'}->{'construction'} eq '1') {
 2093:             #printing content of sequence from the construction space	
 2094: 
 2095: 
 2096: 	    $currentURL=~s|\/~([^\/]+)\/|\/home\/$1\/public_html\/|;
 2097: #	    $result .= &print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2098: 	    $result .= &print_construction_sequence($currentURL, $helper, %form,
 2099: 						    $LaTeXwidth);
 2100: 	    $result .= '\end{document}';  
 2101: 	    if (!($result =~ /\\begin\{document\}/)) {
 2102: 		$result = &print_latex_header() . $result;
 2103: 	    }
 2104: 	    # End construction space sequence.
 2105: 	} elsif ($cleanURL=~/\/(smppg|syllabus|aboutme|bulletinboard)$/) { 
 2106: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2107: 		if ($currentURL=~/\/syllabus$/) {$currentURL=~s/\/res//;}
 2108: 		$resources_printed .= $currentURL.':';
 2109: 		my $texversion = &print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2110: 		$texversion .= &ssi_with_retries($currentURL, $ssi_retry_count, %form);
 2111: 		if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2112: 		    my $annotation = &annotate($currentURL);
 2113: 		    $texversion    =~ s/(\\end{document})/$annotation$1/;
 2114: 		}
 2115: 		$result .= $texversion;
 2116: 	} elsif ($cleanURL =~/\.tex$/) {
 2117: 	    # For this sort of print of a single LaTeX file,
 2118: 	    # We can just print the LaTeX file as it is uninterpreted in any way:
 2119: 	    #
 2120: 
 2121: 	    $result = &fetch_raw_resource($currentURL);
 2122: 	    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2123: 		my $annotation = &annotate($currentURL);
 2124: 		$result =~ s/(\\end{document})/$annotation$1/;
 2125: 	    }
 2126: 
 2127: 	    $do_postprocessing = 0; # Don't massage the result.
 2128: 
 2129: 	} elsif ($cleanURL =~ /\.pdf$/i) {
 2130: 	    $result .= &include_pdf($cleanURL);
 2131: 	    $result .= '\end{document}';
 2132: 	} elsif ($cleanURL =~ /\.page$/i) { #  Print page in non construction space contexts.
 2133: 
 2134: 	    # Determine the set of resources in the map of the page:
 2135: 
 2136: 	    my $navmap         =  Apache::lonnavmaps::navmap->new();
 2137: 	    my @page_resources =  $navmap->retrieveResources($cleanURL);
 2138: 	    $result           .=  &print_page_in_course($helper, $rparmhash,
 2139: 							$cleanURL, \@page_resources);
 2140: 
 2141:        
 2142: 	} else {
 2143: 	    &Apache::lonnet::logthis("Unsupported type handler");
 2144: 	    $result.=&unsupported($currentURL,$helper->{'VARS'}->{'LATEX_TYPE'},
 2145: 				  $helper->{'VARS'}->{'symb'});
 2146: 	}
 2147:     } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems')       or
 2148: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_in_page') or
 2149: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_resources_in_page') or
 2150:              ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_pages') or
 2151:              ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems')       or
 2152: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_resources')      or # BUGBUG
 2153: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'select_sequences') 
 2154: 	     ) { 
 2155: 
 2156: 
 2157:         #-- produce an output string
 2158: 	if (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems')  or
 2159: 	    ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_in_page') ) {
 2160: 	    $selectionmade = 2;
 2161: 	} elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_pages') or
 2162: 		 ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_resources_in_page'))
 2163: 	{
 2164: 	    $selectionmade = 3;
 2165: 	} elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems') 
 2166: 		 ) {
 2167: 	    $selectionmade = 4;
 2168: 	} elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_resources') {  #BUGBUG
 2169: 	    $selectionmade = 4;
 2170: 	} elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'select_sequences') {
 2171: 	    $selectionmade = 7;
 2172: 	}
 2173: 	$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2174: 	$form{'suppress_tries'}=$parmhash{'suppress_tries'};
 2175: 	$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2176: 	$form{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 2177: 	$form{'print_annotations'} = $helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 2178: 	if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes')   ||
 2179: 	    ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') ) {
 2180: 	    $form{'problem_split'}='yes';
 2181: 	}
 2182: 	my $flag_latex_header_remove = 'NO';
 2183: 	my $flag_page_in_sequence = 'NO';
 2184: 	my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 2185: 	my $prevassignment='';
 2186: 
 2187: 	&Apache::lonxml::clear_problem_counter();
 2188: 
 2189: 	my $pbreakresources = keys %page_breaks;
 2190: 	for (my $i=0;$i<=$#master_seq;$i++) {
 2191: 
 2192: 	    &Apache::lonenc::reset_enc();
 2193: 
 2194: 
 2195: 	    # Note due to document structure, not allowed to put \newpage
 2196: 	    # prior to the first resource
 2197: 
 2198: 	    if (defined $page_breaks{$master_seq[$i]}) {
 2199: 		if($i != 0) {
 2200: 		    $result.="\\newpage\n";
 2201: 		}
 2202: 	    }
 2203: 	    my ($sequence,$middle_thingy,$urlp)=&Apache::lonnet::decode_symb($master_seq[$i]);
 2204: 	    $urlp=&Apache::lonnet::clutter($urlp);
 2205: 	    $form{'symb'}=$master_seq[$i];
 2206: 
 2207: 	    my $assignment=&Apache::lonxml::latex_special_symbols(&Apache::lonnet::gettitle($sequence),'header'); #title of the assignment which contains this problem
 2208: 
 2209: 	    if ($selectionmade==7) {$helper->{VARS}->{'assignment'}=$assignment;}
 2210: 	    if ($i==0) {$prevassignment=$assignment;}
 2211: 	    my $texversion='';
 2212: 	    if ($urlp!~m|^/adm/|
 2213: 		&& $urlp=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 2214: 		$resources_printed .= $urlp.':';
 2215: 		&Apache::lonxml::remember_problem_counter();
 2216: 		$texversion.=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});  # RF
 2217: 		$texversion.=&ssi_with_retries($urlp, $ssi_retry_count, %form);
 2218: 		if ($urlp=~/\.page$/) {
 2219: 		    ($texversion,my $number_of_columns_page) = &page_cleanup($texversion);
 2220: 		    if ($number_of_columns_page > $number_of_columns) {$number_of_columns=$number_of_columns_page;} 
 2221: 		    $texversion =~ s/\\end{document}\d*/\\end{document}/;
 2222: 		    $flag_page_in_sequence = 'YES';
 2223: 		} 
 2224: 
 2225: 		if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2226: 		   ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2227: 		    #  Don't permanently pervert the %form hash
 2228: 		    my %answerform = %form;
 2229: 		    $answerform{'grade_target'}='answer';
 2230: 		    $answerform{'answer_output_mode'}='tex';
 2231: 		    $resources_printed .= $urlp.':';
 2232: 
 2233: 		    &Apache::lonxml::restore_problem_counter();
 2234: 		    my $answer=&ssi_with_retries($urlp, $ssi_retry_count, %answerform);
 2235: 
 2236: 		    if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2237: 			$texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 2238: 		    } else {
 2239: 			if ($urlp=~/\.(problem|exam|quiz|assess|survey|form|library)$/) {
 2240: 			    $texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2241: 			    $texversion =~ s/\\begin{document}//;
 2242: 			    my $title = &Apache::lonnet::gettitle($master_seq[$i]);
 2243: 			    $title = &Apache::lonxml::latex_special_symbols($title);
 2244: 			    my $body ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2245: 			    $body   .= &path_to_problem ($urlp,$LaTeXwidth);
 2246: 			    $body   .='\vskip 1 mm '.$answer;
 2247: 			    $body    = &encapsulate_minipage($body);
 2248: 			    $texversion .= $body;
 2249: 			} else {
 2250: 			    $texversion='';
 2251: 			}
 2252: 		    }
 2253: 
 2254: 		}
 2255: 		if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2256: 		    my $annotation .= &annotate($urlp);
 2257: 		    $texversion =~ s/(\\keephidden{ENDOFPROBLEM})/$annotation$1/;
 2258: 		}
 2259: 
 2260: 		if ($flag_latex_header_remove ne 'NO') {
 2261: 		    $texversion = &latex_header_footer_remove($texversion);
 2262: 		} else {
 2263: 		    $texversion =~ s/\\end{document}//;
 2264: 		}
 2265: 		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 2266: 		    $texversion=&IndexCreation($texversion,$urlp);
 2267: 		}
 2268: 		if (($selectionmade == 4) and ($assignment ne $prevassignment)) {
 2269: 		    my $name = &get_name();
 2270: 		    my $courseidinfo = &get_course();
 2271: 		    $prevassignment=$assignment;
 2272: 		    my $header_text = $parmhash{'print_header_format'};
 2273: 		    $header_text    = &format_page_header($textwidth, $header_text,
 2274: 							  $assignment, 
 2275: 							  $courseidinfo, 
 2276: 							  $name);
 2277: 
 2278: 		    if ($numberofcolumns eq '1') {
 2279: 			$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\lhead{'.$header_text.'}} \vskip 5 mm ';
 2280: 		    } else {
 2281: 			$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\fancyhead[LO]{'.$header_text.'}} \vskip 5 mm ';
 2282: 		    }			
 2283: 		}
 2284: 		$result .= $texversion;
 2285: 		$flag_latex_header_remove = 'YES';   
 2286: 	    } elsif ($urlp=~/\/(smppg|syllabus|aboutme|bulletinboard)$/) { 
 2287: 		$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2288: 		if ($urlp=~/\/syllabus$/) {$urlp=~s/\/res//;}
 2289: 		$resources_printed .= $urlp.':';
 2290: 		my $texversion = &print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2291: 		$texversion .= &ssi_with_retries($urlp, $ssi_retry_count, %form);
 2292: 		if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2293: 		    my $annotation = &annotate($urlp);
 2294: 		    $texversion =~ s/(\\end{document)/$annotation$1/;
 2295: 		}
 2296: 
 2297: 		if ($flag_latex_header_remove ne 'NO') {
 2298: 		    $texversion = &latex_header_footer_remove($texversion);
 2299: 		} else {	
 2300: 		    $texversion =~ s/\\end{document}/\\vskip 0\.5mm\\noindent\\makebox\[\\textwidth\/\$number_of_columns\]\[b\]\{\\hrulefill\}/;
 2301: 		}
 2302: 		$result .= $texversion;
 2303: 		$flag_latex_header_remove = 'YES'; 
 2304: 	    } elsif ($urlp=~ /\.pdf$/i) {
 2305: 		if ($i > 0) {
 2306: 		    $result .= '\cleardoublepage';
 2307: 		}
 2308: 		$result .= &include_pdf($urlp);
 2309: 		if ($i != $#master_seq) {
 2310: 		    if ($numberofcolumns eq '1') {
 2311: 			$result .= '\newpage';
 2312: 		    } else {
 2313: 			# the \\'s seem to be needed to let LaTeX know there's something
 2314: 			# on the page since LaTeX seems to not like to clear an empty page.
 2315: 			#
 2316: 			$result .= '\\ \cleardoublepage';
 2317: 		    }
 2318: 		}
 2319: 		$flag_latex_header_remove = 'YES';
 2320: 
 2321: 	    } else {
 2322: 		$texversion=&unsupported($urlp,$helper->{'VARS'}->{'LATEX_TYPE'},
 2323: 					 $master_seq[$i]);
 2324: 		if ($flag_latex_header_remove ne 'NO') {
 2325: 		    $texversion = &latex_header_footer_remove($texversion);
 2326: 		} else {
 2327: 		    $texversion =~ s/\\end{document}//;
 2328: 		}
 2329: 		$result .= $texversion;
 2330: 		$flag_latex_header_remove = 'YES';   
 2331: 	    }	    
 2332: 	    if (&Apache::loncommon::connection_aborted($r)) { 
 2333: 		last; 
 2334: 	    }
 2335: 	}
 2336: 	&Apache::lonxml::clear_problem_counter();
 2337: 	if ($flag_page_in_sequence eq 'YES') {
 2338: 	    $result =~ s/\\usepackage{calc}/\\usepackage{calc}\\usepackage{longtable}/;
 2339: 	}	
 2340: 	$result .= '\end{document}';
 2341:      } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_students') ||
 2342: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_students_from_page') ||
 2343: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems_students') ||
 2344: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_students')){
 2345: 
 2346: 
 2347:      #-- prints assignments for whole class or for selected students  
 2348: 	 my $type;
 2349: 	 if (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_students') ||
 2350: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_students_from_page') ||
 2351: 	     ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems_students') ) {
 2352: 	     $selectionmade=5;
 2353: 	     $type='problems';
 2354: 	 } elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_students') {
 2355: 	     $selectionmade=8;
 2356: 	     $type='resources';
 2357: 	 }
 2358: 	 my @students=split /\|\|\|/, $helper->{'VARS'}->{'STUDENTS'};
 2359: 	 #   The normal sort order is by section then by students within the
 2360: 	 #   section. If the helper var student_sort is 1, then the user has elected
 2361: 	 #   to override this and output the students by name.
 2362: 	 #    Each element of the students array is of the form:
 2363: 	 #       username:domain:section:last, first:status
 2364: 	 #    
 2365: 	 #  Note that student sort is not compatible with printing 
 2366: 	 #  1 section per pdf...so that setting overrides.
 2367: 	 #   
 2368: 	 if (($helper->{'VARS'}->{'student_sort'}    eq 1)  && 
 2369: 	     ($helper->{'VARS'}->{'SPLIT_PDFS'} ne "sections")) {
 2370: 	     @students = sort compare_names  @students;
 2371: 	 }
 2372: 	 &adjust_number_to_print($helper);
 2373: 
 2374:          if ($helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq '0' ||
 2375: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq 'all' ) {
 2376: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'}=$#students+1;
 2377: 	 }
 2378: 	 # If we are splitting on section boundaries, we need 
 2379: 	 # to remember that in split_on_sections and 
 2380: 	 # print all of the students in the list.
 2381: 	 #
 2382: 	 my $split_on_sections = 0;
 2383: 	 if ($helper->{'VARS'}->{'NUMBER_TO_PRINT'} eq 'section') {
 2384: 	     $split_on_sections = 1;
 2385: 	     $helper->{'VARS'}->{'NUMBER_TO_PRINT'} = $#students+1;
 2386: 	 }
 2387: 	 my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 2388: 
 2389: 	 #loop over students
 2390: 
 2391:  	 my $flag_latex_header_remove = 'NO';
 2392: 	 my %moreenv;
 2393:          $moreenv{'instructor_comments'}='hide';
 2394: 	 $moreenv{'textwidth'}=&get_textwidth($helper,$LaTeXwidth);
 2395: 	 $moreenv{'print_discussions'}=$helper->{'VARS'}->{'PRINT_DISCUSSIONS'};
 2396: 	 $moreenv{'print_annotations'} = $helper->{'VARS'}->{'PRINT_ANNOTATIONS'};
 2397: 	 $moreenv{'problem_split'}    = $parmhash{'problem_stream_switch'};
 2398: 	 $moreenv{'suppress_tries'}   = $parmhash{'suppress_tries'};
 2399: 	 if (($helper->{'VARS'}->{'PRINT_DISCUSSIONS'} eq 'yes')  ||
 2400: 	     ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes')) {
 2401: 	     $moreenv{'problem_split'}='yes';
 2402: 	 }
 2403: 	 my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Print Status','Class Print Status',$#students+1,'inline','75');
 2404: 	 my $student_counter=-1;
 2405: 	 my $i = 0;
 2406: 	 my $last_section = (split(/:/,$students[0]))[2];
 2407: 	 foreach my $person (@students) {
 2408: 
 2409:              my $duefile="/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.due";
 2410: 	     if (-e $duefile) {
 2411: 		 my $temp_file = Apache::File->new('>>'.$duefile);
 2412: 		 print $temp_file "1969\n";
 2413: 	     }
 2414: 	     $student_counter++;
 2415: 	     if ($split_on_sections) {
 2416: 		 my $this_section = (split(/:/,$person))[2];
 2417: 		 if ($this_section ne $last_section) {
 2418: 		     $i++;
 2419: 		     $last_section = $this_section;
 2420: 		 }
 2421: 	     } else {
 2422: 		 $i=int($student_counter/$helper->{'VARS'}{'NUMBER_TO_PRINT'});
 2423: 	     }
 2424: 	     my ($output,$fullname, $printed)=&print_resources($r,$helper,
 2425: 						     $person,$type,
 2426: 						     \%moreenv,\@master_seq,
 2427: 						     $flag_latex_header_remove,
 2428: 						     $LaTeXwidth);
 2429: 	     $resources_printed .= ":";
 2430: 	     $print_array[$i].=$output;
 2431: 	     $student_names[$i].=$person.':'.$fullname.'_END_';
 2432: 	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,&mt('last student').' '.$fullname);
 2433: 	     $flag_latex_header_remove = 'YES';
 2434: 	     if (&Apache::loncommon::connection_aborted($r)) { last; }
 2435: 	 }
 2436: 	 &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 2437: 	 $result .= $print_array[0].'  \end{document}';
 2438:      } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_anon')     ||
 2439: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_for_anon_page') ||
 2440: 	      ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'resources_for_anon')  ) { 
 2441: 	 my $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 2442: 	 my $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 2443: 	 my $num_todo=$helper->{'VARS'}->{'NUMBER_TO_PRINT_TOTAL'};
 2444: 	 my $code_name=$helper->{'VARS'}->{'ANON_CODE_STORAGE_NAME'};
 2445: 	 my $old_name=$helper->{'VARS'}->{'REUSE_OLD_CODES'};
 2446: 	 my $single_code = $helper->{'VARS'}->{'SINGLE_CODE'};
 2447: 	 my $selected_code = $helper->{'VARS'}->{'CODE_SELECTED_FROM_LIST'};
 2448: 
 2449: 	 my $code_option=$helper->{'VARS'}->{'CODE_OPTION'};
 2450:          my @lines = &Apache::grades::get_scantronformat_file();
 2451: 	 my ($code_type,$code_length)=('letter',6);
 2452: 	 foreach my $line (@lines) {
 2453: 	     my ($name,$type,$length) = (split(/:/,$line))[0,2,4];
 2454: 	     if ($name eq $code_option) {
 2455: 		 $code_length=$length;
 2456: 		 if ($type eq 'number') { $code_type = 'number'; }
 2457: 	     }
 2458: 	 }
 2459: 	 my %moreenv = ('textwidth' => &get_textwidth($helper,$LaTeXwidth));
 2460: 	 $moreenv{'problem_split'}    = $parmhash{'problem_stream_switch'};
 2461:          $moreenv{'instructor_comments'}='hide';
 2462: 	 my $seed=time+($$<<16)+($$);
 2463: 	 my @allcodes;
 2464: 	 if ($old_name) {
 2465: 	     my %result=&Apache::lonnet::get('CODEs',
 2466: 					     [$old_name,"type\0$old_name"],
 2467: 					     $cdom,$cnum);
 2468: 	     $code_type=$result{"type\0$old_name"};
 2469: 	     @allcodes=split(',',$result{$old_name});
 2470: 	     $num_todo=scalar(@allcodes);
 2471: 	 } elsif ($selected_code) { # Selection value is always numeric.
 2472: 	     $num_todo = 1;
 2473: 	     @allcodes = ($selected_code);
 2474: 	 } elsif ($single_code) {
 2475: 
 2476: 	     $num_todo    = 1;	# Unconditionally one code to do.
 2477: 	     # If an alpha code have to convert to numbers so it can be
 2478: 	     # converted back to letters again :-)
 2479: 	     #
 2480: 	     if ($code_type ne 'number') {
 2481: 		 $single_code = &letters_to_num($single_code);
 2482: 	     }
 2483: 	     @allcodes = ($single_code);
 2484: 	 } else {
 2485: 	     my %allcodes;
 2486: 	     srand($seed);
 2487: 	     for (my $i=0;$i<$num_todo;$i++) {
 2488: 		 $moreenv{'CODE'}=&get_CODE(\%allcodes,$i,$seed,$code_length,
 2489: 					    $code_type);
 2490: 	     }
 2491: 	     if ($code_name) {
 2492: 		 &Apache::lonnet::put('CODEs',
 2493: 				      {
 2494: 					$code_name =>join(',',keys(%allcodes)),
 2495: 					"type\0$code_name" => $code_type
 2496: 				      },
 2497: 				      $cdom,$cnum);
 2498: 	     }
 2499: 	     @allcodes=keys(%allcodes);
 2500: 	 }
 2501: 	 my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
 2502: 	 my ($type) = split(/_/,$helper->{'VARS'}->{'PRINT_TYPE'});
 2503: 	 &adjust_number_to_print($helper);
 2504: 	 my $number_per_page=$helper->{'VARS'}->{'NUMBER_TO_PRINT'};
 2505: 	 if ($number_per_page eq '0' || $number_per_page eq 'all') {
 2506: 	     $number_per_page=$num_todo;
 2507: 	 }
 2508: 	 my $flag_latex_header_remove = 'NO'; 
 2509: 	 my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Print Status','Class Print Status',$num_todo,'inline','75');
 2510: 	 my $count=0;
 2511: 	 foreach my $code (sort(@allcodes)) {
 2512: 	     my $file_num=int($count/$number_per_page);
 2513: 	     if ($code_type eq 'number') { 
 2514: 		 $moreenv{'CODE'}=$code;
 2515: 	     } else {
 2516: 		 $moreenv{'CODE'}=&num_to_letters($code);
 2517: 	     }
 2518: 	     my ($output,$fullname, $printed)=
 2519: 		 &print_resources($r,$helper,'anonymous',$type,\%moreenv,
 2520: 				  \@master_seq,$flag_latex_header_remove,
 2521: 				  $LaTeXwidth);
 2522: 	     $resources_printed .= ":";
 2523: 	     $print_array[$file_num].=$output;
 2524: 	     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 2525: 				       &mt('last assignment').' '.$fullname);
 2526: 	     $flag_latex_header_remove = 'YES';
 2527: 	     $count++;
 2528: 	     if (&Apache::loncommon::connection_aborted($r)) { last; }
 2529: 	 }
 2530: 	 &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 2531: 	 $result .= $print_array[0].'  \end{document}';
 2532:      } elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'problems_from_directory') {      
 2533:     #prints selected problems from the subdirectory 
 2534: 	$selectionmade = 6;
 2535:         my @list_of_files=split /\|\|\|/, $helper->{'VARS'}->{'FILES'};
 2536: 	@list_of_files=sort @list_of_files;
 2537: 	my $flag_latex_header_remove = 'NO'; 
 2538: 	my $rndseed=time;
 2539: 	if ($helper->{'VARS'}->{'curseed'}) {
 2540: 	    $rndseed=$helper->{'VARS'}->{'curseed'};
 2541: 	}
 2542: 	for (my $i=0;$i<=$#list_of_files;$i++) {
 2543: 
 2544: 	    &Apache::lonenc::reset_enc();
 2545: 
 2546: 	    my $urlp = $list_of_files[$i];
 2547: 	    $urlp=~s|//|/|;
 2548: 	    if ($urlp=~/\//) {
 2549: 		$form{'problem_split'}=$parmhash{'problem_stream_switch'};
 2550: 		$form{'rndseed'}=$rndseed;
 2551: 		if ($urlp =~ m|/home/([^/]+)/public_html|) {
 2552: 		    $urlp =~ s|/home/([^/]*)/public_html|/~$1|;
 2553: 		} else {
 2554: 		    $urlp =~ s|^$Apache::lonnet::perlvar{'lonDocRoot'}||;
 2555: 		}
 2556: 		$resources_printed .= $urlp.':';
 2557: 		my $texversion=&ssi_with_retries($urlp, $ssi_retry_count, %form);
 2558: 		if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2559: 		   ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2560: 		    #  Don't permanently pervert %form:
 2561: 		    my %answerform = %form;
 2562: 		    $answerform{'grade_target'}='answer';
 2563: 		    $answerform{'answer_output_mode'}='tex';
 2564: 		    $answerform{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2565: 		    $answerform{'rndseed'}=$rndseed;
 2566: 		    $resources_printed .= $urlp.':';
 2567: 		    my $answer=&ssi_with_retries($urlp, $ssi_retry_count, %answerform);
 2568: 		    if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2569: 			$texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 2570: 		    } else {
 2571: 			$texversion=&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2572: 			if ($helper->{'VARS'}->{'construction'} ne '1') {
 2573: 			    $texversion.='\vskip 0 mm \noindent ';
 2574: 			    $texversion.=&path_to_problem ($urlp,$LaTeXwidth);
 2575: 			} else {
 2576: 			    $texversion.='\vskip 0 mm \noindent\textbf{Prints from construction space - there is no title.}\vskip 0 mm ';
 2577: 			    my $URLpath=$urlp;
 2578: 			    $URLpath=~s/~([^\/]+)/public_html\/$1\/$1/;
 2579: 			    $texversion.=&path_to_problem ($URLpath,$LaTeXwidth);
 2580: 			}
 2581: 			$texversion.='\vskip 1 mm '.$answer.'\end{document}';
 2582: 		    }
 2583: 		}
 2584:                 #this chunk is responsible for printing the path to problem
 2585: 
 2586: 		my $newurlp=$urlp;
 2587: 		if ($newurlp=~/~/) {$newurlp=~s|\/~([^\/]+)\/|\/home\/$1\/public_html\/|;}
 2588: 		$newurlp=&path_to_problem($newurlp,$LaTeXwidth);
 2589: 		$texversion =~ s/(\\begin{minipage}{\\textwidth})/$1 $newurlp/;
 2590: 		if ($flag_latex_header_remove ne 'NO') {
 2591: 		    $texversion = &latex_header_footer_remove($texversion);
 2592: 		} else {
 2593: 		    $texversion =~ s/\\end{document}//;
 2594: 		}
 2595: 		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
 2596: 		    $texversion=&IndexCreation($texversion,$urlp);
 2597: 		}
 2598: 		if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
 2599: 		    $texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
 2600: 		    
 2601: 		}
 2602: 		$result .= $texversion;
 2603: 	    }
 2604: 	    $flag_latex_header_remove = 'YES';  
 2605: 	}
 2606: 	if ($helper->{VARS}->{'construction'} eq '1') {$result=~s/(\\typeout)/ RANDOM SEED IS $rndseed $1/;}
 2607: 	$result .= '\end{document}';      	
 2608:     }
 2609: #-------------------------------------------------------- corrections for the different page formats
 2610: 
 2611:     # Only post process if that has not been turned off e.g. by a raw latex resource.
 2612: 
 2613:     if ($do_postprocessing) {
 2614: 	$result = &page_format_transformation($papersize,$laystyle,$numberofcolumns,$helper->{'VARS'}->{'PRINT_TYPE'},$result,$helper->{VARS}->{'assignment'},$helper->{'VARS'}->{'TABLE_CONTENTS'},$helper->{'VARS'}->{'TABLE_INDEX'},$selectionmade);
 2615: 	$result = &latex_corrections($number_of_columns,$result,$selectionmade,
 2616: 				     $helper->{'VARS'}->{'ANSWER_TYPE'});
 2617: 	#if ($numberofcolumns == 1) {
 2618: 	$result =~ s/\\textwidth\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\textwidth= $helper->{'VARS'}->{'pagesize.width'} $helper->{'VARS'}->{'pagesize.widthunit'} /;
 2619: 	$result =~ s/\\textheight\s*=?\s*-?\d*\.?\d*\s*(cm|mm|in)/\\textheight $helper->{'VARS'}->{'pagesize.height'} $helper->{'VARS'}->{'pagesize.heightunit'} /;
 2620: 	$result =~ s/\\evensidemargin\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\evensidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
 2621: 	$result =~ s/\\oddsidemargin\s*=\s*-?\d*\.?\d*\s*(cm|mm|in)/\\oddsidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
 2622: 	#}
 2623:     }
 2624: 
 2625:     # Set URLback if this is a construction space print so we can provide
 2626:     # a link to the resource being edited.
 2627:     #
 2628: 
 2629:     my $URLback=''; #link to original document
 2630:     if ($helper->{'VARS'}->{'construction'} eq '1') {
 2631: 	#prints resource from the construction space
 2632: 	$URLback='/'.$helper->{'VARS'}->{'filename'};
 2633: 	if ($URLback=~/([^?]+)/) {
 2634: 	    $URLback=$1;
 2635: 	    $URLback=~s|^/~|/priv/|;
 2636: 	}
 2637:     }
 2638:     #
 2639:     # Final adjustment of the font size:
 2640:     #
 2641: 
 2642:     $result = set_font_size($result);
 2643: 
 2644: #-- writing .tex file in prtspool 
 2645:     my $temp_file;
 2646:     my $identifier = &Apache::loncommon::get_cgi_id();
 2647:     my $filename = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout_$identifier.tex";
 2648:     if (!($#print_array>0)) { 
 2649:        unless ($temp_file = Apache::File->new('>'.$filename)) {
 2650: 	  $r->log_error("Couldn't open $filename for output $!");
 2651: 	  return SERVER_ERROR; 
 2652:        }
 2653:        print $temp_file $result;
 2654:        my $begin=index($result,'\begin{document}',0);
 2655:        my $inc=substr($result,0,$begin+16); 
 2656:     } else {
 2657:        my $begin=index($result,'\begin{document}',0);
 2658:        my $inc=substr($result,0,$begin+16);
 2659:        for (my $i=0;$i<=$#print_array;$i++) {
 2660: 	  if ($i==0) {
 2661: 	      $print_array[$i]=$result;
 2662: 	  } else {
 2663: 	      $print_array[$i].='\end{document}';
 2664: 	      $print_array[$i] = 
 2665: 		&latex_corrections($number_of_columns,$print_array[$i],
 2666: 				   $selectionmade, 
 2667: 				   $helper->{'VARS'}->{'ANSWER_TYPE'});
 2668: 	    
 2669: 	      my $anobegin=index($print_array[$i],'\setcounter{page}',0);
 2670: 	      substr($print_array[$i],0,$anobegin)='';
 2671: 	      $print_array[$i]=$inc.$print_array[$i];
 2672: 	  }
 2673: 	  my $temp_file;
 2674: 	  my $newfilename=$filename;
 2675: 	  my $num=$i+1;
 2676: 	  $newfilename =~s/\.tex$//; 
 2677: 	  $newfilename=sprintf("%s_%03d.tex",$newfilename, $num);
 2678: 	  unless ($temp_file = Apache::File->new('>'.$newfilename)) {
 2679: 	      $r->log_error("Couldn't open $newfilename for output $!");
 2680: 	      return SERVER_ERROR; 
 2681: 	  }
 2682: 	  print $temp_file $print_array[$i];
 2683:        }
 2684:     }
 2685:     my $student_names='';
 2686:     if ($#print_array>0) {
 2687:         for (my $i=0;$i<=$#print_array;$i++) {
 2688:   	  $student_names.=$student_names[$i].'_ENDPERSON_';
 2689: 	}
 2690:     } else {
 2691: 	if ($#student_names>-1) {
 2692: 	   $student_names=$student_names[0].'_ENDPERSON_';
 2693: 	} else {
 2694:            my $fullname = &get_name($env{'user.name'},$env{'user.domain'});
 2695: 	   $student_names=join(':',$env{'user.name'},$env{'user.domain'},
 2696: 				    $env{'request.course.sec'},$fullname).
 2697: 					'_ENDPERSON_'.'_END_';
 2698: 	}
 2699:      }
 2700: 	
 2701:      # logic for now is too complex to trace if this has been defined
 2702:      #  yet.
 2703:      my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2704:      my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2705:      &Apache::lonnet::appenv({'cgi.'.$identifier.'.file'   => $filename,
 2706: 				'cgi.'.$identifier.'.layout'  => $laystyle,
 2707: 				'cgi.'.$identifier.'.numcol'  => $numberofcolumns,
 2708: 				'cgi.'.$identifier.'.paper'  => $papersize,
 2709: 				'cgi.'.$identifier.'.selection' => $selectionmade,
 2710: 				'cgi.'.$identifier.'.tableofcontents' => $helper->{'VARS'}->{'TABLE_CONTENTS'},
 2711: 				'cgi.'.$identifier.'.tableofindex' => $helper->{'VARS'}->{'TABLE_INDEX'},
 2712: 				'cgi.'.$identifier.'.role' => $perm{'pav'},
 2713: 				'cgi.'.$identifier.'.numberoffiles' => $#print_array,
 2714: 				'cgi.'.$identifier.'.studentnames' => $student_names,
 2715: 				'cgi.'.$identifier.'.backref' => $URLback,});
 2716:     &Apache::lonnet::appenv({"cgi.$identifier.user"    => $env{'user.name'},
 2717: 				"cgi.$identifier.domain"  => $env{'user.domain'},
 2718: 				"cgi.$identifier.courseid" => $cnum, 
 2719: 				"cgi.$identifier.coursedom" => $cdom, 
 2720: 				"cgi.$identifier.resources" => $resources_printed});
 2721: 	
 2722:     my $end_page = &Apache::loncommon::end_page();
 2723:     my $continue_text = &mt('Continue');
 2724:     # If there's been an unrecoverable SSI error, report it to the user
 2725:     if ($ssi_error) {
 2726:         my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
 2727:         $r->print('<br /><p class="LC_error">'.&mt('An unrecoverable network error occurred:').'</p><p>'.
 2728:                   &mt('At least one of the resources you chose to print could not be rendered due to an unrecoverable error when communicating with a server:').
 2729:                   '<br />'.$ssi_last_error_resource.'<br />'.$ssi_last_error.
 2730:                   '</p><p>'.&mt('You can continue using the link provided below, but make sure to carefully inspect your output file! The errors will be marked in the file.').'<br />'.
 2731:                   &mt('You may be able to reprint the individual resources for which this error occurred, as the issue may be temporary.').
 2732:                   '<br />'.&mt('If the error persists, please contact the [_1] for assistance.',$helpurl).'</p><p>'.
 2733:                   &mt('We apologize for the inconvenience.').'</p>'.
 2734:                   '<a href="/cgi-bin/printout.pl?'.$identifier.'">'.$continue_text.'</a>'.$end_page);
 2735:     } else {
 2736: 	$r->print(<<FINALEND);
 2737: <br />
 2738: <meta http-equiv="Refresh" content="0; url=/cgi-bin/printout.pl?$identifier" />
 2739: <a href="/cgi-bin/printout.pl?$identifier">$continue_text</a>
 2740: $end_page
 2741: FINALEND
 2742:     }                                     # endif ssi errors.
 2743: }
 2744: 
 2745: 
 2746: sub get_CODE {
 2747:     my ($all_codes,$num,$seed,$size,$type)=@_;
 2748:     my $max='1'.'0'x$size;
 2749:     my $newcode;
 2750:     while(1) {
 2751: 	$newcode=sprintf("%0".$size."d",int(rand($max)));
 2752: 	if (!exists($$all_codes{$newcode})) {
 2753: 	    $$all_codes{$newcode}=1;
 2754: 	    if ($type eq 'number' ) {
 2755: 		return $newcode;
 2756: 	    } else {
 2757: 		return &num_to_letters($newcode);
 2758: 	    }
 2759: 	}
 2760:     }
 2761: }
 2762: 
 2763: sub print_resources {
 2764:     my ($r,$helper,$person,$type,$moreenv,$master_seq,$remove_latex_header,
 2765: 	$LaTeXwidth)=@_;
 2766:     my $current_output = ''; 
 2767:     my $printed = '';
 2768:     my ($username,$userdomain,$usersection) = split /:/,$person;
 2769:     my $fullname = &get_name($username,$userdomain);
 2770:     my $namepostfix = "\\\\";	# Both anon and not anon should get the same vspace.
 2771:     if ($person =~ 'anon') {
 2772: 	$namepostfix .="Name: ";
 2773: 	$fullname = "CODE - ".$moreenv->{'CODE'};
 2774:     }
 2775:     #  Fullname may have special latex characters that need \ prefixing:
 2776:     #
 2777: 
 2778:     my $i           = 0;
 2779:     #goes through all resources, checks if they are available for 
 2780:     #current student, and produces output   
 2781: 
 2782:     &Apache::lonxml::clear_problem_counter();
 2783:     my %page_breaks  = &get_page_breaks($helper);
 2784:     my $columns_in_format = (split(/\|/,$helper->{'VARS'}->{'FORMAT'}))[1];
 2785:     #
 2786:     #   end each student with a 
 2787:     #   Special that allows the post processor to even out the page
 2788:     #   counts later.  Nasty problem this... it would be really
 2789:     #   nice to put the special in as a postscript comment
 2790:     #   e.g. \special{ps:\ENDOFSTUDENTSTAMP}  unfortunately,
 2791:     #   The special gets passed the \ and dvips puts it in the output file
 2792:     #   so we will just rely on prntout.pl to strip  ENDOFSTUDENTSTAMP from the
 2793:     #   postscript.  Each ENDOFSTUDENTSTAMP will go on a line by itself.
 2794:     #
 2795: 
 2796:     foreach my $curresline (@{$master_seq})  {
 2797: 	if (defined $page_breaks{$curresline}) {
 2798: 	    if($i != 0) {
 2799: 		$current_output.= "\\newpage\n";
 2800: 	    }
 2801: 	}
 2802: 	$i++;
 2803: 
 2804: 	if ( !($type eq 'problems' && 
 2805: 	       ($curresline!~ m/\.(problem|exam|quiz|assess|survey|form|library)$/)) ) {
 2806: 	    my ($map,$id,$res_url) = &Apache::lonnet::decode_symb($curresline);
 2807: 	    if (&Apache::lonnet::allowed('bre',$res_url)) {
 2808: 		if ($res_url!~m|^ext/|
 2809: 		    && $res_url=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
 2810: 		    $printed .= $curresline.':';
 2811: 		    &Apache::lonxml::remember_problem_counter();    
 2812: 
 2813: 		    my $rendered = &get_student_view_with_retries($curresline,$ssi_retry_count,$username,$userdomain,$env{'request.course.id'},'tex',$moreenv);
 2814: 		    if(($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') ||
 2815: 		       ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'only')) {
 2816: 			#   Use a copy of the hash so we don't pervert it on future loop passes.
 2817: 			my %answerenv = %{$moreenv};
 2818: 			$answerenv{'answer_output_mode'}='tex';
 2819: 			$answerenv{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 2820: 			
 2821: 			&Apache::lonxml::restore_problem_counter();
 2822: 
 2823: 			my $ansrendered = &Apache::loncommon::get_student_answers($curresline,$username,$userdomain,$env{'request.course.id'},%answerenv);
 2824: 
 2825: 			if ($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 2826: 			    $rendered=~s/(\\keephidden{ENDOFPROBLEM})/$ansrendered$1/;
 2827: 			} else {
 2828: 
 2829: 			    
 2830: 			    my $header =&print_latex_header($helper->{'VARS'}->{'LATEX_TYPE'});
 2831: 			    $header =~ s/\\begin{document}//;     #<<<<<
 2832: 			    my $title = &Apache::lonnet::gettitle($curresline);
 2833: 			    $title = &Apache::lonxml::latex_special_symbols($title);
 2834: 			    my $body   ='\vskip 0 mm \noindent\textbf{'.$title.'}\vskip 0 mm ';
 2835: 			    $body     .=&path_to_problem($res_url,$LaTeXwidth);
 2836: 			    $body     .='\vskip 1 mm '.$ansrendered;
 2837: 			    $body     = &encapsulate_minipage($body);
 2838: 			    $rendered = $header.$body;
 2839: 			}
 2840: 		    }
 2841: 		    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2842: 			my $url = &Apache::lonnet::clutter($res_url);
 2843: 			my $annotation = &annotate($url);
 2844: 			$rendered =~  s/(\\keephidden{ENDOFPROBLEM})/$annotation$1/;
 2845: 		    }
 2846: 		    my $junk;
 2847: 		    if ($remove_latex_header eq 'YES') {
 2848: 			$rendered = &latex_header_footer_remove($rendered);
 2849: 		    } else {
 2850: 			$rendered =~ s/\\end{document}//;
 2851: 		    }
 2852: 		    $current_output .= $rendered;		    
 2853: 		} elsif ($res_url=~/\/(smppg|syllabus|aboutme|bulletinboard)$/) {
 2854: 		    $printed .= $curresline.':';
 2855: 		    my $rendered = &get_student_view_with_retries($curresline,$ssi_retry_count,$username,$userdomain,$env{'request.course.id'},'tex',$moreenv);
 2856: 		    if ($helper->{'VARS'}->{'PRINT_ANNOTATIONS'} eq 'yes') {
 2857: 			my $url = &Apache::lonnet::clutter($res_url);
 2858: 			my $annotation = &annotate($url);
 2859: 			$annotation    =~ s/(\\end{document})/$annotation$1/;
 2860: 		    }
 2861: 		    if ($remove_latex_header eq 'YES') {
 2862: 			$rendered = &latex_header_footer_remove($rendered);
 2863: 		    } else {
 2864: 			$rendered =~ s/\\end{document}//;
 2865: 		    }
 2866: 		    $current_output .= $rendered.'\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\strut \vskip 0 mm \strut ';
 2867: 		} elsif($res_url = ~/\.pdf$/) {
 2868: 		    my $url = &Apache::lonnet::clutter($res_url);
 2869: 		    my $rendered  = &include_pdf($url);
 2870: 		    if ($remove_latex_header ne 'NO') {
 2871: 			$rendered = &latex_header_footer_remove($rendered);
 2872: 		    }
 2873: 		    $current_output .= $rendered;
 2874: 		} else {
 2875: 		    my $rendered = &unsupported($res_url,$helper->{'VARS'}->{'LATEX_TYPE'},$curresline);
 2876: 		    if ($remove_latex_header ne 'NO') {
 2877: 			$rendered = &latex_header_footer_remove($rendered);
 2878: 		    } else {
 2879: 			$rendered =~ s/\\end{document}//;
 2880: 		    }
 2881: 		    $current_output .= $rendered;
 2882: 		}
 2883: 	    }
 2884: 	    $remove_latex_header = 'YES';
 2885: 	} 
 2886: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 2887:     }
 2888: 
 2889: 
 2890:     my $courseidinfo = &get_course();
 2891:     my $currentassignment=&Apache::lonxml::latex_special_symbols($helper->{VARS}->{'assignment'},'header');
 2892:     my $header_line =
 2893: 	&format_page_header($LaTeXwidth, $parmhash{'print_header_format'},
 2894: 			    $currentassignment, $courseidinfo, $fullname, $usersection);
 2895:     my $header_start = ($columns_in_format == 1) ? '\lhead'
 2896: 	                                         : '\fancyhead[LO]';
 2897:     $header_line = $header_start.'{'.$header_line.'}';
 2898:     if ($current_output=~/\\documentclass/) {
 2899: 	$current_output =~ s/\\begin{document}/\\setlength{\\topmargin}{1cm} \\begin{document}\\noindent\\parbox{\\minipagewidth}{\\noindent$header_line$namepostfix}\\vskip 5 mm /;
 2900:     } else {
 2901: 	my $blankpages = 
 2902: 	    '\clearpage\strut\clearpage'x$helper->{'VARS'}->{'EMPTY_PAGES'};
 2903: 	    
 2904: 	$current_output = '\strut\vspace*{-6 mm}\\newline'.
 2905: 	    &copyright_line().' \newpage '.$blankpages.$end_of_student.
 2906: 	    '\setcounter{page}{1}\noindent\parbox{\minipagewidth}{\noindent'.
 2907: 	    $header_line.$namepostfix.'} \vskip 5 mm '.$current_output;
 2908:     }
 2909:     #
 2910:     #  Close the student bracketing.
 2911:     #
 2912:     return ($current_output,$fullname, $printed);
 2913: 
 2914: }
 2915: 
 2916: sub handler {
 2917: 
 2918:     my $r = shift;
 2919:     
 2920:     &init_perm();
 2921: 
 2922: 
 2923: 
 2924:     my $helper = printHelper($r);
 2925:     if (!ref($helper)) {
 2926: 	return $helper;
 2927:     }
 2928:    
 2929: 
 2930:     %parmhash=&Apache::lonnet::coursedescription($env{'request.course.id'});
 2931:  
 2932: 
 2933: 
 2934: 
 2935:     #  If a figure conversion queue file exists for this user.domain
 2936:     # we delete it since it can only be bad (if it were good, printout.pl
 2937:     # would have deleted it the last time around.
 2938: 
 2939:     my $conversion_queuefile = "/home/httpd/prtspool/$env{'user.name'}_$env{'user.domain'}_printout.dat";
 2940:     if(-e $conversion_queuefile) {
 2941: 	unlink $conversion_queuefile;
 2942:     }
 2943:     
 2944: 
 2945:     &output_data($r,$helper,\%parmhash);
 2946:     return OK;
 2947: } 
 2948: 
 2949: use Apache::lonhelper;
 2950: 
 2951: sub addMessage {
 2952:     my $text = shift;
 2953:     my $paramHash = Apache::lonhelper::getParamHash();
 2954:     $paramHash->{MESSAGE_TEXT} = $text;
 2955:     Apache::lonhelper::message->new();
 2956: }
 2957: 
 2958: 
 2959: 
 2960: sub init_perm {
 2961:     undef(%perm);
 2962:     $perm{'pav'}=&Apache::lonnet::allowed('pav',$env{'request.course.id'});
 2963:     if (!$perm{'pav'}) {
 2964: 	$perm{'pav'}=&Apache::lonnet::allowed('pav',
 2965: 		  $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 2966:     }
 2967:     $perm{'pfo'}=&Apache::lonnet::allowed('pfo',$env{'request.course.id'});
 2968:     if (!$perm{'pfo'}) {
 2969: 	$perm{'pfo'}=&Apache::lonnet::allowed('pfo',
 2970: 		  $env{'request.course.id'}.'/'.$env{'request.course.sec'});
 2971:     }
 2972: }
 2973: 
 2974: sub get_randomly_ordered_warning {
 2975:     my ($helper,$map) = @_;
 2976: 
 2977:     my $message;
 2978: 
 2979:     my $postdata = $env{'form.postdata'} || $helper->{VARS}{'postdata'};
 2980:     my $navmap = Apache::lonnavmaps::navmap->new();
 2981:     if (defined($navmap)) {
 2982:         my $res = $navmap->getResourceByUrl($map);
 2983:         if ($res) {
 2984: 	    my $func = 
 2985: 	        sub { return ($_[0]->is_map() && $_[0]->randomorder); };
 2986: 	    my @matches = $navmap->retrieveResources($res, $func,1,1,1);
 2987: 	    if (@matches) {
 2988: 	        $message = "Some of the items below are in folders set to be randomly ordered. However, when printing the contents of these folders, they will be printed in the original order for all students, not the randomized order.";
 2989: 	    }
 2990:         }
 2991:         if ($message) {
 2992: 	    return '<message type="warning">'.$message.'</message>';
 2993:         }
 2994:     } else {
 2995:         $message = "Retrieval of information about ordering of resources failed."; 
 2996:         return '<message type="warning">'.$message.'</message>';
 2997:     }
 2998:     return;
 2999: }
 3000: 
 3001: sub printHelper {
 3002:     my $r = shift;
 3003: 
 3004:     if ($r->header_only) {
 3005:         if ($env{'browser.mathml'}) {
 3006:             &Apache::loncommon::content_type($r,'text/xml');
 3007:         } else {
 3008:             &Apache::loncommon::content_type($r,'text/html');
 3009:         }
 3010:         $r->send_http_header;
 3011:         return OK;
 3012:     }
 3013: 
 3014:     # Send header, nocache
 3015:     if ($env{'browser.mathml'}) {
 3016:         &Apache::loncommon::content_type($r,'text/xml');
 3017:     } else {
 3018:         &Apache::loncommon::content_type($r,'text/html');
 3019:     }
 3020:     &Apache::loncommon::no_cache($r);
 3021:     $r->send_http_header;
 3022:     $r->rflush();
 3023: 
 3024:     # Unfortunately, this helper is so complicated we have to
 3025:     # write it by hand
 3026: 
 3027:     Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
 3028:     
 3029:     my $helper = Apache::lonhelper::helper->new("Printing Helper");
 3030:     $helper->declareVar('symb');
 3031:     $helper->declareVar('postdata');    
 3032:     $helper->declareVar('curseed'); 
 3033:     $helper->declareVar('probstatus');   
 3034:     $helper->declareVar('filename');
 3035:     $helper->declareVar('construction');
 3036:     $helper->declareVar('assignment');
 3037:     $helper->declareVar('style_file');
 3038:     $helper->declareVar('student_sort');
 3039:     $helper->declareVar('FINISHPAGE');
 3040:     $helper->declareVar('PRINT_TYPE');
 3041:     $helper->declareVar("showallfoils");
 3042:     $helper->declareVar("STUDENTS");
 3043: 
 3044: 
 3045:    
 3046: 
 3047: 
 3048:     #  The page breaks can get loaded initially from the course environment:
 3049:     # But we only do this in the initial state so that they are allowed to change.
 3050:     #
 3051: 
 3052:     # $helper->{VARS}->{FINISHPAGE} = '';
 3053:     
 3054:     &Apache::loncommon::restore_course_settings('print',
 3055: 						{'pagebreaks'  => 'scalar',
 3056: 					         'lastprinttype' => 'scalar'});
 3057:     
 3058:     # This will persistently load in the data we want from the
 3059:     # very first screen.
 3060:     
 3061:     if($helper->{VARS}->{PRINT_TYPE} eq $env{'form.lastprinttype'}) {
 3062: 	if (!defined ($env{"form.CURRENT_STATE"})) {
 3063: 	    
 3064: 	    $helper->{VARS}->{FINISHPAGE} = $env{'form.pagebreaks'};
 3065: 	} else {
 3066: 	    my $state = $env{"form.CURRENT_STATE"};
 3067: 	    if ($state eq "START") {
 3068: 		$helper->{VARS}->{FINISHPAGE} = $env{'form.pagebreaks'};
 3069: 	    }
 3070: 	}
 3071: 	
 3072:     }
 3073: 
 3074:     # Detect whether we're coming from construction space
 3075:     if ($env{'form.postdata'}=~/^(?:http:\/\/[^\/]+\/|\/|)\~([^\/]+)\/(.*)$/) {
 3076:         $helper->{VARS}->{'filename'} = "~$1/$2";
 3077:         $helper->{VARS}->{'construction'} = 1;
 3078:     } else {
 3079:         if ($env{'form.postdata'}) {
 3080:             $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($env{'form.postdata'});
 3081: 	    if ( $helper->{VARS}->{'symb'} eq '') {
 3082: 		$helper->{VARS}->{'postdata'} = $env{'form.postdata'};
 3083: 	    }
 3084:         }
 3085:         if ($env{'form.symb'}) {
 3086:             $helper->{VARS}->{'symb'} = $env{'form.symb'};
 3087:         }
 3088:         if ($env{'form.url'}) {
 3089:             $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($helper->{VARS}->{'postdata'});
 3090:         }
 3091: 
 3092:     }
 3093: 
 3094:     if ($env{'form.symb'}) {
 3095:         $helper->{VARS}->{'symb'} = $env{'form.symb'};
 3096:     }
 3097:     if ($env{'form.url'}) {
 3098:         $helper->{VARS}->{'symb'} = &Apache::lonnet::symbread($helper->{VARS}->{'postdata'});
 3099: 
 3100:     }
 3101:     $helper->{VARS}->{'symb'}=
 3102: 	&Apache::lonenc::check_encrypt($helper->{VARS}->{'symb'});
 3103:     my ($resourceTitle,$sequenceTitle,$mapTitle) = &details_for_menu($helper);
 3104:     if ($sequenceTitle ne '') {$helper->{VARS}->{'assignment'}=$sequenceTitle;}
 3105: 
 3106:     
 3107:     # Extract map
 3108:     my $symb = $helper->{VARS}->{'symb'};
 3109:     my ($map, $id, $url);
 3110:     my $subdir;
 3111:     my $is_published=0;		# True when printing from resource space.
 3112: 
 3113:     # Get the resource name from construction space
 3114:     if ($helper->{VARS}->{'construction'}) {
 3115:         $resourceTitle = substr($helper->{VARS}->{'filename'}, 
 3116:                                 rindex($helper->{VARS}->{'filename'}, '/')+1);
 3117:         $subdir = substr($helper->{VARS}->{'filename'},
 3118:                          0, rindex($helper->{VARS}->{'filename'}, '/') + 1);
 3119:     } else {
 3120: 	# From course space:
 3121: 
 3122: 	if ($symb ne '') {
 3123: 	    ($map, $id, $url) = &Apache::lonnet::decode_symb($symb);
 3124: 	    $helper->{VARS}->{'postdata'} = 
 3125: 		&Apache::lonenc::check_encrypt(&Apache::lonnet::clutter($url));
 3126: 	} else {
 3127: 	    $url = $helper->{VARS}->{'postdata'};
 3128: 	    $is_published=1;	# From resource space.
 3129: 	}
 3130: 	$url = &Apache::lonnet::clutter($url);
 3131:         if (!$resourceTitle) { # if the resource doesn't have a title, use the filename
 3132:             my $postdata = $helper->{VARS}->{'postdata'};
 3133:             $resourceTitle = substr($postdata, rindex($postdata, '/') + 1);
 3134:         }
 3135:         $subdir = &Apache::lonnet::filelocation("", $url);
 3136:     }
 3137:     if (!$helper->{VARS}->{'curseed'} && $env{'form.curseed'}) {
 3138: 	$helper->{VARS}->{'curseed'}=$env{'form.curseed'};
 3139:     }
 3140:     if (!$helper->{VARS}->{'probstatus'} && $env{'form.problemtype'}) {
 3141: 	$helper->{VARS}->{'probstatus'}=$env{'form.problemstatus'};
 3142:     }
 3143: 
 3144:     my $userCanSeeHidden = Apache::lonnavmaps::advancedUser();
 3145: 
 3146:     Apache::lonhelper::registerHelperTags();
 3147: 
 3148:     # "Delete everything after the last slash."
 3149:     $subdir =~ s|/[^/]+$||;
 3150: 
 3151:     # What can be printed is a very dynamic decision based on
 3152:     # lots of factors. So we need to dynamically build this list.
 3153:     # To prevent security leaks, states are only added to the wizard
 3154:     # if they can be reached, which ensures manipulating the form input
 3155:     # won't allow anyone to reach states they shouldn't have permission
 3156:     # to reach.
 3157: 
 3158:     # printChoices is tracking the kind of printing the user can
 3159:     # do, and will be used in a choices construction later.
 3160:     # In the meantime we will be adding states and elements to
 3161:     # the helper by hand.
 3162:     my $printChoices = [];
 3163:     my $paramHash;
 3164: 
 3165:     if ($resourceTitle) {
 3166:         push @{$printChoices}, ["<b><i>$resourceTitle</i></b> (".&mt('the resource you just saw on the screen').")", 'current_document', 'PAGESIZE'];
 3167:     }
 3168: 
 3169:     # Useful filter strings
 3170:     my $isProblem = '($res->is_problem()||$res->contains_problem||$res->is_practice()) ';
 3171:     $isProblem .= ' && !$res->randomout()' if !$userCanSeeHidden;
 3172:     my $isProblemOrMap = '$res->is_problem() || $res->contains_problem() || $res->is_sequence() || $res->is_practice()';
 3173:     my $isNotMap = '!$res->is_sequence()';
 3174:     $isNotMap .= ' && !$res->randomout()' if !$userCanSeeHidden;
 3175:     my $isMap = '$res->is_map()';
 3176:     my $symbFilter = '$res->shown_symb()';
 3177:     my $urlValue = '$res->link()';
 3178: 
 3179:     $helper->declareVar('SEQUENCE');
 3180: 
 3181:     # If we're in a sequence...
 3182: 
 3183:     my $start_new_option;
 3184:     if ($perm{'pav'}) {
 3185: 	$start_new_option = 
 3186: 	    "<option text='".&mt('Start new page<br />before selected').
 3187: 	    "' variable='FINISHPAGE' />";
 3188:     }
 3189: 
 3190:     # If not construction space user can print the components of a page:
 3191: 
 3192:     my $page_ispage;
 3193:     my $page_title;
 3194:     if (!$helper->{VARS}->{'construction'}) {
 3195: 	my $varspostdata = $helper->{VARS}->{'postdata'};
 3196: 	my $varsassignment = $helper->{VARS}->{'assignment'};
 3197: 	my $page_navmap         = Apache::lonnavmaps::navmap->new();
 3198: 	if (defined($page_navmap)) {
 3199: 	    my @page_resources      = $page_navmap->retrieveResources($url);
 3200: 	    if(defined($page_resources[0])) {
 3201: 		$page_ispage       = $page_resources[0]->is_page();
 3202: 		$page_title     = $page_resources[0]->title();
 3203: 		my $resourcesymb   = $page_resources[0]->symb();
 3204: 		my ($pagemap, $pageid, $pageurl) = &Apache::lonnet::decode_symb($symb);
 3205: 		if ($page_ispage) {
 3206: 		    push @{$printChoices}, 
 3207: 		    [&mt('Selected [_1]Problems[_2] from page [_3]', '<b>', '</b>', '<b><i>'.$page_title.'</i></b>'), 
 3208: 		     'map_problems_in_page', 
 3209: 		     'CHOOSE_PROBLEMS_PAGE'];
 3210: 		    push @{$printChoices}, 
 3211: 		    [&mt('Selected [_1]Resources[_2] from page [_3]', '<b>', '</b>', '<b><i>'.$page_title.'</i></b>'), 
 3212: 		     'map_resources_in_page', 
 3213: 		     'CHOOSE_RESOURCES_PAGE'];
 3214: 		}
 3215:         my $helperFragment = &generate_resource_chooser('CHOOSE_PROBLEMS_PAGE',
 3216: 							'Select Problem(s) to print',
 3217: 							"multichoice='1' toponly='1' addstatus='1' closeallpages='1'",
 3218: 							'RESOURCES',
 3219: 							'PAGESIZE',
 3220: 							$url,
 3221: 							$isProblem, '',  $symbFilter,
 3222: 							$start_new_option);
 3223: 
 3224: 
 3225:       $helperFragment .= &generate_resource_chooser('CHOOSE_RESOURCES_PAGE',
 3226: 						    'Select Resource(s) to print',
 3227: 						    'multichoice="1" toponly="1" addstatus="1" closeallpages="1"',
 3228: 						    'RESOURCES',
 3229: 						    'PAGESIZE',
 3230: 						    $url,
 3231: 						    $isNotMap, '', $symbFilter,
 3232: 						    $start_new_option);
 3233: 
 3234: 						    
 3235: 
 3236: 
 3237: 
 3238: 	&Apache::lonxml::xmlparse($r, 'helper', $helperFragment);
 3239: 	
 3240: 	    }
 3241: 	}
 3242:     }
 3243: 
 3244:     if (($helper->{'VAR'}->{'construction'} ne '1' ) &&
 3245: 	$helper->{VARS}->{'postdata'} &&
 3246: 	$helper->{VARS}->{'assignment'}) {
 3247:         # Allow problems from sequence
 3248:         push @{$printChoices}, 
 3249: 	    [&mt('Selected [_1]Problems[_2] from folder [_3]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>'), 
 3250: 	     'map_problems', 
 3251: 	     'CHOOSE_PROBLEMS'];
 3252:         # Allow all resources from sequence
 3253:         push @{$printChoices}, [&mt('Selected [_1]Resources[_2] from folder [_3]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>'), 
 3254: 				'map_problems_pages', 
 3255: 				'CHOOSE_PROBLEMS_HTML'];
 3256:         my $helperFragment = &generate_resource_chooser('CHOOSE_PROBLEMS',
 3257: 							'Select Problem(s) to print',
 3258: 							'multichoice="1" toponly="1" addstatus="1" closeallpages="1"',
 3259: 							'RESOURCES',
 3260: 							'PAGESIZE',
 3261: 							$map,
 3262: 							$isProblem, '',
 3263: 							$symbFilter,
 3264: 							$start_new_option);
 3265: 	$helperFragment .= &generate_resource_chooser('CHOOSE_PROBLEMS_HTML',
 3266: 						      'Select Resource(s) to print',
 3267: 						      	'multichoice="1" toponly="1" addstatus="1" closeallpages="1"',
 3268: 						      'RESOURCES',
 3269: 						      'PAGESIZE',
 3270: 						      $map,
 3271: 						      $isNotMap, '',
 3272: 						      $symbFilter,
 3273: 						      $start_new_option);
 3274: 
 3275: 	&Apache::lonxml::xmlparse($r, 'helper', $helperFragment);
 3276:     }
 3277: 
 3278:     # If the user has pfo (print for others) allow them to print all 
 3279:     # problems and resources  in the entire course, optionally for selected students
 3280:     my $post_data = $helper->{VARS}->{'postdata'};
 3281:     if ($perm{'pfo'} &&  !$is_published  &&
 3282:         ($post_data=~/\/res\// || $post_data =~/\/(syllabus|smppg|aboutme|bulletinboard)$/)) { 
 3283: 
 3284:         push @{$printChoices}, [&mtn('Selected <b>Problems</b> from <b>entire course</b>'), 'all_problems', 'ALL_PROBLEMS'];
 3285: 	push @{$printChoices}, [&mtn('Selected <b>Resources</b> from <b>entire course</b>'), 'all_resources', 'ALL_RESOURCES'];
 3286: 	push @{$printChoices}, [&mtn('Selected <b>Problems</b> from <b>entire course</b> for <b>selected people</b>'), 'all_problems_students', 'ALL_PROBLEMS_STUDENTS'];
 3287: my $suffixXml = <<ALL_PROBLEMS;
 3288:   <state name="STUDENTS1" title="Select People">
 3289:       <message><b>Select sorting order of printout</b> </message>
 3290:     <choices variable='student_sort'>
 3291:       <choice computer='0'>Sort by section then student</choice>
 3292:       <choice computer='1'>Sort by students across sections.</choice>
 3293:     </choices>
 3294:       <message><br /><hr /><br /> </message>
 3295:       <student multichoice='1' variable="STUDENTS" nextstate="PRINT_FORMATTING" coursepersonnel="1"/>
 3296:   </state>
 3297: ALL_PROBLEMS
 3298:          &Apache::lonxml::xmlparse($r, 'helper', 
 3299: 				   &generate_resource_chooser('ALL_PROBLEMS',
 3300: 							      'SelectProblem(s) to print',
 3301: 							      'multichoice="1" suppressEmptySequences="0" addstatus="1" closeallpages="1"',
 3302: 							      'RESOURCES',
 3303: 							      'PAGESIZE',
 3304: 							      '',
 3305: 							      $isProblemOrMap, $isNotMap,
 3306: 							      $symbFilter,
 3307: 							      $start_new_option) .
 3308: 				   &generate_resource_chooser('ALL_RESOURCES',
 3309: 							      'Select Resource(s) to print',
 3310: 							      " toponly='0' multichoice='1' suppressEmptySequences='0' addstatus='1' closeallpages='1'",
 3311: 							      'RESOURCES',
 3312: 							      'PAGESIZE',
 3313: 							      '',
 3314: 							      $isNotMap,'',$symbFilter,
 3315: 							      $start_new_option) .
 3316: 				   &generate_resource_chooser('ALL_PROBLEMS_STUDENTS',
 3317: 							      'Select Problem(s) to print',
 3318: 							      'toponly="0" multichoice="1" suppressEmptySequences="0" addstatus="1" closeallpages="1"',
 3319: 							      'RESOURCES',
 3320: 							      'STUDENTS1',
 3321: 							      '',
 3322: 							      $isProblemOrMap,'' , $symbFilter,
 3323: 							      $start_new_option) .
 3324: 				     $suffixXml
 3325: 				   );
 3326: 
 3327: 	if ($helper->{VARS}->{'assignment'}) {
 3328: 
 3329: 	    # If we were looking at a page, allow a selection of problems from the page
 3330: 	    # either for selected students or for coded assignments.
 3331: 
 3332: 	    if ($page_ispage) {
 3333: 		push @{$printChoices}, [&mt('Selected [_1]Problems[_2] from page [_3] for [_4]selected people[_5]',
 3334: 					    '<b>', '</b>', '<b><i>'.$page_title.'</i></b>', '<b>', '</b>'),
 3335: 					'problems_for_students_from_page', 'CHOOSE_TGT_STUDENTS_PAGE'];
 3336: 		push @{$printChoices}, [&mt('Selected [_1]Problems[_2] from page [_3] for [_4]CODEd assignments[_5]',
 3337: 					    '<b>', '</b>', '<b><i>'.$page_title.'</i></b>', '<b>', '</b>'),
 3338: 					'problems_for_anon_page', 'CHOOSE_ANON1_PAGE'];
 3339: 	    }
 3340: 	    push @{$printChoices}, [&mt('Selected [_1]Problems[_2] from folder [_3] for [_4]selected people[_5]',
 3341: 					'<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'), 
 3342: 				    'problems_for_students', 'CHOOSE_STUDENTS'];
 3343: 	    push @{$printChoices}, [&mt('Selected [_1]Problems[_2] from folder [_3] for [_4]CODEd assignments[_5]',
 3344: 					'<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'), 
 3345: 				    'problems_for_anon', 'CHOOSE_ANON1'];
 3346: 	}
 3347: 
 3348: 	my $randomly_ordered_warning = 
 3349: 	    &get_randomly_ordered_warning($helper,$map);
 3350: 
 3351: 	# resource_selector will hold a few states that:
 3352: 	#   - Allow resources to be selected for printing.
 3353: 	#   - Determine pagination between assignments.
 3354: 	#   - Determine how many assignments should be bundled into a single PDF.
 3355:         # TODO:
 3356: 	#    Probably good to do things like separate this up into several vars, each
 3357: 	#    with one state, and use REGEXPs at inclusion time to set state names
 3358: 	#    and next states for better mix and match capability
 3359: 	#
 3360: 	my $resource_selector= &generate_resource_chooser('SELECT_PROBLEMS',
 3361: 							  'Select resources to print',
 3362: 							  'multichoice="1" addstatus="1" closeallpages="1"',
 3363: 							  'RESOURCES', 
 3364: 							  'PRINT_FORMATTING',
 3365: 							  '',
 3366: 							  $isProblem, '', $symbFilter,
 3367: 							  $start_new_option);
 3368: 	$resource_selector .=  <<RESOURCE_SELECTOR;
 3369:     <state name="PRINT_FORMATTING" title="How should results be printed?">
 3370:     <message><br /><big><i><b>How should the results be printed?</b></i></big><br /></message>
 3371:     <choices variable="EMPTY_PAGES">
 3372:       <choice computer='0'>Start each student\'s assignment on a new page/column (add a pagefeed after each assignment)</choice>
 3373:       <choice computer='1'>Add one empty page/column after each student\'s assignment</choice>
 3374:       <choice computer='2'>Add two empty pages/column after each student\'s assignment</choice>
 3375:       <choice computer='3'>Add three empty pages/column after each student\'s assignment</choice>
 3376:     </choices>
 3377:     <nextstate>PAGESIZE</nextstate>
 3378:     <message><hr width='33%' /><b>How do you want assignments split into PDF files? </b></message>
 3379:     <choices variable="SPLIT_PDFS">
 3380:        <choice computer="all">All assignments in a single PDF file</choice>
 3381:        <choice computer="sections">Each PDF contains exactly one section</choice>
 3382:        <choice computer="oneper">Each PDF contains exactly one assignment</choice>
 3383:        <choice computer="usenumber" relatedvalue="NUMBER_TO_PRINT">
 3384:             Specify the number of assignments per PDF:</choice>
 3385:     </choices>
 3386:     </state>
 3387: RESOURCE_SELECTOR
 3388:         $resource_selector .= &generate_resource_chooser('CHOOSE_STUDENTS_PAGE',
 3389: 							'Select Problem(s) to print',
 3390: 							"multichoice='1' addstatus='1' closeallpages ='1'",
 3391: 							'RESOURCES',
 3392: 							'PRINT_FORMATTING',
 3393: 							$url,
 3394: 							$isProblem, '',  $symbFilter,
 3395: 							$start_new_option);
 3396: 
 3397: 
 3398: # Generate student choosers.
 3399: 
 3400: 
 3401: 
 3402:         &Apache::lonxml::xmlparse($r, 'helper',
 3403: 				  &generate_student_chooser('CHOOSE_TGT_STUDENTS_PAGE',
 3404: 							    'student_sort',
 3405: 							    'STUDENTS',
 3406: 							    'CHOOSE_STUDENTS_PAGE'));
 3407: 	&Apache::lonxml::xmlparse($r, 'helper', 
 3408: 				  &generate_student_chooser('CHOOSE_STUDENTS',
 3409: 							    'student_sort',
 3410: 							    'STUDENTS',
 3411: 							    'SELECT_PROBLEMS'));
 3412: 	&Apache::lonxml::xmlparse($r, 'helper', $resource_selector);
 3413: 
 3414: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3415: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3416:         my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 3417: 	my $namechoice='<choice></choice>';
 3418: 	foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 3419: 	    if ($name =~ /^error: 2 /) { next; }
 3420: 	    if ($name =~ /^type\0/) { next; }
 3421: 	    $namechoice.='<choice computer="'.$name.'">'.$name.'</choice>';
 3422: 	}
 3423: 
 3424: 
 3425: 	my %code_values;
 3426: 	my %codes_to_print;
 3427: 	foreach my $key (@names) {
 3428: 	    %code_values = &Apache::grades::get_codes($key, $cdom, $cnum);
 3429: 	    foreach my $key (keys(%code_values)) {
 3430: 		$codes_to_print{$key} = 1;
 3431: 	    }
 3432: 	}
 3433: 
 3434: 	my $code_selection;
 3435: 	foreach my $code (sort {uc($a) cmp uc($b)} (keys(%codes_to_print))) {
 3436: 	    my $choice  = $code;
 3437: 	    if ($code =~ /^[A-Z]+$/) { # Alpha code
 3438: 		$choice = &letters_to_num($code);
 3439: 	    }
 3440: 	    push(@{$helper->{DATA}{ALL_CODE_CHOICES}},[$code,$choice]);
 3441: 	}
 3442: 	if (%codes_to_print) {
 3443: 	    $code_selection .='   
 3444: 	    <message><b>Choose single CODE from list:</b></message>
 3445: 		<message></td><td></message>
 3446: 		<dropdown variable="CODE_SELECTED_FROM_LIST" multichoice="0" allowempty="0">
 3447:                   <choice></choice>
 3448:                   <exec>
 3449:                      push(@{$state->{CHOICES}},@{$helper->{DATA}{ALL_CODE_CHOICES}});
 3450:                   </exec>
 3451: 		</dropdown>
 3452: 	    <message></td></tr><tr><td></message>
 3453:             '.$/;
 3454: 
 3455: 	}
 3456: 
 3457:         my @lines = &Apache::grades::get_scantronformat_file();
 3458: 	my $codechoice='';
 3459: 	foreach my $line (@lines) {
 3460: 	    my ($name,$description,$code_type,$code_length)=
 3461: 		(split(/:/,$line))[0,1,2,4];
 3462: 	    if ($code_length > 0 && 
 3463: 		$code_type =~/^(letter|number|-1)/) {
 3464: 		$codechoice.='<choice computer="'.$name.'">'.$description.'</choice>';
 3465: 	    }
 3466: 	}
 3467: 	if ($codechoice eq '') {
 3468: 	    $codechoice='<choice computer="default">Default</choice>';
 3469: 	}
 3470: 	my $anon1 = &generate_code_selector($helper, 
 3471: 					    'CHOOSE_ANON1',
 3472: 					    'SELECT_PROBLEMS',
 3473: 					    $codechoice,
 3474: 					    $code_selection,
 3475: 					    $namechoice) . $resource_selector;
 3476: 					    
 3477: 					    
 3478:         &Apache::lonxml::xmlparse($r, 'helper',$anon1);
 3479: 
 3480: 	my $anon_page = &generate_code_selector($helper,
 3481: 						'CHOOSE_ANON1_PAGE',
 3482: 						'SELECT_PROBLEMS_PAGE',
 3483: 						$codechoice,
 3484: 						$code_selection,
 3485: 						$namechoice) .
 3486: 			&generate_resource_chooser('SELECT_PROBLEMS_PAGE',
 3487: 						   'Select Problem(s) to print',
 3488: 						   "multichoice='1' addstatus='1' closeallpages ='1'",
 3489: 						   'RESOURCES',
 3490: 						   'PRINT_FORMATTING',
 3491: 						   $url,
 3492: 						   $isProblem, '',  $symbFilter,
 3493: 						   $start_new_option);
 3494: 	&Apache::lonxml::xmlparse($r, 'helper', $anon_page);
 3495: 
 3496: 
 3497: 	if ($helper->{VARS}->{'assignment'}) {
 3498: 	    push @{$printChoices}, [&mt('Selected [_1]Resources[_2] from folder [_3] for [_4]selected people[_5]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'), 'resources_for_students', 'CHOOSE_STUDENTS1'];
 3499: 	    push @{$printChoices}, [&mt('Selected [_1]Resources[_2] from folder [_3] for [_4]CODEd assignments[_5]','<b>','</b>','<b><i>'.$sequenceTitle.'</i></b>','<b>','</b>'), 'resources_for_anon', 'CHOOSE_ANON2'];
 3500: 	}
 3501: 	    
 3502: 
 3503: 	$resource_selector=<<RESOURCE_SELECTOR;
 3504:     <state name="SELECT_RESOURCES" title="Select Resources">
 3505:     $randomly_ordered_warning
 3506:     <nextstate>PRINT_FORMATTING</nextstate>
 3507:     <message><br /><big><i><b>Select resources for the assignment</b></i></big><br /></message>
 3508:     <resource variable="RESOURCES" multichoice="1" addstatus="1" 
 3509:               closeallpages="1">
 3510:       <filterfunc>return $isNotMap;</filterfunc>
 3511:       <mapurl>$map</mapurl>
 3512:       <valuefunc>return $symbFilter;</valuefunc>
 3513:       $start_new_option
 3514:       </resource>
 3515:     </state>
 3516: 
 3517:     <state name="PRINT_FORMATTING" title="Format of the print job">
 3518:     <nextstate>NUMBER_PER_PDF</nextstate>
 3519:     <message><br /><big><i><b>How should the results be printed?</b></i></big><br /></message>
 3520:     <choices variable="EMPTY_PAGES">
 3521:       <choice computer='0'>Start each student\'s assignment on a new page/column (add a pagefeed after each assignment)</choice>
 3522:       <choice computer='1'>Add one empty page/column after each student\'s assignment</choice>
 3523:       <choice computer='2'>Add two empty pages/column after each student\'s assignment</choice>
 3524:       <choice computer='3'>Add three empty pages/column after each student\'s assignment</choice>
 3525:     </choices>
 3526:     <nextstate>PAGESIZE</nextstate>
 3527:     <message><hr width='33%' /><b>How do you want assignments split into PDF files? </b></message>
 3528:     <choices variable="SPLIT_PDFS">
 3529:        <choice computer="all">All assignments in a single PDF file</choice>
 3530:        <choice computer="sections">Each PDF contains exactly one section</choice>
 3531:        <choice computer="oneper">Each PDF contains exactly one assignment</choice>
 3532:        <choice computer="usenumber" relatedvalue="NUMBER_TO_PRINT">
 3533:            Specify the number of assignments per PDF:</choice>
 3534:     </choices>
 3535:     </state>
 3536: RESOURCE_SELECTOR
 3537: 
 3538: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_STUDENTS1);
 3539:   <state name="CHOOSE_STUDENTS1" title="Select Students and Resources">
 3540:     <choices variable='student_sort'>
 3541:       <choice computer='0'>Sort by section then student</choice>
 3542:       <choice computer='1'>Sort by students across sections.</choice>
 3543:     </choices>
 3544:     <message><br /><hr /><br /></message>
 3545:     <student multichoice='1' variable="STUDENTS" nextstate="SELECT_RESOURCES" coursepersonnel="1" />
 3546: 
 3547:     </state>
 3548:     $resource_selector
 3549: CHOOSE_STUDENTS1
 3550: 
 3551: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_ANON2);
 3552:   <state name="CHOOSE_ANON2" title="Select CODEd Assignments">
 3553:     <nextstate>SELECT_RESOURCES</nextstate>
 3554:     <message><h4>Fill out one of the forms below</h4></message>
 3555:     <message><br /><hr /> <br /></message>
 3556:     <message><h3>Generate new CODEd Assignments</h3></message>
 3557:     <message><table><tr><td><b>Number of CODEd assignments to print:</b></td><td></message>
 3558:     <string variable="NUMBER_TO_PRINT_TOTAL" maxlength="5" size="5">
 3559:        <validator>
 3560: 	if (((\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}+0) < 1) &&
 3561: 	    !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                &&
 3562: 	    !\$helper->{'VARS'}{'SINGLE_CODE'}                   &&
 3563: 	    !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 3564: 	    return "You need to specify the number of assignments to print";
 3565: 	}
 3566: 	return undef;
 3567:        </validator>
 3568:     </string>
 3569:     <message></td></tr><tr><td></message>
 3570:     <message><b>Names to save the CODEs under for later:</b></message>
 3571:     <message></td><td></message>
 3572:     <string variable="ANON_CODE_STORAGE_NAME" maxlength="50" size="20" />
 3573:     <message></td></tr><tr><td></message>
 3574:     <message><b>Bubble sheet type:</b></message>
 3575:     <message></td><td></message>
 3576:     <dropdown variable="CODE_OPTION" multichoice="0" allowempty="0">
 3577:     $codechoice
 3578:     </dropdown>
 3579:     <message></td></tr><tr><td></table></message>
 3580:     <message><br /><hr /><h3>Print a Specific CODE </h3><br /><table></message>
 3581:     <message><tr><td><b>Enter a CODE to print:</b></td><td></message>
 3582:     <string variable="SINGLE_CODE" size="10">
 3583:         <validator>
 3584: 	   if(!\$helper->{'VARS'}{'NUMBER_TO_PRINT_TOTAL'}           &&
 3585: 	      !\$helper->{'VARS'}{'REUSE_OLD_CODES'}                 &&
 3586: 	      !\$helper->{'VARS'}{'CODE_SELECTED_FROM_LIST'}) {
 3587: 	      return &Apache::lonprintout::is_code_valid(\$helper->{'VARS'}{'SINGLE_CODE'},
 3588: 						      \$helper->{'VARS'}{'CODE_OPTION'});
 3589: 	   } else {
 3590: 	       return undef;	# Other forces control us.
 3591: 	   }
 3592:         </validator>
 3593:     </string>
 3594:     <message></td></tr><tr><td></message>
 3595:         $code_selection
 3596:     <message></td></tr></table></message>
 3597:     <message><hr /><h3>Reprint a Set of Saved CODEs</h3><table><tr><td></message>
 3598:     <message><b>Select saved CODEs:</b></message>
 3599:     <message></td><td></message>
 3600:     <dropdown variable="REUSE_OLD_CODES">
 3601:         $namechoice
 3602:     </dropdown>
 3603:     <message></td></tr></table></message>
 3604:   </state>
 3605:     $resource_selector
 3606: CHOOSE_ANON2
 3607:     }
 3608: 
 3609:     # FIXME: That RE should come from a library somewhere.
 3610:     if (($perm{'pav'} 
 3611: 	&& $subdir ne $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'
 3612: 	&& (defined($helper->{'VARS'}->{'construction'})
 3613: 	    ||
 3614: 	    (&Apache::lonnet::allowed('bre',$subdir) eq 'F'
 3615: 	     && 
 3616: 	     $helper->{VARS}->{'postdata'}=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)/)
 3617: 	    )) 
 3618: 	&& $helper->{VARS}->{'assignment'} eq ""
 3619: 	) {
 3620: 	my $pretty_dir = &Apache::lonnet::hreflocation($subdir);
 3621:         push @{$printChoices}, [&mt('Selected [_1]Problems[_2] from current subdirectory [_3]','<b>','</b>','<b><i>'.$pretty_dir.'</i></b>','<b>','</b>'), 'problems_from_directory', 'CHOOSE_FROM_SUBDIR'];
 3622:         my $xmlfrag = <<CHOOSE_FROM_SUBDIR;
 3623:   <state name="CHOOSE_FROM_SUBDIR" title="Select File(s) from <b><small>$pretty_dir</small></b> to print">
 3624: 
 3625:     <files variable="FILES" multichoice='1'>
 3626:       <nextstate>PAGESIZE</nextstate>
 3627:       <filechoice>return '$subdir';</filechoice>
 3628: CHOOSE_FROM_SUBDIR
 3629:         
 3630:         # this is broken up because I really want interpolation above,
 3631:         # and I really DON'T want it below
 3632:         $xmlfrag .= <<'CHOOSE_FROM_SUBDIR';
 3633:       <filefilter>return Apache::lonhelper::files::not_old_version($filename) &&
 3634: 	  $filename =~ m/\.(problem|exam|quiz|assess|survey|form|library)$/;
 3635:       </filefilter>
 3636:       </files>
 3637:     </state>
 3638: CHOOSE_FROM_SUBDIR
 3639:         &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 3640:     }
 3641: 
 3642:     # Allow the user to select any sequence in the course, feed it to
 3643:     # another resource selector for that sequence
 3644:     if (!$helper->{VARS}->{'construction'} && !$is_published) {
 3645: 	push @$printChoices, [&mtn("Selected <b>Resources</b> from <b>selected folder</b> in course"),
 3646: 			      'select_sequences', 'CHOOSE_SEQUENCE'];
 3647: 	my $escapedSequenceName = $helper->{VARS}->{'SEQUENCE'};
 3648: 	#Escape apostrophes and backslashes for Perl
 3649: 	$escapedSequenceName =~ s/\\/\\\\/g;
 3650: 	$escapedSequenceName =~ s/'/\\'/g;
 3651: 	&Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_FROM_ANY_SEQUENCE);
 3652:   <state name="CHOOSE_SEQUENCE" title="Select Sequence To Print From">
 3653:     <message>Select the sequence to print resources from:</message>
 3654:     <resource variable="SEQUENCE">
 3655:       <nextstate>CHOOSE_FROM_ANY_SEQUENCE</nextstate>
 3656:       <filterfunc>return \$res->is_sequence;</filterfunc>
 3657:       <valuefunc>return $urlValue;</valuefunc>
 3658:       <choicefunc>return \$res->hasResource(\$res,sub { return !\$_[0]->is_sequence() },0,0);
 3659: 	</choicefunc>
 3660:       </resource>
 3661:     </state>
 3662:   <state name="CHOOSE_FROM_ANY_SEQUENCE" title="Select Resources To Print">
 3663:     <message>(mark desired resources then click "next" button) <br /></message>
 3664:     <resource variable="RESOURCES" multichoice="1" toponly='1' addstatus="1"
 3665:               closeallpages="1">
 3666:       <nextstate>PAGESIZE</nextstate>
 3667:       <filterfunc>return $isNotMap</filterfunc>
 3668:       <mapurl evaluate='1'>return '$escapedSequenceName';</mapurl>
 3669:       <valuefunc>return $symbFilter;</valuefunc>
 3670:       $start_new_option
 3671:       </resource>
 3672:     </state>
 3673: CHOOSE_FROM_ANY_SEQUENCE
 3674: }
 3675: 
 3676:     # Generate the first state, to select which resources get printed.
 3677:     Apache::lonhelper::state->new("START", "Select Printing Options:");
 3678:     $paramHash = Apache::lonhelper::getParamHash();
 3679:     $paramHash->{MESSAGE_TEXT} = "";
 3680:     Apache::lonhelper::message->new();
 3681:     $paramHash = Apache::lonhelper::getParamHash();
 3682:     $paramHash->{'variable'} = 'PRINT_TYPE';
 3683:     $paramHash->{CHOICES} = $printChoices;
 3684:     Apache::lonhelper::choices->new();
 3685: 
 3686:     my $startedTable = 0; # have we started an HTML table yet? (need
 3687:                           # to close it later)
 3688: 
 3689:     if (($perm{'pav'} and &Apache::lonnet::allowed('vgr',$env{'request.course.id'})) or 
 3690: 	($helper->{VARS}->{'construction'} eq '1')) {
 3691: 	&addMessage('<br />'
 3692:                    .'<h3>'.&mt('Print Options').'</h3>'
 3693:                    .&Apache::lonhtmlcommon::start_pick_box()
 3694:                    .&Apache::lonhtmlcommon::row_title(
 3695:                        '<label for="ANSWER_TYPE_forminput">'
 3696:                       .&mt('Print Answers')
 3697:                       .'</label>'
 3698:                     )
 3699:         );
 3700:         $paramHash = Apache::lonhelper::getParamHash();
 3701: 	$paramHash->{'variable'} = 'ANSWER_TYPE';   
 3702: 	$helper->declareVar('ANSWER_TYPE');         
 3703:         $paramHash->{CHOICES} = [
 3704:                                    ['Without Answers', 'yes'],
 3705:                                    ['With Answers', 'no'],
 3706:                                    ['Only Answers', 'only']
 3707:                                 ];
 3708:         Apache::lonhelper::dropdown->new();
 3709: 	&addMessage(&Apache::lonhtmlcommon::row_closure());
 3710: 	$startedTable = 1;
 3711: 
 3712: #
 3713: #  Select font size.
 3714: #
 3715: 
 3716:             $helper->declareVar('fontsize');
 3717:             &addMessage(&Apache::lonhtmlcommon::row_title(&mt('Font Size')));
 3718:             my $xmlfrag = << "FONT_SELECTION";
 3719: 
 3720:           
 3721:             <dropdown variable='fontsize' multichoice='0', allowempty='0'>
 3722:             <defaultvalue>
 3723: 		  return 'normalsize';
 3724:             </defaultvalue>
 3725:             <choice computer='tiny'>Tiny</choice>
 3726:             <choice computer='sub/superscriptsize'>Script Size</choice>
 3727:             <choice computer='footnotesize'>Footnote Size</choice>
 3728:             <choice computer='small'>Small</choice>
 3729:             <choice computer='normalsize'>Normal (default)</choice>
 3730:             <choice computer='large'>larger than normal</choice>
 3731:             <choice computer='Large'>Even larger than normal</choice>
 3732:             <choice computer='LARGE'>Still larger than normal</choice>
 3733:             <choice computer='huge'>huge font size</choice>
 3734:             <choice computer='Huge'>Largest possible size</choice>
 3735:             </dropdown>
 3736: FONT_SELECTION
 3737:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 3738:             &addMessage(&Apache::lonhtmlcommon::row_closure(1));
 3739:     }
 3740: 
 3741:     if ($perm{'pav'}) {
 3742: 	if (!$startedTable) {
 3743: 	    addMessage("<hr width='33%' /><table><tr><td align='right'>".
 3744:                        '<label for="LATEX_TYPE_forminput">'.
 3745:                        &mt('LaTeX mode').
 3746:                        "</label>: </td><td>");
 3747: 	    $startedTable = 1;
 3748: 	} else {
 3749: 	    &addMessage(&Apache::lonhtmlcommon::row_title(
 3750:                            '<label for="LATEX_TYPE_forminput">'
 3751:                            .&mt('LaTeX mode')
 3752:                            .'</label>'
 3753:                         )
 3754:             );
 3755: 	}
 3756:         $paramHash = Apache::lonhelper::getParamHash();
 3757: 	$paramHash->{'variable'} = 'LATEX_TYPE';   
 3758: 	$helper->declareVar('LATEX_TYPE');  
 3759: 	if ($helper->{VARS}->{'construction'} eq '1') {       
 3760: 	    $paramHash->{CHOICES} = [
 3761: 				     ['standard LaTeX mode', 'standard'], 
 3762: 				     ['LaTeX batchmode', 'batchmode'], ];
 3763: 	} else {
 3764: 	    $paramHash->{CHOICES} = [
 3765: 				     ['LaTeX batchmode', 'batchmode'],
 3766: 				     ['standard LaTeX mode', 'standard'] ];
 3767: 	}
 3768:         Apache::lonhelper::dropdown->new();
 3769:  
 3770: 	&addMessage(&Apache::lonhtmlcommon::row_closure()
 3771:                    .&Apache::lonhtmlcommon::row_title(
 3772:                         '<label for="TABLE_CONTENTS_forminput">'
 3773:                        .&mt('Print Table of Contents')
 3774:                        .'</label>'
 3775:                     )
 3776:         );
 3777:         $paramHash = Apache::lonhelper::getParamHash();
 3778: 	$paramHash->{'variable'} = 'TABLE_CONTENTS';   
 3779: 	$helper->declareVar('TABLE_CONTENTS');         
 3780:         $paramHash->{CHOICES} = [
 3781:                                    ['No', 'no'],
 3782:                                    ['Yes', 'yes'] ];
 3783:         Apache::lonhelper::dropdown->new();
 3784: 	&addMessage(&Apache::lonhtmlcommon::row_closure());
 3785:         
 3786: 	if (not $helper->{VARS}->{'construction'}) {
 3787: 	    &addMessage(&Apache::lonhtmlcommon::row_title(
 3788:                             '<label for="TABLE_INDEX_forminput">'
 3789:                            .&mt('Print Index')
 3790:                            .'</label>'
 3791:                         )
 3792:             );
 3793: 	    $paramHash = Apache::lonhelper::getParamHash();
 3794: 	    $paramHash->{'variable'} = 'TABLE_INDEX';   
 3795: 	    $helper->declareVar('TABLE_INDEX');         
 3796: 	    $paramHash->{CHOICES} = [
 3797: 				     ['No', 'no'],
 3798: 				     ['Yes', 'yes'] ];
 3799: 	    Apache::lonhelper::dropdown->new();
 3800:             &addMessage(&Apache::lonhtmlcommon::row_closure());
 3801:             &addMessage(&Apache::lonhtmlcommon::row_title(
 3802:                             '<label for="PRINT_DISCUSSIONS_forminput">'
 3803:                            .&mt('Print Discussions')
 3804:                            .'</label>'
 3805:                         )
 3806:             );
 3807: 	    $paramHash = Apache::lonhelper::getParamHash();
 3808: 	    $paramHash->{'variable'} = 'PRINT_DISCUSSIONS';   
 3809: 	    $helper->declareVar('PRINT_DISCUSSIONS');         
 3810: 	    $paramHash->{CHOICES} = [
 3811: 				     ['No', 'no'],
 3812: 				     ['Yes', 'yes'] ];
 3813: 	    Apache::lonhelper::dropdown->new();
 3814:             &addMessage(&Apache::lonhtmlcommon::row_closure());
 3815: 
 3816: 	    # Prompt for printing annotations too.
 3817: 		
 3818: 	    &addMessage(&Apache::lonhtmlcommon::row_title(
 3819:                             '<label for="PRINT_ANNOTATIONS_forminput">'
 3820:                            .&mt('Print Annotations')
 3821:                            .'</label>'
 3822:                         )
 3823:             );
 3824: 	    $paramHash = Apache::lonhelper::getParamHash();
 3825: 	    $paramHash->{'variable'} = "PRINT_ANNOTATIONS";
 3826: 	    $helper->declareVar("PRINT_ANNOTATIONS");
 3827: 	    $paramHash->{CHOICES} = [
 3828: 				     ['No', 'no'],
 3829: 				     ['Yes', 'yes']];
 3830: 	    Apache::lonhelper::dropdown->new();
 3831:             &addMessage(&Apache::lonhtmlcommon::row_closure());
 3832: 
 3833:             &addMessage(&Apache::lonhtmlcommon::row_title(&mt('Foils')));
 3834: 	    $paramHash = Apache::lonhelper::getParamHash();
 3835: 	    $paramHash->{'multichoice'} = "true";
 3836: 	    $paramHash->{'allowempty'}  = "true";
 3837: 	    $paramHash->{'variable'}   = "showallfoils";
 3838: 	    $paramHash->{'CHOICES'} = [ [&mt('Show All Foils'), "1"] ];
 3839: 	    Apache::lonhelper::choices->new();
 3840:             &addMessage(&Apache::lonhtmlcommon::row_closure(1));
 3841: 	}
 3842: 
 3843: 	if ($helper->{'VARS'}->{'construction'}) { 
 3844: 	    my $stylevalue='$Apache::lonnet::env{"construct.style"}';
 3845:             my $randseedtext=&mt("Use random seed");
 3846:             my $stylefiletext=&mt("Use style file");
 3847:             my $selectfiletext=&mt("Select style file");
 3848: 
 3849: 	    my $xmlfrag .= '<message>'
 3850:             .&Apache::lonhtmlcommon::row_title('<label for="curseed_forminput">'
 3851:                                               .$randseedtext
 3852:                                               .'</label>'
 3853:              )
 3854:             .'</message>
 3855:             <string variable="curseed" size="15" maxlength="15">
 3856:                 <defaultvalue>
 3857:                    return '.$helper->{VARS}->{'curseed'}.';
 3858:                 </defaultvalue>'
 3859:             .'</string>'
 3860:             .'<message>'
 3861:             .&Apache::lonhtmlcommon::row_closure()
 3862:             .&Apache::lonhtmlcommon::row_title('<label for="style_file">'
 3863:                                               .$stylefiletext
 3864:                                               .'</label>'
 3865:              )
 3866:             .'</message>
 3867:              <string variable="style_file" size="40">
 3868:                 <defaultvalue>
 3869:                     return '.$stylevalue.';
 3870:                 </defaultvalue>
 3871:              </string><message>&nbsp;'
 3872: .qq|<a href="javascript:openbrowser('helpform','style_file_forminput','sty')">|
 3873: .$selectfiletext.'</a>'
 3874:             .&Apache::lonhtmlcommon::row_closure()
 3875:             .&Apache::lonhtmlcommon::row_title(&mt('Show All Foils'))
 3876:             .'</message>
 3877: 	     <choices allowempty="1" multichoice="true" variable="showallfoils">
 3878:                 <choice computer="1">&nbsp;</choice>
 3879:              </choices>'
 3880: 	    .'<message>'
 3881:             .&Apache::lonhtmlcommon::row_closure()
 3882:             .'</message>';
 3883:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 3884: 
 3885: 
 3886:             &addMessage(&Apache::lonhtmlcommon::row_title(&mt('Problem Type')));
 3887: 	    #
 3888: 	    # Initial value from construction space:
 3889: 	    #
 3890: 	    if (!$helper->{VARS}->{'probstatus'} && $env{'form.problemtype'}) {
 3891: 		$helper->{VARS}->{'probstatus'} = $env{'form.problemtype'};	# initial value
 3892: 	    }
 3893: 	    $xmlfrag = << "PROBTYPE";
 3894: 		<dropdown variable="probstatus" multichoice="0" allowempty="0">
 3895: 		   <defaultvalue>
 3896: 		      return "$helper->{VARS}->{'probstatus'}";
 3897:                    </defaultvalue>
 3898: 		   <choice computer="problem">Homework Problem</choice>
 3899: 		   <choice computer="exam">Exam Problem</choice>
 3900: 		   <choice computer="survey">Survey question</choice>
 3901: 		</dropdown>
 3902: PROBTYPE
 3903:             &Apache::lonxml::xmlparse($r, 'helper', $xmlfrag);
 3904:             &addMessage(&Apache::lonhtmlcommon::row_closure(1));
 3905: 
 3906: 
 3907: 
 3908:         }
 3909:     }
 3910: 
 3911: 
 3912: 
 3913: 
 3914:     if ($startedTable) {
 3915:         &addMessage(&Apache::lonhtmlcommon::end_pick_box());
 3916:     }
 3917: 
 3918:     Apache::lonprintout::page_format_state->new("FORMAT");
 3919: 
 3920:     # Generate the PAGESIZE state which will offer the user the margin
 3921:     # choices if they select one column
 3922:     Apache::lonhelper::state->new("PAGESIZE", "Set Margins");
 3923:     Apache::lonprintout::page_size_state->new('pagesize', 'FORMAT', 'FINAL');
 3924: 
 3925: 
 3926:     $helper->process();
 3927: 
 3928: 
 3929:     # MANUAL BAILOUT CONDITION:
 3930:     # If we're in the "final" state, bailout and return to handler
 3931:     if ($helper->{STATE} eq 'FINAL') {
 3932:         return $helper;
 3933:     }    
 3934: 
 3935:     $r->print($helper->display());
 3936:     if ($helper->{STATE} eq 'START') {
 3937: 	&recently_generated($r);
 3938:     }
 3939:     &Apache::lonhelper::unregisterHelperTags();
 3940: 
 3941:     return OK;
 3942: }
 3943: 
 3944: 
 3945: 1;
 3946: 
 3947: package Apache::lonprintout::page_format_state;
 3948: 
 3949: =pod
 3950: 
 3951: =head1 Helper element: page_format_state
 3952: 
 3953: See lonhelper.pm documentation for discussion of the helper framework.
 3954: 
 3955: Apache::lonprintout::page_format_state is an element that gives the 
 3956: user an opportunity to select the page layout they wish to print 
 3957: with: Number of columns, portrait/landscape, and paper size. If you 
 3958: want to change the paper size choices, change the @paperSize array 
 3959: contents in this package.
 3960: 
 3961: page_format_state is always directly invoked in lonprintout.pm, so there
 3962: is no tag interface. You actually pass parameters to the constructor.
 3963: 
 3964: =over 4
 3965: 
 3966: =item * B<new>(varName): varName is where the print information will be stored in the format FIXME.
 3967: 
 3968: =back
 3969: 
 3970: =cut
 3971: 
 3972: use Apache::lonhelper;
 3973: 
 3974: no strict;
 3975: @ISA = ("Apache::lonhelper::element");
 3976: use strict;
 3977: use Apache::lonlocal;
 3978: use Apache::lonnet;
 3979: 
 3980: my $maxColumns = 2;
 3981: # it'd be nice if these all worked
 3982: #my @paperSize = ("letter [8 1/2x11 in]", "legal [8 1/2x14 in]", 
 3983: #                 "tabloid (ledger) [11x17 in]", "executive [7 1/2x10 in]",
 3984: #                 "a2 [420x594 mm]", "a3 [297x420 mm]", "a4 [210x297 mm]", 
 3985: #                 "a5 [148x210 mm]", "a6 [105x148 mm]" );
 3986: my @paperSize = ("letter [8 1/2x11 in]", "legal [8 1/2x14 in]", 
 3987: 		 "a4 [210x297 mm]");
 3988: 
 3989: # Tentative format: Orientation (L = Landscape, P = portrait) | Colnum |
 3990: #                   Paper type
 3991: 
 3992: sub new { 
 3993:     my $self = Apache::lonhelper::element->new();
 3994: 
 3995:     shift;
 3996: 
 3997:     $self->{'variable'} = shift;
 3998:     my $helper = Apache::lonhelper::getHelper();
 3999:     $helper->declareVar($self->{'variable'});
 4000:     bless($self);
 4001:     return $self;
 4002: }
 4003: 
 4004: sub render {
 4005:     my $self = shift;
 4006:     my $helper = Apache::lonhelper::getHelper();
 4007:     my $result = '';
 4008:     my $var = $self->{'variable'};
 4009:     my $PageLayout=&mt('Page layout');
 4010:     my $NumberOfColumns=&mt('Number of columns');
 4011:     my $PaperType=&mt('Paper type');
 4012:     my $landscape=&mt('Landscape');
 4013:     my $portrait=&mt('Portrait');
 4014:     my $pdfFormLabel=&mt('PDF-Formfields');
 4015:     my $with=&mt('with Formfields');
 4016:     my $without=&mt('without Formfields');
 4017:     
 4018: 
 4019:     $result.='<h3>'.&mt('Layout Options').'</h3>'
 4020:             .&Apache::loncommon::start_data_table()
 4021:             .&Apache::loncommon::start_data_table_header_row()
 4022:             .'<th>'.$PageLayout.'</th>'
 4023:             .'<th>'.$NumberOfColumns.'</th>'
 4024:             .'<th>'.$PaperType.'</th>'
 4025:             .'<th>'.$pdfFormLabel.'</th>'
 4026:             .&Apache::loncommon::end_data_table_header_row()
 4027:             .&Apache::loncommon::start_data_table_row()
 4028:     .'<td>'
 4029:     .'<label><input type="radio" name="'.${var}.'.layout" value="L" />'.$landscape.'</label><br />'
 4030:     .'<label><input type="radio" name="'.${var}.'.layout" value="P" checked="checked" />'.$portrait.'</label>'
 4031:     .'</td>';
 4032: 
 4033:     $result.='<td align="center">'
 4034:             .'<select name="'.${var}.'.cols">';
 4035: 
 4036:     my $i;
 4037:     for ($i = 1; $i <= $maxColumns; $i++) {
 4038:         if ($i == 2) {
 4039:             $result .= '<option value="'.$i.'" selected="selected">'.$i.'</option>'."\n";
 4040:         } else {
 4041:             $result .= '<option value="'.$i.'">'.$i.'</option>'."\n";
 4042:         }
 4043:     }
 4044: 
 4045:     $result .= "</select></td><td>\n";
 4046:     $result .= "<select name='${var}.paper'>\n";
 4047: 
 4048:     my %parmhash=&Apache::lonnet::coursedescription($env{'request.course.id'});
 4049:     my $DefaultPaperSize=lc($parmhash{'default_paper_size'});
 4050:     $DefaultPaperSize=~s/\s//g;
 4051:     if ($DefaultPaperSize eq '') {$DefaultPaperSize='letter';}
 4052:     $i = 0;
 4053:     foreach (@paperSize) {
 4054: 	$_=~/(\w+)/;
 4055: 	my $papersize=$1;
 4056:         if ($paperSize[$i]=~/$DefaultPaperSize/) {
 4057:             $result .= '<option selected="selected" value="'.$papersize.'">'.$paperSize[$i].'</option>'."\n";
 4058:         } else {
 4059:             $result .= '<option value="'.$papersize.'">'.$paperSize[$i].'</option>'."\n";
 4060:         }
 4061:         $i++;
 4062:     }
 4063:     $result .= <<HTML;
 4064:         </select>
 4065:     </td>
 4066:     <td align='center'>
 4067:         <select name='${var}.pdfFormFields'>
 4068:             <option selected="selected" value="no">$without</option>
 4069:             <option value="yes">$with</option>
 4070:         </select>
 4071:     </td>
 4072: HTML
 4073:     $result.=&Apache::loncommon::end_data_table_row()
 4074:             .&Apache::loncommon::end_data_table();
 4075: 
 4076:     return $result;
 4077: }
 4078: 
 4079: sub postprocess {
 4080:     my $self = shift;
 4081: 
 4082:     my $var = $self->{'variable'};
 4083:     my $helper = Apache::lonhelper->getHelper();
 4084:     $helper->{VARS}->{$var} = 
 4085:         $env{"form.$var.layout"} . '|' . $env{"form.$var.cols"} . '|' .
 4086:         $env{"form.$var.paper"} . '|' . $env{"form.$var.pdfFormFields"};
 4087:     return 1;
 4088: }
 4089: 
 4090: 1;
 4091: 
 4092: package Apache::lonprintout::page_size_state;
 4093: 
 4094: =pod
 4095: 
 4096: =head1 Helper element: page_size_state
 4097: 
 4098: See lonhelper.pm documentation for discussion of the helper framework.
 4099: 
 4100: Apache::lonprintout::page_size_state is an element that gives the 
 4101: user the opportunity to further refine the page settings if they
 4102: select a single-column page.
 4103: 
 4104: page_size_state is always directly invoked in lonprintout.pm, so there
 4105: is no tag interface. You actually pass parameters to the constructor.
 4106: 
 4107: =over 4
 4108: 
 4109: =item * B<new>(varName): varName is where the print information will be stored in the format FIXME.
 4110: 
 4111: =back
 4112: 
 4113: =cut
 4114: 
 4115: use Apache::lonhelper;
 4116: use Apache::lonnet;
 4117: no strict;
 4118: @ISA = ("Apache::lonhelper::element");
 4119: use strict;
 4120: 
 4121: 
 4122: 
 4123: sub new { 
 4124:     my $self = Apache::lonhelper::element->new();
 4125: 
 4126:     shift; # disturbs me (probably prevents subclassing) but works (drops
 4127:            # package descriptor)... - Jeremy
 4128: 
 4129:     $self->{'variable'} = shift;
 4130:     my $helper = Apache::lonhelper::getHelper();
 4131:     $helper->declareVar($self->{'variable'});
 4132: 
 4133:     # The variable name of the format element, so we can look into 
 4134:     # $helper->{VARS} to figure out whether the columns are one or two
 4135:     $self->{'formatvar'} = shift;
 4136: 
 4137: 
 4138:     $self->{NEXTSTATE} = shift;
 4139:     bless($self);
 4140: 
 4141:     return $self;
 4142: }
 4143: 
 4144: sub render {
 4145:     my $self = shift;
 4146:     my $helper = Apache::lonhelper::getHelper();
 4147:     my $result = '';
 4148:     my $var = $self->{'variable'};
 4149: 
 4150: 
 4151: 
 4152:     if (defined $self->{ERROR_MSG}) {
 4153:         $result .= '<br /><span class="LC_error">' . $self->{ERROR_MSG} . '</span><br />';
 4154:     }
 4155: 
 4156:     my $format = $helper->{VARS}->{$self->{'formatvar'}};
 4157: 
 4158:     # Use format to get sensible defaults for the margins:
 4159: 
 4160: 
 4161:     my ($laystyle, $cols, $papersize) = split(/\|/, $format);
 4162:     ($papersize)                      = split(/ /, $papersize);
 4163: 
 4164:     $laystyle = &Apache::lonprintout::map_laystyle($laystyle);
 4165: 
 4166: 
 4167: 
 4168:     my %size;
 4169:     ($size{'width_and_units'},
 4170:      $size{'height_and_units'},
 4171:      $size{'margin_and_units'})=
 4172: 	 &Apache::lonprintout::page_format($papersize, $laystyle, $cols);
 4173:     
 4174:     foreach my $dimension ('width','height','margin') {
 4175: 	($size{$dimension},$size{$dimension.'_unit'}) =
 4176: 	    split(/ +/, $size{$dimension.'_and_units'},2);
 4177:        	
 4178: 	foreach my $unit ('cm','in') {
 4179: 	    $size{$dimension.'_options'} .= '<option ';
 4180: 	    if ($size{$dimension.'_unit'} eq $unit) {
 4181: 		$size{$dimension.'_options'} .= 'selected="selected" ';
 4182: 	    }
 4183: 	    $size{$dimension.'_options'} .= '>'.$unit.'</option>';
 4184: 	}
 4185:     }
 4186: 
 4187:     # Adjust margin for LaTeX margin: .. requires units == cm or in.
 4188: 
 4189:     if ($size{'margin_unit'} eq 'in') {
 4190: 	$size{'margin'} += 1;
 4191:     }  else {
 4192: 	$size{'margin'} += 2.54;
 4193:     }
 4194:     my %lt = &Apache::lonlocal::texthash(
 4195:         'format' => 'How should each column be formatted?',
 4196:         'width'  => 'Width',
 4197:         'height' => 'Height',
 4198:         'margin' => 'Left Margin'
 4199:     );
 4200: 
 4201:     $result .= '<p>'.$lt{'format'}.'</p>'
 4202:               .&Apache::lonhtmlcommon::start_pick_box()
 4203:               .&Apache::lonhtmlcommon::row_title($lt{'width'})
 4204:               .'<input type="text" name="'.$var.'.width" value="'.$size{'width'}.'" size="4" />'
 4205:               .'<select name="'.$var.'.widthunit">'
 4206:               .$size{'width_options'}
 4207:               .'</select>'
 4208:               .&Apache::lonhtmlcommon::row_closure()
 4209:               .&Apache::lonhtmlcommon::row_title($lt{'height'})
 4210:               .'<input type="text" name="'.$var.'.height" value="'.$size{'height'}.'" size="4" />'
 4211:               .'<select name="'.$var.'.heightunit">'
 4212:               .$size{'height_options'}
 4213:               .'</select>'
 4214:               .&Apache::lonhtmlcommon::row_closure()
 4215:               .&Apache::lonhtmlcommon::row_title($lt{'margin'})
 4216:               .'<input type="text" name="'.$var.'.lmargin" value="'.$size{'margin'}.'" size="4" />'
 4217:               .'<select name="'.$var.'.lmarginunit">'
 4218:               .$size{'margin_options'}
 4219:               .'</select>'
 4220:               .&Apache::lonhtmlcommon::row_closure(1)
 4221:               .&Apache::lonhtmlcommon::end_pick_box();
 4222:     # <p>Hint: Some instructors like to leave scratch space for the student by
 4223:     # making the width much smaller than the width of the page.</p>
 4224: 
 4225:     return $result;
 4226: }
 4227: 
 4228: 
 4229: sub preprocess {
 4230:     my $self = shift;
 4231:     my $helper = Apache::lonhelper::getHelper();
 4232: 
 4233:     my $format = $helper->{VARS}->{$self->{'formatvar'}};
 4234: 
 4235:     #  If the user does not have 'pav' privilege, set default widths and
 4236:     #  on to the next state right away.
 4237:     #
 4238:     if (!$perm{'pav'}) {
 4239: 	my $var = $self->{'variable'};
 4240: 	my $format = $helper->{VARS}->{$self->{'formatvar'}};
 4241: 	
 4242: 	my ($laystyle, $cols, $papersize) = split(/\|/, $format);
 4243: 	($papersize)                      = split(/ /, $papersize);
 4244: 	
 4245: 	
 4246: 	$laystyle = &Apache::lonprintout::map_laystyle($laystyle);
 4247: 
 4248: 	#  Figure out some good defaults for the print out and set them:
 4249: 	
 4250: 	my %size;
 4251: 	($size{'width'},
 4252: 	 $size{'height'},
 4253: 	 $size{'lmargin'})=
 4254: 	     &Apache::lonprintout::page_format($papersize, $laystyle, $cols);
 4255: 	
 4256: 	foreach my $dim ('width', 'height', 'lmargin') {
 4257: 	    my ($value, $units) = split(/ /, $size{$dim});
 4258: 	    	    
 4259: 	    $helper->{VARS}->{"$var.".$dim}      = $value;
 4260: 	    $helper->{VARS}->{"$var.".$dim.'unit'} = $units;
 4261: 	    
 4262: 	}
 4263: 	
 4264: 
 4265: 	# Transition to the next state
 4266: 
 4267: 	$helper->changeState($self->{NEXTSTATE});
 4268:     }
 4269:    
 4270:     return 1;
 4271: }
 4272: 
 4273: sub postprocess {
 4274:     my $self = shift;
 4275: 
 4276:     my $var = $self->{'variable'};
 4277:     my $helper = Apache::lonhelper->getHelper();
 4278:     my $width = $helper->{VARS}->{$var .'.width'} = $env{"form.${var}.width"}; 
 4279:     my $height = $helper->{VARS}->{$var .'.height'} = $env{"form.${var}.height"}; 
 4280:     my $lmargin = $helper->{VARS}->{$var .'.lmargin'} = $env{"form.${var}.lmargin"}; 
 4281:     $helper->{VARS}->{$var .'.widthunit'} = $env{"form.${var}.widthunit"}; 
 4282:     $helper->{VARS}->{$var .'.heightunit'} = $env{"form.${var}.heightunit"}; 
 4283:     $helper->{VARS}->{$var .'.lmarginunit'} = $env{"form.${var}.lmarginunit"}; 
 4284: 
 4285:     my $error = '';
 4286: 
 4287:     # /^-?[0-9]+(\.[0-9]*)?$/ -> optional minus, at least on digit, followed 
 4288:     # by an optional period, followed by digits, ending the string
 4289: 
 4290:     if ($width !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 4291:         $error .= "Invalid width; please type only a number.<br />\n";
 4292:     }
 4293:     if ($height !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 4294:         $error .= "Invalid height; please type only a number.<br />\n";
 4295:     }
 4296:     if ($lmargin !~  /^-?[0-9]*(\.[0-9]*)?$/) {
 4297:         $error .= "Invalid left margin; please type only a number.<br />\n";
 4298:     } else {
 4299: 	# Adjust for LaTeX 1.0 inch margin:
 4300: 
 4301: 	if ($env{"form.${var}.lmarginunit"} eq "in") {
 4302: 	    $helper->{VARS}->{$var.'.lmargin'} = $lmargin - 1;
 4303: 	} else {
 4304: 	    $helper->{VARS}->{$var.'.lmargin'} = $lmargin - 2.54;
 4305: 	}
 4306:     }
 4307: 
 4308:     if (!$error) {
 4309:         Apache::lonhelper::getHelper()->changeState($self->{NEXTSTATE});
 4310:         return 1;
 4311:     } else {
 4312:         $self->{ERROR_MSG} = $error;
 4313:         return 0;
 4314:     }
 4315: }
 4316: 
 4317: 
 4318: 
 4319: __END__
 4320: 

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