File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.281: download - view: text, annotated - select for diffs
Sat Sep 27 04:08:56 2003 UTC (20 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Can't do Apache::lonnet::ssi when &xmlparse()ing from inside the safe space, register the url and call it after we absolutely out of the safe space.

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

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