File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.266.2.1: download - view: text, annotated - select for diffs
Thu Aug 7 19:31:16 2003 UTC (20 years, 9 months ago) by albertel
Branches: version_0_99_4
CVS tags: version_1_0_1, version_1_0_0, version_0_99_5
- backport 1.269

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

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