File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.317: download - view: text, annotated - select for diffs
Thu Apr 15 20:18:46 2004 UTC (20 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- the tag  <annoy)guy> is valid. :-)

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

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