File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.296: download - view: text, annotated - select for diffs
Tue Dec 9 16:52:13 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_1_1_0, version_1_0_99_3, version_1_0_99_2, version_1_0_99_1, HEAD
Revert back to revision 1.293 due to bug #2420

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

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