File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.272: download - view: text, annotated - select for diffs
Wed Aug 13 18:57:28 2003 UTC (20 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- cleanup latex_special_symbols call (unnneeded middle parameters)

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

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