File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.269: download - view: text, annotated - select for diffs
Wed Aug 6 17:00:30 2003 UTC (20 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixes BUG#1989, students can generate an answer mode display but only when
  generating a feedback email

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.269 2003/08/06 17:00:30 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: # last modified 06/26/00 by Alexander Sakharuk
   40: # 11/6 Gerd Kortemeyer
   41: # 6/1/1 Gerd Kortemeyer
   42: # 2/21,3/13 Guy
   43: # 3/29,5/4 Gerd Kortemeyer
   44: # 5/26 Gerd Kortemeyer
   45: # 5/27 H. K. Ng
   46: # 6/2,6/3,6/8,6/9 Gerd Kortemeyer
   47: # 6/12,6/13 H. K. Ng
   48: # 6/16 Gerd Kortemeyer
   49: # 7/27 H. K. Ng
   50: # 8/7,8/9,8/10,8/11,8/15,8/16,8/17,8/18,8/20,8/23,8/24 Gerd Kortemeyer
   51: # Guy Albertelli
   52: # 9/26 Gerd Kortemeyer
   53: # Dec Guy Albertelli
   54: # YEAR=2002
   55: # 1/1 Gerd Kortemeyer
   56: # 1/2 Matthew Hall
   57: # 1/3 Gerd Kortemeyer
   58: #
   59: 
   60: package Apache::lonxml; 
   61: use vars 
   62: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $prevent_entity_encode $errorcount $warningcount);
   63: use strict;
   64: use HTML::LCParser();
   65: use HTML::TreeBuilder();
   66: use HTML::Entities();
   67: use Safe();
   68: use Safe::Hole();
   69: use Math::Cephes();
   70: use Math::Random();
   71: use Opcode();
   72: 
   73: 
   74: sub register {
   75:   my ($space,@taglist) = @_;
   76:   foreach my $temptag (@taglist) {
   77:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   78:   }
   79: }
   80: 
   81: sub deregister {
   82:   my ($space,@taglist) = @_;
   83:   foreach my $temptag (@taglist) {
   84:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   85:     if ($tempspace eq $space) {
   86:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   87:     }
   88:   }
   89:   #&printalltags();
   90: }
   91: 
   92: use Apache::Constants qw(:common);
   93: use Apache::lontexconvert();
   94: use Apache::style();
   95: use Apache::run();
   96: use Apache::londefdef();
   97: use Apache::scripttag();
   98: use Apache::edit();
   99: use Apache::inputtags();
  100: use Apache::outputtags();
  101: use Apache::lonnet();
  102: use Apache::File();
  103: use Apache::loncommon();
  104: use Apache::lonfeedback();
  105: use Apache::lonmsg();
  106: use Apache::loncacc();
  107: 
  108: #==================================================   Main subroutine: xmlparse  
  109: #debugging control, to turn on debugging modify the correct handler
  110: $Apache::lonxml::debug=0;
  111: 
  112: # keeps count of the number of warnings and errors generated in a parse
  113: $warningcount=0;
  114: $errorcount=0;
  115: 
  116: #path to the directory containing the file currently being processed
  117: @pwd=();
  118: 
  119: #these two are used for capturing a subset of the output for later processing,
  120: #don't touch them directly use &startredirection and &endredirection
  121: @outputstack = ();
  122: $redirection = 0;
  123: 
  124: #controls wheter the <import> tag actually does
  125: $import = 1;
  126: @extlinks=();
  127: 
  128: # meta mode is a bit weird only some output is to be turned off
  129: #<output> tag turns metamode off (defined in londefdef.pm)
  130: $metamode = 0;
  131: 
  132: # turns on and of run::evaluate actually derefencing var refs
  133: $evaluate = 1;
  134: 
  135: # data structure for eidt mode, determines what tags can go into what other tags
  136: %insertlist=();
  137: 
  138: # stores the list of active tag namespaces
  139: @namespace=();
  140: 
  141: # if 0 all high ASCII characters will be encoded into HTML Entities
  142: $prevent_entity_encode=0;
  143: 
  144: # has the dynamic menu been updated to know about this resource
  145: $Apache::lonxml::registered=0;
  146: 
  147: # a pointer the the Apache request object
  148: $Apache::lonxml::request='';
  149: 
  150: # a problem number counter, and check on ether it is used
  151: $Apache::lonxml::counter=1;
  152: $Apache::lonxml::counter_changed=0;
  153: 
  154: #internal check on whether to look at style defs
  155: $Apache::lonxml::usestyle=1;
  156: 
  157: #locations used to store the parameter string for style substitutions
  158: $Apache::lonxml::style_values='';
  159: $Apache::lonxml::style_end_values='';
  160: 
  161: sub xmlbegin {
  162:   my $output='';
  163:   if ($ENV{'browser.mathml'}) {
  164:       $output='<?xml version="1.0"?>'
  165:             .'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'
  166:             .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
  167:             .'[<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">]>'
  168:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
  169: 		.'xmlns="http://www.w3.org/TR/REC-html40">';
  170:   } else {
  171:       $output='<html>';
  172:   }
  173:   return $output;
  174: }
  175: 
  176: sub xmlend {
  177:     my ($discussiononly,$symb)=@_;
  178:     my $discussion='';
  179:     if ($ENV{'request.course.id'}) {
  180:        my $crs='/'.$ENV{'request.course.id'};
  181:        if ($ENV{'request.course.sec'}) {
  182:           $crs.='_'.$ENV{'request.course.sec'};
  183:        }                 
  184:        $crs=~s/\_/\//g;
  185:        my $seeid=&Apache::lonnet::allowed('rin',$crs);
  186:        unless ($symb) {
  187:            $symb=&Apache::lonnet::symbread();
  188:        }
  189:        if ($symb) {
  190:           my %contrib=&Apache::lonnet::restore($symb,$ENV{'request.course.id'},
  191:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  192: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  193:           if ($contrib{'version'}) {
  194:               unless ($discussiononly) {
  195:                  $discussion.=
  196:                   '<address><hr />';
  197: 	     }
  198:               my $idx;
  199:               for ($idx=1;$idx<=$contrib{'version'};$idx++) {
  200: 		my $hidden=($contrib{'hidden'}=~/\.$idx\./);
  201: 		my $deleted=($contrib{'deleted'}=~/\.$idx\./);
  202: 		unless ((($hidden) && (!$seeid)) || ($deleted)) {
  203:                  my $message=$contrib{$idx.':message'};
  204:                  $message=~s/\n/\<br \/\>/g;
  205: 		 $message=&Apache::lontexconvert::msgtexconverted($message);
  206:                  if ($contrib{$idx.':attachmenturl'}) {
  207:                      my ($fname,$ft)
  208:                         =($contrib{$idx.':attachmenturl'}=~/\/(\w+)\.(\w+)$/);
  209: 		     $message.='<p>Attachment: <a href="'.
  210: 	       &Apache::lonnet::tokenwrapper($contrib{$idx.':attachmenturl'}).
  211:                      '"><tt>'.$fname.'.'.$ft.'</tt></a>';
  212:                  }
  213:                  if ($message) {
  214:                   if ($hidden) {
  215: 		      $message='<font color="#888888">'.$message.'</font>';
  216:                   }
  217:                   my $screenname=&Apache::loncommon::screenname(
  218:                                $contrib{$idx.':sendername'},
  219: 			       $contrib{$idx.':senderdomain'});
  220:                   my $plainname=&Apache::loncommon::nickname(
  221:                                $contrib{$idx.':sendername'},
  222: 			       $contrib{$idx.':senderdomain'});
  223: 
  224:                   my $sender='Anonymous';
  225:                   if ((!$contrib{$idx.':anonymous'}) || ($seeid)) {
  226:                       $sender=&Apache::loncommon::aboutmewrapper(
  227:                                $plainname,
  228:                                $contrib{$idx.':sendername'},
  229:                                $contrib{$idx.':senderdomain'}).' ('.
  230:                               $contrib{$idx.':sendername'}.' at '.
  231: 		      $contrib{$idx.':senderdomain'}.')';
  232:                       if ($contrib{$idx.':anonymous'}) {
  233: 			  $sender.=' [anonymous] '.
  234:                                      $screenname;
  235:                       }
  236:                       if ($seeid) {
  237: 			  if ($hidden) {
  238:                              $sender.=' <a href="/adm/feedback?unhide='.
  239: 				 $symb.':::'.$idx.'">Make Visible</a>';
  240:                           } else {
  241:                              $sender.=' <a href="/adm/feedback?hide='.
  242: 				 $symb.':::'.$idx.'">Hide</a>';
  243: 			  }                     
  244:                           $sender.=' <a href="/adm/feedback?deldisc='.
  245: 				 $symb.':::'.$idx.'">Delete</a>';
  246:                       }
  247:                   } else {
  248:                       if ($screenname) {
  249: 			  $sender='<i>'.$screenname.'</i>';
  250:                       }
  251:                   }
  252: 		  $discussion.='<p><b>'.$sender.'</b> ('.
  253:                       localtime($contrib{$idx.':timestamp'}).
  254:                       '):<blockquote>'.$message.
  255:                       '</blockquote></p>';
  256: 	        }
  257:                } 
  258:               }
  259:               unless ($discussiononly) {
  260:                  $discussion.='</address>';
  261: 	      }
  262:           }
  263:           if ($discussiononly) {
  264: 	      $discussion.=(<<ENDDISCUSS);
  265: <form action="/adm/feedback" method="post" name="mailform" enctype="multipart/form-data">
  266: <input type="submit" name="discuss" value="Post Discussion" />
  267: <input type="submit" name="anondiscuss" value="Post Anonymous Discussion" />
  268: <input type="hidden" name="symb" value="$symb" />
  269: <input type="hidden" name="sendit" value="true" />
  270: <br />
  271: <font size="1">Note: in anonymous discussion, your name is visible only to
  272: course faculty</font><br />
  273: <textarea name=comment cols=60 rows=10 wrap=hard></textarea>
  274: <p>
  275: Attachment (128 KB max size): <input type="file" name="attachment" />
  276: </p>
  277: </form>
  278: ENDDISCUSS
  279:              $discussion.=&Apache::lonfeedback::generate_preview_button();
  280:           }
  281:        }
  282:     }
  283:     return $discussion.($discussiononly?'':'</html>');
  284: }
  285: 
  286: sub tokeninputfield {
  287:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  288:     $defhost=~tr/a-z/A-Z/;
  289:     return (<<ENDINPUTFIELD)
  290: <script type="text/javascript">
  291:     function updatetoken() {
  292: 	var comp=new Array;
  293:         var barcode=unescape(document.tokeninput.barcode.value);
  294:         comp=barcode.split('*');
  295:         if (typeof(comp[0])!="undefined") {
  296: 	    document.tokeninput.codeone.value=comp[0];
  297: 	}
  298:         if (typeof(comp[1])!="undefined") {
  299: 	    document.tokeninput.codetwo.value=comp[1];
  300: 	}
  301:         if (typeof(comp[2])!="undefined") {
  302:             comp[2]=comp[2].toUpperCase();
  303: 	    document.tokeninput.codethree.value=comp[2];
  304: 	}
  305:         document.tokeninput.barcode.value='';
  306:     }  
  307: </script>
  308: <form method="post" name="tokeninput">
  309: <table border="2" bgcolor="#FFFFBB">
  310: <tr><th>DocID Checkin</th></tr>
  311: <tr><td>
  312: <table>
  313: <tr>
  314: <td>Scan in Barcode</td>
  315: <td><input type="text" size="22" name="barcode" 
  316: onChange="updatetoken()"/></td>
  317: </tr>
  318: <tr><td><i>or</i> Type in DocID</td>
  319: <td>
  320: <input type="text" size="5" name="codeone" />
  321: <b><font size="+2">*</font></b>
  322: <input type="text" size="5" name="codetwo" />
  323: <b><font size="+2">*</font></b>
  324: <input type="text" size="10" name="codethree" value="$defhost" 
  325: onChange="this.value=this.value.toUpperCase()" />
  326: </td></tr>
  327: </table>
  328: </td></tr>
  329: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  330: </table>
  331: </form>
  332: ENDINPUTFIELD
  333: }
  334: 
  335: sub maketoken {
  336:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  337:     unless ($symb) {
  338: 	$symb=&Apache::lonnet::symbread();
  339:     }
  340:     unless ($tuname) {
  341: 	$tuname=$ENV{'user.name'};
  342:         $tudom=$ENV{'user.domain'};
  343:         $tcrsid=$ENV{'request.course.id'};
  344:     }
  345: 
  346:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  347: }
  348: 
  349: sub printtokenheader {
  350:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  351:     unless ($token) { return ''; }
  352: 
  353:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  354:     unless ($tsymb) {
  355: 	$tsymb=$symb;
  356:     }
  357:     unless ($tuname) {
  358: 	$tuname=$name;
  359:         $tudom=$domain;
  360:         $tcrsid=$courseid;
  361:     }
  362: 
  363:     my %reply=&Apache::lonnet::get('environment',
  364:               ['firstname','middlename','lastname','generation'],
  365:               $tudom,$tuname);
  366:     my $plainname=$reply{'firstname'}.' '. 
  367:                   $reply{'middlename'}.' '.
  368:                   $reply{'lastname'}.' '.
  369: 		  $reply{'generation'};
  370: 
  371:     if ($target eq 'web') {
  372:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  373: 	return 
  374:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  375:                'Checked out for '.$plainname.
  376:                '<br />User: '.$tuname.' at '.$tudom.
  377: 	       '<br />ID: '.$idhash{$tuname}.
  378: 	       '<br />CourseID: '.$tcrsid.
  379: 	       '<br />Course: '.$ENV{'course.'.$tcrsid.'.description'}.
  380:                '<br />DocID: '.$token.
  381:                '<br />Time: '.localtime().'<hr />';
  382:     } else {
  383:         return $token;
  384:     }
  385: }
  386: 
  387: sub fontsettings() {
  388:     my $headerstring='';
  389:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
  390: 	$headerstring.=
  391: 	    '<meta Content-Type="text/html; charset=x-mac-roman">';
  392:     } elsif (!$ENV{'browser.mathml'} && $ENV{'browser.unicode'}) {
  393: 	$headerstring.=
  394: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  395:     }
  396:     return $headerstring;
  397: }
  398: 
  399: sub printalltags {
  400:   my $temp;
  401:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  402:     &Apache::lonxml::debug("$temp -- ".
  403: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  404:   }
  405: }
  406: 
  407: sub xmlparse {
  408:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  409: 
  410:  &setup_globals($request,$target);
  411:  &Apache::inputtags::initialize_inputtags();
  412:  &Apache::outputtags::initialize_outputtags();
  413:  &Apache::edit::initialize_edit();
  414: 
  415: #
  416: # do we have a course style file?
  417: #
  418: 
  419:  if ($ENV{'request.course.id'} && $ENV{'request.state'} ne 'construct') {
  420:      my $bodytext=
  421: 	 $ENV{'course.'.$ENV{'request.course.id'}.'.default_xml_style'};
  422:      if ($bodytext) {
  423:        my $location=&Apache::lonnet::filelocation('',$bodytext);
  424:        my $styletext=&Apache::lonnet::getfile($location);
  425:        if ($styletext ne '-1') {
  426:           %style_for_target = (%style_for_target,
  427:                           &Apache::style::styleparser($target,$styletext));
  428:        }
  429:     }
  430:  }
  431: #&printalltags();
  432:  my @pars = ();
  433:  my $pwd=$ENV{'request.filename'};
  434:  $pwd =~ s:/[^/]*$::;
  435:  &newparser(\@pars,\$content_file_string,$pwd);
  436: 
  437:  my $safeeval = new Safe;
  438:  my $safehole = new Safe::Hole;
  439:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  440: #-------------------- Redefinition of the target in the case of compound target
  441: 
  442:  ($target, my @tenta) = split('&&',$target);
  443: 
  444:  my @stack = ();
  445:  my @parstack = ();
  446:  &initdepth;
  447: 
  448:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  449: 				   $safeeval,\%style_for_target);
  450: 
  451:  if ($ENV{'request.uri'}) {
  452:     &writeallows($ENV{'request.uri'});
  453:  }
  454:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  455:  return $finaloutput;
  456: }
  457: 
  458: sub htmlclean {
  459:     my ($raw,$full)=@_;
  460: 
  461:     my $tree = HTML::TreeBuilder->new;
  462:     $tree->ignore_unknown(0);
  463: 
  464:     $tree->parse($raw);
  465: 
  466:     my $output= $tree->as_HTML(undef,' ');
  467: 
  468:     $output=~s/\<(br|hr|img|meta|allow)(.*?)\>/\<$1$2 \/\>/gis;
  469:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
  470:     unless ($full) {
  471:        $output=~s/\<[\/]*(body|head|html)\>//gis;
  472:     }
  473: 
  474:     $tree = $tree->delete;
  475: 
  476:     return $output;
  477: }
  478: 
  479: sub latex_special_symbols {
  480:     my ($current_token,$stack,$parstack,$where)=@_;
  481:     if ($where eq 'header') {
  482: 	$current_token =~ s/(\\|_|\^)/ /g;
  483: 	$current_token =~ s/(\$|%|\#|&|\{|\})/\\$1/g;
  484:     } else {
  485: 	$current_token=~s/\\ /\\char92 /g;
  486: 	$current_token=~s/\^/\\char94 /g;
  487: 	$current_token=~s/\~/\\char126 /g;
  488: 	$current_token=~s/(&[^A-Za-z\#])/\\$1/g;
  489: 	$current_token=~s/([^&])\#/$1\\#/g;
  490: 	$current_token=~s/(\$|_|{|})/\\$1/g;
  491: 	$current_token=~s/\\char92 /\\texttt{\\char92}/g;
  492: 	$current_token=~s/(>|<)/\$$1\$/g; #more or less
  493: 	if ($current_token=~m/\d%/) {$current_token =~ s/(\d)%/$1\\%/g;} #percent after digit
  494: 	if ($current_token=~m/\s%/) {$current_token =~ s/(\s)%/$1\\%/g;} #persent after space
  495: 	if ($current_token eq '%.') {$current_token = '\%.';} #persent at the end of statement
  496:     }
  497:     return $current_token;
  498: }
  499: 
  500: sub inner_xmlparse {
  501:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  502:   my $finaloutput = '';
  503:   my $result;
  504:   my $token;
  505:   my $dontpop=0;
  506:   while ( $#$pars > -1 ) {
  507:     while ($token = $$pars['-1']->get_token) {
  508:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
  509: 	if ($metamode<1) {
  510: 	    my $text=$token->[1];
  511: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  512: 		$text = '';
  513: #		$text = '%'.$text."\n";
  514: 	    }
  515: 	    $result.=$text;
  516: 	}
  517:       } elsif (($token->[0] eq 'D')) {
  518: 	if ($metamode<1 && $target eq 'web') {
  519: 	    my $text=$token->[1];
  520: 	    $result.=$text;
  521: 	}
  522:       } elsif ($token->[0] eq 'PI') {
  523: 	if ($metamode<1 && $target eq 'web') {
  524: 	  $result=$token->[2];
  525: 	}
  526:       } elsif ($token->[0] eq 'S') {
  527: 	# add tag to stack
  528: 	push (@$stack,$token->[1]);
  529: 	# add parameters list to another stack
  530: 	push (@$parstack,&parstring($token));
  531: 	&increasedepth($token);
  532: 	if ($Apache::lonxml::usestyle &&
  533: 	    exists($$style_for_target{$token->[1]})) {
  534: 	    $Apache::lonxml::usestyle=0;
  535: 	    my $string=$$style_for_target{$token->[1]}.
  536: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  537: 	    &Apache::lonxml::newparser($pars,\$string);
  538: 	    $Apache::lonxml::style_values=$$parstack[-1];
  539: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
  540: 	} else {
  541: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  542: 			     $parstack, $pars, $safeeval, $style_for_target);
  543: 	}
  544:       } elsif ($token->[0] eq 'E') {
  545: 	if ($Apache::lonxml::usestyle &&
  546: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  547: 	    $Apache::lonxml::usestyle=0;
  548: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  549: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
  550: 	    &Apache::lonxml::newparser($pars,\$string);
  551: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
  552: 	    $Apache::lonxml::style_end_values='';
  553: 	    $dontpop=1;
  554: 	} else {
  555: 	    #clear out any tags that didn't end
  556: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  557: 		my $lasttag=$$stack[-1];
  558: 		if ($token->[1] =~ /^$lasttag$/i) {
  559: 		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
  560: 		    last;
  561: 		} else {
  562: 		    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' when looking for &lt;/'.$$stack[-1].'&gt; in file');
  563: 		    &end_tag($stack,$parstack,$token);
  564: 		}
  565: 	    }
  566: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
  567: 			       $parstack, $pars,$safeeval, $style_for_target);
  568: 	}
  569:       } else {
  570: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  571:       }
  572:       #evaluate variable refs in result
  573:       if ($result ne "") {
  574: 	  my $extras;
  575: 	  if (!$Apache::lonxml::usestyle) {
  576: 	      $extras=$Apache::lonxml::style_values;
  577: 	  }
  578: 	if ( $#$parstack > -1 ) {
  579: 	  $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
  580: 	} else {
  581: 	  $result= &Apache::run::evaluate($result,$safeeval,$extras);
  582: 	}
  583:       }
  584:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  585: 	  #Style file definitions should be correct
  586: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
  587: 	      $result=&latex_special_symbols($result,$stack,$parstack);
  588: 	  }
  589:       }
  590: 
  591:       # Encode any high ASCII characters
  592:       if (!$Apache::lonxml::prevent_entity_encode) {
  593: 	$result=&HTML::Entities::encode($result,"\200-\377");
  594:       }
  595:       if ($Apache::lonxml::redirection) {
  596: 	$Apache::lonxml::outputstack['-1'] .= $result;
  597:       } else {
  598: 	$finaloutput.=$result;
  599:       }
  600:       $result = '';
  601: 
  602:       if ($token->[0] eq 'E' && !$dontpop) {
  603: 	&end_tag($stack,$parstack,$token);
  604:       }
  605:       $dontpop=0;
  606:     }	
  607:     if ($#$pars > -1) {
  608: 	pop @$pars;
  609: 	pop @Apache::lonxml::pwd;
  610:     }
  611:   }
  612: 
  613:   # if ($target eq 'meta') {
  614:   #   $finaloutput.=&endredirection;
  615:   # }
  616: 
  617: 
  618:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  619:     $finaloutput=&afterburn($finaloutput);
  620:   }	    
  621:   return $finaloutput;
  622: }
  623: 
  624: sub callsub {
  625:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  626:   my $currentstring='';
  627:   my $nodefault;
  628:   {
  629:     my $sub1;
  630:     no strict 'refs';
  631:     my $tag=$token->[1];
  632: # get utterly rid of extended html tags
  633:     if ($tag=~/^x\-/i) { return ''; }
  634:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  635:     if (!$space) {
  636:      	$tag=~tr/A-Z/a-z/;
  637: 	$sub=~tr/A-Z/a-z/;
  638: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  639:     }
  640: 
  641:     my $deleted=0;
  642:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  643:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  644:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  645: 					     $parstack,$parser,$safeeval,
  646: 					     $style);
  647:     }
  648:     if (!$deleted) {
  649:       if ($space) {
  650: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  651: 	$sub1="$space\:\:$sub";
  652: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  653: 					     $parstack,$parser,$safeeval,
  654: 					     $style);
  655:       } else {
  656: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  657: 	if ($metamode <1) {
  658: 	  if (defined($token->[4]) && ($metamode < 1)) {
  659: 	    $currentstring = $token->[4];
  660: 	  } else {
  661: 	    $currentstring = $token->[2];
  662: 	  }
  663: 	}
  664:       }
  665:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  666:       if ($currentstring eq '' && $nodefault eq '') {
  667: 	if ($target eq 'edit') {
  668: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  669: 	  if ($token->[0] eq 'S') {
  670: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  671: 	  } elsif ($token->[0] eq 'E') {
  672: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  673: 	  }
  674: 	} elsif ($target eq 'modified') {
  675: 	  if ($token->[0] eq 'S') {
  676: 	    $currentstring = $token->[4];
  677: 	    $currentstring.=&Apache::edit::handle_insert();
  678: 	  } elsif ($token->[0] eq 'E') {
  679: 	    $currentstring = $token->[2];
  680:             $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  681: 	  } else {
  682: 	    $currentstring = $token->[2];
  683: 	  }
  684: 	}
  685:       }
  686:     }
  687:     use strict 'refs';
  688:   }
  689:   return $currentstring;
  690: }
  691: 
  692: sub setup_globals {
  693:   my ($request,$target)=@_;
  694:   $Apache::lonxml::request=$request;
  695:   $Apache::lonxml::registered = 0;
  696:   $errorcount=0;
  697:   $warningcount=0;
  698:   $Apache::lonxml::default_homework_loaded=0;
  699:   $Apache::lonxml::usestyle=1;
  700:   &init_counter();
  701:   @Apache::lonxml::pwd=();
  702:   @Apache::lonxml::extlinks=();
  703:   if ($target eq 'meta') {
  704:     $Apache::lonxml::redirection = 0;
  705:     $Apache::lonxml::metamode = 1;
  706:     $Apache::lonxml::evaluate = 1;
  707:     $Apache::lonxml::import = 0;
  708:   } elsif ($target eq 'answer') {
  709:     $Apache::lonxml::redirection = 0;
  710:     $Apache::lonxml::metamode = 1;
  711:     $Apache::lonxml::evaluate = 1;
  712:     $Apache::lonxml::import = 1;
  713:   } elsif ($target eq 'grade') {
  714:     &startredirection;
  715:     $Apache::lonxml::metamode = 0;
  716:     $Apache::lonxml::evaluate = 1;
  717:     $Apache::lonxml::import = 1;
  718:   } elsif ($target eq 'modified') {
  719:     $Apache::lonxml::redirection = 0;
  720:     $Apache::lonxml::metamode = 0;
  721:     $Apache::lonxml::evaluate = 0;
  722:     $Apache::lonxml::import = 0;
  723:   } elsif ($target eq 'edit') {
  724:     $Apache::lonxml::redirection = 0;
  725:     $Apache::lonxml::metamode = 0;
  726:     $Apache::lonxml::evaluate = 0;
  727:     $Apache::lonxml::import = 0;
  728:   } elsif ($target eq 'analyze') {
  729:     $Apache::lonxml::redirection = 0;
  730:     $Apache::lonxml::metamode = 0;
  731:     $Apache::lonxml::evaluate = 1;
  732:     $Apache::lonxml::import = 1;
  733:   } else {
  734:     $Apache::lonxml::redirection = 0;
  735:     $Apache::lonxml::metamode = 0;
  736:     $Apache::lonxml::evaluate = 1;
  737:     $Apache::lonxml::import = 1;
  738:   }
  739: }
  740: 
  741: sub init_safespace {
  742:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  743:   $safeeval->permit("entereval");
  744:   $safeeval->permit(":base_math");
  745:   $safeeval->permit("sort");
  746:   $safeeval->deny(":base_io");
  747:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  748:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  749:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  750:   
  751:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  752:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  753:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  754:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  755:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  756:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  757:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  758:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  759:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  760:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  761:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  762:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  763:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  764:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  765:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  766:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  767:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  768:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  769:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  770:   
  771:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  772:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  773:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  774:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  775:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  776:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  777:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  778:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  779:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  780:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  781:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  782:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  783:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  784:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  785:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  786:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  787:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  788:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  789:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  790:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  791:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  792:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  793: 
  794: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  795: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  796: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  797: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  798: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  799: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  800: 
  801:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  802:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  803:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  804:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  805:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  806:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  807:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  808:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  809:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  810:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  811:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  812:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  813:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  814:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  815:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  816:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  817:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  818:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  819:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  820:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  821:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  822: 
  823: #need to inspect this class of ops
  824: # $safeeval->deny(":base_orig");
  825:   $safeinit .= ';$external::target="'.$target.'";';
  826:   my $rndseed;
  827:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  828:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  829:   $safeinit .= ';$external::randomseed='.$rndseed.';';
  830:   &Apache::lonxml::debug("Setting rndseed to $rndseed");
  831:   &Apache::run::run($safeinit,$safeeval);
  832: }
  833: 
  834: sub default_homework_load {
  835:     my ($safeeval)=@_;
  836:     &Apache::lonxml::debug('Loading default_homework');
  837:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  838:     if ($default eq -1) {
  839: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  840:     } else {
  841: 	&Apache::run::run($default,$safeeval);
  842: 	$Apache::lonxml::default_homework_loaded=1;
  843:     }
  844: }
  845: 
  846: sub startredirection {
  847:   $Apache::lonxml::redirection++;
  848:   push (@Apache::lonxml::outputstack, '');
  849: }
  850: 
  851: sub endredirection {
  852:   if (!$Apache::lonxml::redirection) {
  853:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  854:     return '';
  855:   }
  856:   $Apache::lonxml::redirection--;
  857:   pop @Apache::lonxml::outputstack;
  858: }
  859: 
  860: sub end_tag {
  861:   my ($tagstack,$parstack,$token)=@_;
  862:   pop(@$tagstack);
  863:   pop(@$parstack);
  864:   &decreasedepth($token);
  865: }
  866: 
  867: sub initdepth {
  868:   @Apache::lonxml::depthcounter=();
  869:   $Apache::lonxml::depth=-1;
  870:   $Apache::lonxml::olddepth=-1;
  871: }
  872: 
  873: sub increasedepth {
  874:   my ($token) = @_;
  875:   $Apache::lonxml::depth++;
  876:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  877:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  878:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  879:   }
  880:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  881:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  882: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  883: }
  884: 
  885: sub decreasedepth {
  886:   my ($token) = @_;
  887:   $Apache::lonxml::depth--;
  888:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  889:     $#Apache::lonxml::depthcounter--;
  890:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  891:   }
  892:   if (  $Apache::lonxml::depth < -1) {
  893:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
  894:     $Apache::lonxml::depth='-1';
  895:   }
  896:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  897:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  898: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  899: }
  900: 
  901: sub get_all_text_unbalanced {
  902: #there is a copy of this in lonpublisher.pm
  903:  my($tag,$pars)= @_;
  904:  my $token;
  905:  my $result='';
  906:  $tag='<'.$tag.'>';
  907:  while ($token = $$pars[-1]->get_token) {
  908:    if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  909:      $result.=$token->[1];
  910:    } elsif ($token->[0] eq 'PI') {
  911:      $result.=$token->[2];
  912:    } elsif ($token->[0] eq 'S') {
  913:      $result.=$token->[4];
  914:    } elsif ($token->[0] eq 'E')  {
  915:      $result.=$token->[2];
  916:    }
  917:    if ($result =~ /(.*)\Q$tag\E(.*)/s) {
  918:      &Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
  919:      &Apache::lonxml::debug('Result is :'.$1);
  920:      $result=$1;
  921:      my $redo=$tag.$2;
  922:      &Apache::lonxml::newparser($pars,\$redo);
  923:      last;
  924:    }
  925:  }
  926:  return $result
  927: }
  928: 
  929: sub increment_counter {
  930:     my ($increment) = @_;
  931:     if (defined($increment) && $increment gt 0) {
  932: 	$Apache::lonxml::counter+=$increment;
  933:     } else {
  934: 	$Apache::lonxml::counter++;
  935:     }
  936:     $Apache::lonxml::counter_changed=1;
  937: }
  938: 
  939: sub init_counter {
  940:     if (defined($ENV{'form.counter'})) {
  941: 	$Apache::lonxml::counter=$ENV{'form.counter'};
  942: 	$Apache::lonxml::counter_changed=0;
  943:     } else {
  944: 	$Apache::lonxml::counter=1;
  945: 	$Apache::lonxml::counter_changed=1;
  946:     }
  947: }
  948: 
  949: sub store_counter {
  950:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
  951:     return '';
  952: }
  953: 
  954: sub get_all_text {
  955:  my($tag,$pars)= @_;
  956:  &Apache::lonxml::debug("Got a ".ref($pars));
  957:  my $gotfullstack=1;
  958:  if (ref($pars) ne 'ARRAY') {
  959:      $gotfullstack=0;
  960:      $pars=[$pars];
  961:  }
  962:  my $depth=0;
  963:  my $token;
  964:  my $result='';
  965:  if ( $tag =~ m:^/: ) { 
  966:    my $tag=substr($tag,1); 
  967:    #&Apache::lonxml::debug("have:$tag:");
  968:    my $top_empty=0;
  969:    while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
  970:      while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
  971:        #&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
  972:        if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  973: 	 $result.=$token->[1];
  974:        } elsif ($token->[0] eq 'PI') {
  975: 	 $result.=$token->[2];
  976:        } elsif ($token->[0] eq 'S') {
  977: 	 if ($token->[1] =~ /^$tag$/i) { $depth++; }
  978: 	 $result.=$token->[4];
  979:        } elsif ($token->[0] eq 'E')  {
  980: 	 if ( $token->[1] =~ /^$tag$/i) { $depth--; }
  981: 	 #skip sending back the last end tag
  982: 	 if ($depth > -1) { $result.=$token->[2]; } else {
  983: 	   $$pars[-1]->unget_token($token);
  984: 	 }
  985:        }
  986:      }
  987:      if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
  988:      if (($depth >=0) && ($#$pars > 0) ) {
  989:        pop(@$pars);
  990:        pop(@Apache::lonxml::pwd);
  991:      }
  992:    }
  993:    if ($top_empty && $depth >= 0) {
  994:        #never found the end tag ran out of text, throw error send back blank
  995:        &error('Never found end tag for &lt;'.$tag.'&gt;');
  996:        if ($gotfullstack) {
  997: 	   my $newstring='</'.$tag.'>'.$result;
  998: 	   &Apache::lonxml::newparser($pars,\$newstring);
  999:        }
 1000:        $result='';
 1001:    }
 1002:  } else {
 1003:      while ($#$pars > -1) {
 1004: 	 while ($token = $$pars[-1]->get_token) {
 1005: 	     #&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
 1006: 	     if (($token->[0] eq 'T')||($token->[0] eq 'C')||
 1007: 		 ($token->[0] eq 'D')) {
 1008: 		 $result.=$token->[1];
 1009: 	     } elsif ($token->[0] eq 'PI') {
 1010: 		 $result.=$token->[2];
 1011: 	     } elsif ($token->[0] eq 'S') {
 1012: 		 if ( $token->[1] =~ /^$tag$/i) {
 1013: 		     $$pars[-1]->unget_token($token); last;
 1014: 		 } else {
 1015: 		     $result.=$token->[4];
 1016: 		 }
 1017: 	     } elsif ($token->[0] eq 'E')  {
 1018: 		 $result.=$token->[2];
 1019: 	     }
 1020: 	 }
 1021: 	 if (($#$pars > 0) ) {
 1022: 	     pop(@$pars);
 1023: 	     pop(@Apache::lonxml::pwd);
 1024: 	 } else { last; }
 1025:      }
 1026:  }
 1027:  if ($result =~ m|<LONCAPA_INTERNAL_TURN_STYLE_ON />|) {
 1028:      $Apache::lonxml::usestyle=1;
 1029:  }
 1030:  #&Apache::lonxml::debug("Exit:$result:");
 1031:  return $result
 1032: }
 1033: 
 1034: sub newparser {
 1035:   my ($parser,$contentref,$dir) = @_;
 1036:   push (@$parser,HTML::LCParser->new($contentref));
 1037:   $$parser['-1']->xml_mode('1');
 1038:   if ( $dir eq '' ) {
 1039:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1040:   } else {
 1041:     push (@Apache::lonxml::pwd, $dir);
 1042:   } 
 1043: }
 1044: 
 1045: sub parstring {
 1046:   my ($token) = @_;
 1047:   my $temp='';
 1048:   foreach (@{$token->[3]}) {
 1049:     unless ($_=~/\W/) {
 1050:       my $val=$token->[2]->{$_};
 1051:       $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1052:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1053:       $temp .= "my \$$_=\"$val\";";
 1054:     }
 1055:   }
 1056:   return $temp;
 1057: }
 1058: 
 1059: sub writeallows {
 1060:     unless ($#extlinks>=0) { return; }
 1061:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
 1062:     if ($ENV{'httpref.'.$thisurl}) {
 1063: 	$thisurl=$ENV{'httpref.'.$thisurl};
 1064:     }
 1065:     my $thisdir=$thisurl;
 1066:     $thisdir=~s/\/[^\/]+$//;
 1067:     my %httpref=();
 1068:     foreach (@extlinks) {
 1069:        $httpref{'httpref.'.
 1070:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1071:     }
 1072:     @extlinks=();
 1073:     &Apache::lonnet::appenv(%httpref);
 1074: }
 1075: 
 1076: #
 1077: # Afterburner handles anchors, highlights and links
 1078: #
 1079: sub afterburn {
 1080:     my $result=shift;
 1081:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1082: 					    ['highlight','anchor','link']);
 1083:     if ($ENV{'form.highlight'}) {
 1084:        foreach (split(/\,/,$ENV{'form.highlight'})) {
 1085:            my $anchorname=$_;
 1086: 	   my $matchthis=$anchorname;
 1087:            $matchthis=~s/\_+/\\s\+/g;
 1088:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1089:        }
 1090:     }
 1091:     if ($ENV{'form.link'}) {
 1092:        foreach (split(/\,/,$ENV{'form.link'})) {
 1093:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1094: 	   my $matchthis=$anchorname;
 1095:            $matchthis=~s/\_+/\\s\+/g;
 1096:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1097:        }
 1098:     }
 1099:     if ($ENV{'form.anchor'}) {
 1100:         my $anchorname=$ENV{'form.anchor'};
 1101: 	my $matchthis=$anchorname;
 1102:         $matchthis=~s/\_+/\\s\+/g;
 1103:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1104:         $result.=(<<"ENDSCRIPT");
 1105: <script type="text/javascript">
 1106:     document.location.hash='$anchorname';
 1107: </script>
 1108: ENDSCRIPT
 1109:     }
 1110:     return $result;
 1111: }
 1112: 
 1113: sub storefile {
 1114:     my ($file,$contents)=@_;
 1115:     if (my $fh=Apache::File->new('>'.$file)) {
 1116: 	print $fh $contents;
 1117:         $fh->close();
 1118:     } else {
 1119:       &warning("Unable to save file $file");
 1120:     }
 1121: }
 1122: 
 1123: sub createnewhtml {
 1124:   my $filecontents=(<<SIMPLECONTENT);
 1125: <html>
 1126: <head>
 1127: <title>
 1128:                            Title of Document Goes Here
 1129: </title>
 1130: </head>
 1131: <body bgcolor="#FFFFFF">
 1132: 
 1133:                            Body of Document Goes Here
 1134: 
 1135: </body>
 1136: </html>
 1137: SIMPLECONTENT
 1138:   return $filecontents;
 1139: }
 1140: 
 1141: 
 1142: sub inserteditinfo {
 1143:       my ($result,$filecontents)=@_;
 1144:       $filecontents = &HTML::Entities::encode($filecontents);
 1145: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1146:       my $xml_help = Apache::loncommon::helpLatexCheatsheet();
 1147:       my $titledisplay=&display_title();
 1148:       my $buttons=(<<BUTTONS);
 1149: <input type="submit" name="attemptclean" 
 1150:        value="Save and then attempt to clean HTML" />
 1151: <input type="submit" name="savethisfile" value="Save this" />
 1152: <input type="submit" name="viewmode" value="View" />
 1153: BUTTONS
 1154:       my $editfooter=(<<ENDFOOTER);
 1155: <hr />
 1156: <a name="editsection" />
 1157: <form method="post">
 1158: $xml_help
 1159: <input type="hidden" name="editmode" value="Edit" />
 1160: $buttons<br />
 1161: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
 1162: <br />$buttons
 1163: <br />
 1164: </form>
 1165: $titledisplay
 1166: ENDFOOTER
 1167: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1168:       $result=~s/(\<\/body\>)/$editfooter/is;
 1169:       return $result;
 1170: }
 1171: 
 1172: sub get_target {
 1173:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
 1174:   if ( $ENV{'request.state'} eq 'published') {
 1175:     if ( defined($ENV{'form.grade_target'})
 1176: 	 && ($viewgrades == 'F' )) {
 1177:       return ($ENV{'form.grade_target'});
 1178:     } elsif (defined($ENV{'form.grade_target'})) {
 1179:       if (($ENV{'form.grade_target'} eq 'web') ||
 1180: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
 1181: 	return $ENV{'form.grade_target'}
 1182:       } else {
 1183: 	return 'web';
 1184:       }
 1185:     } else {
 1186:       return 'web';
 1187:     }
 1188:   } elsif ($ENV{'request.state'} eq 'construct') {
 1189:     if ( defined($ENV{'form.grade_target'})) {
 1190:       return ($ENV{'form.grade_target'});
 1191:     } else {
 1192:       return 'web';
 1193:     }
 1194:   } else {
 1195:     return 'web';
 1196:   }
 1197: }
 1198: 
 1199: sub handler {
 1200:     my $request=shift;
 1201:     
 1202:     my $target=&get_target();
 1203:     
 1204:     $Apache::lonxml::debug=$ENV{'user.debug'};
 1205:     
 1206:     if ($ENV{'browser.mathml'}) {
 1207: 	$request->content_type('text/xml');
 1208:     } else {
 1209: 	$request->content_type('text/html');
 1210:     }
 1211:     &Apache::loncommon::no_cache($request);
 1212:     $request->send_http_header;
 1213:     
 1214:     return OK if $request->header_only;
 1215: 
 1216: 
 1217:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1218: #
 1219: # Edit action? Save file.
 1220: #
 1221:     unless ($ENV{'request.state'} eq 'published') {
 1222: 	if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
 1223: 	    &storefile($file,$ENV{'form.filecont'});
 1224: 	}
 1225:     }
 1226:     my %mystyle;
 1227:     my $result = '';
 1228:     my $filecontents=&Apache::lonnet::getfile($file);
 1229:     if ($filecontents eq -1) {
 1230: 	$result=(<<ENDNOTFOUND);
 1231: <html>
 1232: <head>
 1233: <title>File not found</title>
 1234: </head>
 1235: <body bgcolor="#FFFFFF">
 1236: <b>File not found: $file</b>
 1237: </body>
 1238: </html>
 1239: ENDNOTFOUND
 1240:     $filecontents='';
 1241: 	if ($ENV{'request.state'} ne 'published') {
 1242: 	    $filecontents=&createnewhtml();
 1243: 	    $ENV{'form.editmode'}='Edit'; #force edit mode
 1244: 	}
 1245:     } else {
 1246: 	unless ($ENV{'request.state'} eq 'published') {
 1247: 	    if ($ENV{'form.attemptclean'}) {
 1248: 		$filecontents=&htmlclean($filecontents,1);
 1249: 	    }
 1250: #
 1251: # we are in construction space, see if edit mode forced
 1252:             &Apache::loncommon::get_unprocessed_cgi
 1253:                           ($ENV{'QUERY_STRING'},['editmode']);
 1254: 	}
 1255: 	if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
 1256: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
 1257: 						'',%mystyle);
 1258: 	}
 1259:     }
 1260:     
 1261: #
 1262: # Edit action? Insert editing commands
 1263: #
 1264:     unless ($ENV{'request.state'} eq 'published') {
 1265: 	if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
 1266: 	    my $displayfile=$request->uri;
 1267: 	    $displayfile=~s/^\/[^\/]*//;
 1268: 	    $result='<html><body bgcolor="#FFFFFF"><h3>'.$displayfile.
 1269: 		'</h3></body></html>';
 1270: 	    $result=&inserteditinfo($result,$filecontents);
 1271: 	}
 1272:     }
 1273:     
 1274:     writeallows($request->uri);
 1275:     
 1276: 
 1277:     $request->print($result);
 1278:     
 1279:     return OK;
 1280: }
 1281: 
 1282: sub display_title {
 1283:     my $result;
 1284:     if ($ENV{'request.state'} eq 'construct') {
 1285: 	my $title=&Apache::lonnet::gettitle();
 1286: 	if (!defined($title) || $title eq '') {
 1287: 	    $title = $ENV{'request.filename'};
 1288: 	    $title = substr($title, rindex($title, '/') + 1);
 1289: 	}
 1290: 	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
 1291:     }
 1292:     return $result;
 1293: }
 1294: 
 1295: sub debug {
 1296:   if ($Apache::lonxml::debug eq 1) {
 1297:     $|=1;
 1298:     print('<font size="-2"<pre>DEBUG:'.&HTML::Entities::encode($_[0])."</pre></font>\n");
 1299:   }
 1300: }
 1301: 
 1302: sub error {
 1303:   $errorcount++;
 1304:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
 1305:     # If printing in construction space, put the error inside <pre></pre>
 1306:     print "<b>ERROR:</b>".join("\n",@_)."\n";
 1307:   } else {
 1308:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
 1309:     #notify author
 1310:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
 1311:     #notify course
 1312:     if ( $ENV{'request.course.id'} ) {
 1313:       my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
 1314:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
 1315:       foreach (keys %users) {
 1316: 	my ($user,$domain) = split(/:/, $_);
 1317: 	&Apache::lonmsg::user_normal_msg($user,$domain,
 1318:         "Error [$declutter]",join('<br />',@_));
 1319:       }
 1320:     }
 1321: 
 1322:     #FIXME probably shouldn't have me get everything forever.
 1323:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
 1324:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
 1325:   }
 1326: }
 1327: 
 1328: sub warning {
 1329:   $warningcount++;
 1330:   
 1331:   if ($ENV{'form.grade_target'} ne 'tex') {
 1332:       if ($ENV{'request.state'} eq 'construct' || $Apache::lonxml::debug) {
 1333:         print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
 1334:       }
 1335:   }
 1336: }
 1337: 
 1338: sub get_param {
 1339:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1340:     if ( ! $context ) { $context = -1; }
 1341:     my $args ='';
 1342:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1343:     if ( ! $args ) { return undef; }
 1344:     if ( $case_insensitive ) {
 1345: 	if ($args =~ s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei) {
 1346: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1347:                                      $safeeval); #'
 1348: 	} else {
 1349: 	    return undef;
 1350: 	}
 1351:     } else {
 1352: 	if ( $args =~ /my \$\Q$param\E=\"/ ) {
 1353: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1354:                                      $safeeval); #'
 1355: 	} else {
 1356: 	    return undef;
 1357: 	}
 1358:     }
 1359: }
 1360: 
 1361: sub get_param_var {
 1362:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1363:   if ( ! $context ) { $context = -1; }
 1364:   my $args ='';
 1365:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1366:   &Apache::lonxml::debug("Args are $args param is $param");
 1367:   if ($case_insensitive) {
 1368:       if (! ($args=~s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei)) {
 1369: 	  return undef;
 1370:       }
 1371:   } elsif ( $args !~ /my \$\Q$param\E=\"/ ) { return undef; }
 1372:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1373:   &Apache::lonxml::debug("first run is $value");
 1374:   if ($value =~ /^[\$\@\%]\w+$/) {
 1375:       &Apache::lonxml::debug("doing second");
 1376:       my @result=&Apache::run::run("return $value",$safeeval,1);
 1377:       if (!defined($result[0])) {
 1378: 	  return $value
 1379:       } else {
 1380: 	  if (wantarray) { return @result; } else { return $result[0]; }
 1381:       }
 1382:   } else {
 1383:     return $value;
 1384:   }
 1385: }
 1386: 
 1387: sub register_insert {
 1388:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1389:   my $i;
 1390:   my $tagnum=0;
 1391:   my @order;
 1392:   for ($i=0;$i < $#data; $i++) {
 1393:     my $line = $data[$i];
 1394:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1395:     if ( $line =~ /TABLE/ ) { last; }
 1396:     my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
 1397:     if ($tag) {
 1398:       $insertlist{"$tagnum.tag"} = $tag;
 1399:       $insertlist{"$tagnum.description"} = $descrip;
 1400:       $insertlist{"$tagnum.color"} = $color;
 1401:       $insertlist{"$tagnum.function"} = $function;
 1402:       if (!defined($show)) { $show='yes'; }
 1403:       $insertlist{"$tagnum.show"}= $show;
 1404:       $insertlist{"$tagnum.helpfile"} = $helpfile;
 1405:       $insertlist{"$tagnum.helpdesc"} = $helpdesc;
 1406:       $insertlist{"$tag.num"}=$tagnum;
 1407:       $tagnum++;
 1408:     }
 1409:   }
 1410:   $i++; #skipping TABLE line
 1411:   $tagnum = 0;
 1412:   for (;$i < $#data;$i++) {
 1413:     my $line = $data[$i];
 1414:     my ($mnemonic,@which) = split(/ +/,$line);
 1415:     my $tag = $insertlist{"$tagnum.tag"};
 1416:     for (my $j=0;$j <=$#which;$j++) {
 1417:       if ( $which[$j] eq 'Y' ) {
 1418: 	if ($insertlist{"$j.show"} ne 'no') {
 1419: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1420: 	}
 1421:       }
 1422:     }
 1423:     $tagnum++;
 1424:   }
 1425: }
 1426: 
 1427: sub description {
 1428:   my ($token)=@_;
 1429:   my $tagnum;
 1430:   my $tag=$token->[1];
 1431:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1432:     my $testtag=$namespace.'::'.$tag;
 1433:     $tagnum=$insertlist{"$testtag.num"};
 1434:     if (defined($tagnum)) { last; }
 1435:   }
 1436:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1437:   return $insertlist{$tagnum.'.description'};
 1438: }
 1439: 
 1440: # Returns a list containing the help file, and the description
 1441: sub helpinfo {
 1442:   my ($token)=@_;
 1443:   my $tagnum;
 1444:   my $tag=$token->[1];
 1445:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1446:     my $testtag=$namespace.'::'.$tag;
 1447:     $tagnum=$insertlist{"$testtag.num"};
 1448:     if (defined($tagnum)) { last; }
 1449:   }
 1450:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1451:   return ($insertlist{$tagnum.'.helpfile'}, $insertlist{$tagnum.'.helpdesc'});
 1452: }
 1453: 
 1454: # ----------------------------------------------------------------- whichuser
 1455: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1456: # calls to lonnet functions for this setup.
 1457: # - looks for form.grade_ parameters
 1458: sub whichuser {
 1459:   my ($passedsymb)=@_;
 1460:   my ($symb,$courseid,$domain,$name,$publicuser);
 1461:   if (defined($ENV{'form.grade_symb'})) {
 1462:     my $tmp_courseid=$ENV{'form.grade_courseid'};
 1463:     my $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid);
 1464:     if ($allowed) {
 1465:       $symb=$ENV{'form.grade_symb'};
 1466:       $courseid=$ENV{'form.grade_courseid'};
 1467:       $domain=$ENV{'form.grade_domain'};
 1468:       $name=$ENV{'form.grade_username'};
 1469:     }
 1470:   } else {
 1471:       if (!$passedsymb) {
 1472:           $symb=&Apache::lonnet::symbread();
 1473:       } else {
 1474:           $symb=$passedsymb;
 1475:       }
 1476:       $courseid=$ENV{'request.course.id'};
 1477:       $domain=$ENV{'user.domain'};
 1478:       $name=$ENV{'user.name'};
 1479:       if ($name eq 'public' && $domain eq 'public') {
 1480: 	  if (!defined($ENV{'form.username'})) {
 1481: 	      $ENV{'form.username'}.=time.rand(10000000);
 1482: 	  }
 1483: 	  $name.=$ENV{'form.username'};
 1484:       }
 1485:   }
 1486:   return ($symb,$courseid,$domain,$name,$publicuser);
 1487: }
 1488: 
 1489: 1;
 1490: __END__
 1491: 
 1492: 

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