File:  [LON-CAPA] / loncom / interface / lonprintout.pm
Revision 1.560.2.6: download - view: text, annotated - select for diffs
Tue Oct 13 11:01:16 2009 UTC (14 years, 7 months ago) by foxr
Branches: bz2851
Diff to branchpoint 1.560: preferred, unified
BZ2851 - Make selected CODE problems from .page work correctly.

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

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