File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.259: download - view: text, annotated - select for diffs
Thu May 29 18:41:04 2003 UTC (20 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- end style tags need to get the parameter values for the start style tag, which is some arbitrary location in the tag stack, not -1

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

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