File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.277: download - view: text, annotated - select for diffs
Mon Sep 15 13:38:19 2003 UTC (20 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Further cleanup of spaghetti between lonxml::xmlend and
lonfeedback::list_discussion in preparation of an overhaul of
the discussion feature.

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

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