File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.276: download - view: text, annotated - select for diffs
Sun Sep 14 23:57:18 2003 UTC (20 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
In preparation for implementing threaded discussion and disentangling COM
from FDBK, disentagle the subroutines - there is really no reason for the
discussion display to be embedded into lonxml.

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.276 2003/09/14 23:57:18 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:     my ($discussiononly,$symb)=@_;
  179:     my $discussion='';
  180:     if ($ENV{'request.course.id'}) {
  181:        my $crs='/'.$ENV{'request.course.id'};
  182:        if ($ENV{'request.course.sec'}) {
  183:           $crs.='_'.$ENV{'request.course.sec'};
  184:        }                 
  185:        $crs=~s/\_/\//g;
  186:        $discussion=&Apache::lonfeedback::list_discussion
  187: 	   ($crs,$symb,$discussiononly);
  188:     }
  189:     return $discussion.($discussiononly?'':'</html>');
  190: }
  191: 
  192: sub tokeninputfield {
  193:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  194:     $defhost=~tr/a-z/A-Z/;
  195:     return (<<ENDINPUTFIELD)
  196: <script type="text/javascript">
  197:     function updatetoken() {
  198: 	var comp=new Array;
  199:         var barcode=unescape(document.tokeninput.barcode.value);
  200:         comp=barcode.split('*');
  201:         if (typeof(comp[0])!="undefined") {
  202: 	    document.tokeninput.codeone.value=comp[0];
  203: 	}
  204:         if (typeof(comp[1])!="undefined") {
  205: 	    document.tokeninput.codetwo.value=comp[1];
  206: 	}
  207:         if (typeof(comp[2])!="undefined") {
  208:             comp[2]=comp[2].toUpperCase();
  209: 	    document.tokeninput.codethree.value=comp[2];
  210: 	}
  211:         document.tokeninput.barcode.value='';
  212:     }  
  213: </script>
  214: <form method="post" name="tokeninput">
  215: <table border="2" bgcolor="#FFFFBB">
  216: <tr><th>DocID Checkin</th></tr>
  217: <tr><td>
  218: <table>
  219: <tr>
  220: <td>Scan in Barcode</td>
  221: <td><input type="text" size="22" name="barcode" 
  222: onChange="updatetoken()"/></td>
  223: </tr>
  224: <tr><td><i>or</i> Type in DocID</td>
  225: <td>
  226: <input type="text" size="5" name="codeone" />
  227: <b><font size="+2">*</font></b>
  228: <input type="text" size="5" name="codetwo" />
  229: <b><font size="+2">*</font></b>
  230: <input type="text" size="10" name="codethree" value="$defhost" 
  231: onChange="this.value=this.value.toUpperCase()" />
  232: </td></tr>
  233: </table>
  234: </td></tr>
  235: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  236: </table>
  237: </form>
  238: ENDINPUTFIELD
  239: }
  240: 
  241: sub maketoken {
  242:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  243:     unless ($symb) {
  244: 	$symb=&Apache::lonnet::symbread();
  245:     }
  246:     unless ($tuname) {
  247: 	$tuname=$ENV{'user.name'};
  248:         $tudom=$ENV{'user.domain'};
  249:         $tcrsid=$ENV{'request.course.id'};
  250:     }
  251: 
  252:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  253: }
  254: 
  255: sub printtokenheader {
  256:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  257:     unless ($token) { return ''; }
  258: 
  259:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  260:     unless ($tsymb) {
  261: 	$tsymb=$symb;
  262:     }
  263:     unless ($tuname) {
  264: 	$tuname=$name;
  265:         $tudom=$domain;
  266:         $tcrsid=$courseid;
  267:     }
  268: 
  269:     my %reply=&Apache::lonnet::get('environment',
  270:               ['firstname','middlename','lastname','generation'],
  271:               $tudom,$tuname);
  272:     my $plainname=$reply{'firstname'}.' '. 
  273:                   $reply{'middlename'}.' '.
  274:                   $reply{'lastname'}.' '.
  275: 		  $reply{'generation'};
  276: 
  277:     if ($target eq 'web') {
  278:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  279: 	return 
  280:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  281:                'Checked out for '.$plainname.
  282:                '<br />User: '.$tuname.' at '.$tudom.
  283: 	       '<br />ID: '.$idhash{$tuname}.
  284: 	       '<br />CourseID: '.$tcrsid.
  285: 	       '<br />Course: '.$ENV{'course.'.$tcrsid.'.description'}.
  286:                '<br />DocID: '.$token.
  287:                '<br />Time: '.localtime().'<hr />';
  288:     } else {
  289:         return $token;
  290:     }
  291: }
  292: 
  293: sub fontsettings() {
  294:     my $headerstring='';
  295:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
  296: 	$headerstring.=
  297: 	    '<meta Content-Type="text/html; charset=x-mac-roman">';
  298:     } elsif (!$ENV{'browser.mathml'} && $ENV{'browser.unicode'}) {
  299: 	$headerstring.=
  300: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  301:     }
  302:     return $headerstring;
  303: }
  304: 
  305: sub printalltags {
  306:   my $temp;
  307:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  308:     &Apache::lonxml::debug("$temp -- ".
  309: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  310:   }
  311: }
  312: 
  313: sub xmlparse {
  314:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  315: 
  316:  &setup_globals($request,$target);
  317:  &Apache::inputtags::initialize_inputtags();
  318:  &Apache::outputtags::initialize_outputtags();
  319:  &Apache::edit::initialize_edit();
  320: 
  321: #
  322: # do we have a course style file?
  323: #
  324: 
  325:  if ($ENV{'request.course.id'} && $ENV{'request.state'} ne 'construct') {
  326:      my $bodytext=
  327: 	 $ENV{'course.'.$ENV{'request.course.id'}.'.default_xml_style'};
  328:      if ($bodytext) {
  329:        my $location=&Apache::lonnet::filelocation('',$bodytext);
  330:        my $styletext=&Apache::lonnet::getfile($location);
  331:        if ($styletext ne '-1') {
  332:           %style_for_target = (%style_for_target,
  333:                           &Apache::style::styleparser($target,$styletext));
  334:        }
  335:     }
  336:  }
  337: #&printalltags();
  338:  my @pars = ();
  339:  my $pwd=$ENV{'request.filename'};
  340:  $pwd =~ s:/[^/]*$::;
  341:  &newparser(\@pars,\$content_file_string,$pwd);
  342: 
  343:  my $safeeval = new Safe;
  344:  my $safehole = new Safe::Hole;
  345:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  346: #-------------------- Redefinition of the target in the case of compound target
  347: 
  348:  ($target, my @tenta) = split('&&',$target);
  349: 
  350:  my @stack = ();
  351:  my @parstack = ();
  352:  &initdepth;
  353: 
  354:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  355: 				   $safeeval,\%style_for_target);
  356: 
  357:  if ($ENV{'request.uri'}) {
  358:     &writeallows($ENV{'request.uri'});
  359:  }
  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:   if ($target eq 'meta') {
  611:     $Apache::lonxml::redirection = 0;
  612:     $Apache::lonxml::metamode = 1;
  613:     $Apache::lonxml::evaluate = 1;
  614:     $Apache::lonxml::import = 0;
  615:   } elsif ($target eq 'answer') {
  616:     $Apache::lonxml::redirection = 0;
  617:     $Apache::lonxml::metamode = 1;
  618:     $Apache::lonxml::evaluate = 1;
  619:     $Apache::lonxml::import = 1;
  620:   } elsif ($target eq 'grade') {
  621:     &startredirection;
  622:     $Apache::lonxml::metamode = 0;
  623:     $Apache::lonxml::evaluate = 1;
  624:     $Apache::lonxml::import = 1;
  625:   } elsif ($target eq 'modified') {
  626:     $Apache::lonxml::redirection = 0;
  627:     $Apache::lonxml::metamode = 0;
  628:     $Apache::lonxml::evaluate = 0;
  629:     $Apache::lonxml::import = 0;
  630:   } elsif ($target eq 'edit') {
  631:     $Apache::lonxml::redirection = 0;
  632:     $Apache::lonxml::metamode = 0;
  633:     $Apache::lonxml::evaluate = 0;
  634:     $Apache::lonxml::import = 0;
  635:   } elsif ($target eq 'analyze') {
  636:     $Apache::lonxml::redirection = 0;
  637:     $Apache::lonxml::metamode = 0;
  638:     $Apache::lonxml::evaluate = 1;
  639:     $Apache::lonxml::import = 1;
  640:   } else {
  641:     $Apache::lonxml::redirection = 0;
  642:     $Apache::lonxml::metamode = 0;
  643:     $Apache::lonxml::evaluate = 1;
  644:     $Apache::lonxml::import = 1;
  645:   }
  646: }
  647: 
  648: sub init_safespace {
  649:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  650:   $safeeval->permit("entereval");
  651:   $safeeval->permit(":base_math");
  652:   $safeeval->permit("sort");
  653:   $safeeval->deny(":base_io");
  654:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  655:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
  656:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  657:   
  658:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  659:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  660:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  661:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  662:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  663:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  664:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  665:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  666:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  667:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  668:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  669:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  670:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  671:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  672:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  673:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  674:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  675:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  676:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  677:   
  678:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  679:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  680:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  681:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  682:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  683:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  684:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  685:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  686:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  687:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  688:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  689:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  690:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  691:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  692:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  693:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  694:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  695:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  696:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  697:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  698:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  699:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  700: 
  701: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  702: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  703: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  704: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  705: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  706: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  707: 
  708:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  709:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  710:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  711:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  712:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  713:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  714:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  715:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  716:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  717:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  718:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  719:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  720:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  721:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  722:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  723:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  724:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  725:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  726:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  727:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  728:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  729: 
  730: #need to inspect this class of ops
  731: # $safeeval->deny(":base_orig");
  732:   $safeinit .= ';$external::target="'.$target.'";';
  733:   my $rndseed;
  734:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  735:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  736:   $safeinit .= ';$external::randomseed='.$rndseed.';';
  737:   &Apache::lonxml::debug("Setting rndseed to $rndseed");
  738:   &Apache::run::run($safeinit,$safeeval);
  739: }
  740: 
  741: sub default_homework_load {
  742:     my ($safeeval)=@_;
  743:     &Apache::lonxml::debug('Loading default_homework');
  744:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  745:     if ($default eq -1) {
  746: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  747:     } else {
  748: 	&Apache::run::run($default,$safeeval);
  749: 	$Apache::lonxml::default_homework_loaded=1;
  750:     }
  751: }
  752: 
  753: sub startredirection {
  754:   $Apache::lonxml::redirection++;
  755:   push (@Apache::lonxml::outputstack, '');
  756: }
  757: 
  758: sub endredirection {
  759:   if (!$Apache::lonxml::redirection) {
  760:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  761:     return '';
  762:   }
  763:   $Apache::lonxml::redirection--;
  764:   pop @Apache::lonxml::outputstack;
  765: }
  766: 
  767: sub end_tag {
  768:   my ($tagstack,$parstack,$token)=@_;
  769:   pop(@$tagstack);
  770:   pop(@$parstack);
  771:   &decreasedepth($token);
  772: }
  773: 
  774: sub initdepth {
  775:   @Apache::lonxml::depthcounter=();
  776:   $Apache::lonxml::depth=-1;
  777:   $Apache::lonxml::olddepth=-1;
  778: }
  779: 
  780: sub increasedepth {
  781:   my ($token) = @_;
  782:   $Apache::lonxml::depth++;
  783:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  784:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  785:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  786:   }
  787:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  788:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  789: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  790: }
  791: 
  792: sub decreasedepth {
  793:   my ($token) = @_;
  794:   $Apache::lonxml::depth--;
  795:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  796:     $#Apache::lonxml::depthcounter--;
  797:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  798:   }
  799:   if (  $Apache::lonxml::depth < -1) {
  800:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
  801:     $Apache::lonxml::depth='-1';
  802:   }
  803:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  804:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  805: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  806: }
  807: 
  808: sub get_all_text_unbalanced {
  809: #there is a copy of this in lonpublisher.pm
  810:  my($tag,$pars)= @_;
  811:  my $token;
  812:  my $result='';
  813:  $tag='<'.$tag.'>';
  814:  while ($token = $$pars[-1]->get_token) {
  815:    if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  816:      $result.=$token->[1];
  817:    } elsif ($token->[0] eq 'PI') {
  818:      $result.=$token->[2];
  819:    } elsif ($token->[0] eq 'S') {
  820:      $result.=$token->[4];
  821:    } elsif ($token->[0] eq 'E')  {
  822:      $result.=$token->[2];
  823:    }
  824:    if ($result =~ /(.*)\Q$tag\E(.*)/s) {
  825:      &Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
  826:      &Apache::lonxml::debug('Result is :'.$1);
  827:      $result=$1;
  828:      my $redo=$tag.$2;
  829:      &Apache::lonxml::newparser($pars,\$redo);
  830:      last;
  831:    }
  832:  }
  833:  return $result
  834: }
  835: 
  836: sub increment_counter {
  837:     my ($increment) = @_;
  838:     if (defined($increment) && $increment gt 0) {
  839: 	$Apache::lonxml::counter+=$increment;
  840:     } else {
  841: 	$Apache::lonxml::counter++;
  842:     }
  843:     $Apache::lonxml::counter_changed=1;
  844: }
  845: 
  846: sub init_counter {
  847:     if (defined($ENV{'form.counter'})) {
  848: 	$Apache::lonxml::counter=$ENV{'form.counter'};
  849: 	$Apache::lonxml::counter_changed=0;
  850:     } else {
  851: 	$Apache::lonxml::counter=1;
  852: 	$Apache::lonxml::counter_changed=1;
  853:     }
  854: }
  855: 
  856: sub store_counter {
  857:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
  858:     return '';
  859: }
  860: 
  861: sub get_all_text {
  862:     my($tag,$pars,$style)= @_;
  863:     &Apache::lonxml::debug("Got a ".ref($pars));
  864:     my $gotfullstack=1;
  865:     if (ref($pars) ne 'ARRAY') {
  866: 	$gotfullstack=0;
  867: 	$pars=[$pars];
  868:     }
  869:     &Apache::lonxml::debug("Got a ".ref($style));
  870:     if (ref($style) ne 'HASH') {
  871: 	$style={};
  872:     } else {
  873: 	&Apache::lonhomework::showhash(%$style);
  874:     }
  875:     my $depth=0;
  876:     my $token;
  877:     my $result='';
  878:     if ( $tag =~ m:^/: ) { 
  879: 	my $tag=substr($tag,1); 
  880: 	#&Apache::lonxml::debug("have:$tag:");
  881: 	my $top_empty=0;
  882: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
  883: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
  884: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
  885: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  886: 		    $result.=$token->[1];
  887: 		} elsif ($token->[0] eq 'PI') {
  888: 		    $result.=$token->[2];
  889: 		} elsif ($token->[0] eq 'S') {
  890: 		    if ($token->[1] =~ /^$tag$/i) { $depth++; }
  891: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/i) { $Apache::lonxml::usestyle=1; }
  892: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/i) { $Apache::lonxml::usestyle=0; }
  893: 		    $result.=$token->[4];
  894: 		} elsif ($token->[0] eq 'E')  {
  895: 		    if ( $token->[1] =~ /^$tag$/i) { $depth--; }
  896: 		    #skip sending back the last end tag
  897: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]})) {
  898: 			my $string=
  899: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
  900: 				$$style{'/'.$token->[1]}.
  901: 				    $token->[2].
  902: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  903: 			&Apache::lonxml::newparser($pars,\$string);
  904: 			#&Apache::lonxml::debug("reParsing $string");
  905: 			next;
  906: 		    }
  907: 		    if ($depth > -1) {
  908: 			$result.=$token->[2];
  909: 		    } else {
  910: 			$$pars[-1]->unget_token($token);
  911: 		    }
  912: 		}
  913: 	    }
  914: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
  915: 	    if (($depth >=0) && ($#$pars > 0) ) {
  916: 		pop(@$pars);
  917: 		pop(@Apache::lonxml::pwd);
  918: 	    }
  919: 	}
  920: 	if ($top_empty && $depth >= 0) {
  921: 	    #never found the end tag ran out of text, throw error send back blank
  922: 	    &error('Never found end tag for &lt;'.$tag.
  923: 		   '&gt; current string <pre>'.
  924: 		   &HTML::Entities::encode($result).
  925: 		   '</pre>');
  926: 	    if ($gotfullstack) {
  927: 		my $newstring='</'.$tag.'>'.$result;
  928: 		&Apache::lonxml::newparser($pars,\$newstring);
  929: 	    }
  930: 	    $result='';
  931: 	}
  932:     } else {
  933: 	while ($#$pars > -1) {
  934: 	    while ($token = $$pars[-1]->get_token) {
  935: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
  936: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
  937: 		    ($token->[0] eq 'D')) {
  938: 		    $result.=$token->[1];
  939: 		} elsif ($token->[0] eq 'PI') {
  940: 		    $result.=$token->[2];
  941: 		} elsif ($token->[0] eq 'S') {
  942: 		    if ( $token->[1] =~ /^$tag$/i) {
  943: 			$$pars[-1]->unget_token($token); last;
  944: 		    } else {
  945: 			$result.=$token->[4];
  946: 		    }
  947: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/i) { $Apache::lonxml::usestyle=1; }
  948: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/i) { $Apache::lonxml::usestyle=0; }
  949: 		} elsif ($token->[0] eq 'E')  {
  950: 		    $result.=$token->[2];
  951: 		}
  952: 	    }
  953: 	    if (($#$pars > 0) ) {
  954: 		pop(@$pars);
  955: 		pop(@Apache::lonxml::pwd);
  956: 	    } else { last; }
  957: 	}
  958:     }
  959:     #&Apache::lonxml::debug("Exit:$result:");
  960:     return $result
  961: }
  962: 
  963: sub newparser {
  964:   my ($parser,$contentref,$dir) = @_;
  965:   push (@$parser,HTML::LCParser->new($contentref));
  966:   $$parser['-1']->xml_mode('1');
  967:   if ( $dir eq '' ) {
  968:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
  969:   } else {
  970:     push (@Apache::lonxml::pwd, $dir);
  971:   } 
  972: }
  973: 
  974: sub parstring {
  975:   my ($token) = @_;
  976:   my $temp='';
  977:   foreach (@{$token->[3]}) {
  978:     unless ($_=~/\W/) {
  979:       my $val=$token->[2]->{$_};
  980:       $val =~ s/([\%\@\\\"\'])/\\$1/g;
  981:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
  982:       $temp .= "my \$$_=\"$val\";";
  983:     }
  984:   }
  985:   return $temp;
  986: }
  987: 
  988: sub writeallows {
  989:     unless ($#extlinks>=0) { return; }
  990:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
  991:     if ($ENV{'httpref.'.$thisurl}) {
  992: 	$thisurl=$ENV{'httpref.'.$thisurl};
  993:     }
  994:     my $thisdir=$thisurl;
  995:     $thisdir=~s/\/[^\/]+$//;
  996:     my %httpref=();
  997:     foreach (@extlinks) {
  998:        $httpref{'httpref.'.
  999:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1000:     }
 1001:     @extlinks=();
 1002:     &Apache::lonnet::appenv(%httpref);
 1003: }
 1004: 
 1005: #
 1006: # Afterburner handles anchors, highlights and links
 1007: #
 1008: sub afterburn {
 1009:     my $result=shift;
 1010:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1011: 					    ['highlight','anchor','link']);
 1012:     if ($ENV{'form.highlight'}) {
 1013:        foreach (split(/\,/,$ENV{'form.highlight'})) {
 1014:            my $anchorname=$_;
 1015: 	   my $matchthis=$anchorname;
 1016:            $matchthis=~s/\_+/\\s\+/g;
 1017:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1018:        }
 1019:     }
 1020:     if ($ENV{'form.link'}) {
 1021:        foreach (split(/\,/,$ENV{'form.link'})) {
 1022:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1023: 	   my $matchthis=$anchorname;
 1024:            $matchthis=~s/\_+/\\s\+/g;
 1025:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1026:        }
 1027:     }
 1028:     if ($ENV{'form.anchor'}) {
 1029:         my $anchorname=$ENV{'form.anchor'};
 1030: 	my $matchthis=$anchorname;
 1031:         $matchthis=~s/\_+/\\s\+/g;
 1032:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1033:         $result.=(<<"ENDSCRIPT");
 1034: <script type="text/javascript">
 1035:     document.location.hash='$anchorname';
 1036: </script>
 1037: ENDSCRIPT
 1038:     }
 1039:     return $result;
 1040: }
 1041: 
 1042: sub storefile {
 1043:     my ($file,$contents)=@_;
 1044:     if (my $fh=Apache::File->new('>'.$file)) {
 1045: 	print $fh $contents;
 1046:         $fh->close();
 1047:         return 1;
 1048:     } else {
 1049: 	&warning("Unable to save file $file");
 1050: 	return 0;
 1051:     }
 1052: }
 1053: 
 1054: sub createnewhtml {
 1055:   my $filecontents=(<<SIMPLECONTENT);
 1056: <html>
 1057: <head>
 1058: <title>
 1059:                            Title of Document Goes Here
 1060: </title>
 1061: </head>
 1062: <body bgcolor="#FFFFFF">
 1063: 
 1064:                            Body of Document Goes Here
 1065: 
 1066: </body>
 1067: </html>
 1068: SIMPLECONTENT
 1069:   return $filecontents;
 1070: }
 1071: 
 1072: sub createnewsty {
 1073:   my $filecontents=(<<SIMPLECONTENT);
 1074: <definetag name="">
 1075:     <render>
 1076:        <web></web>
 1077:        <tex></tex>
 1078:     </render>
 1079: </definetag>
 1080: SIMPLECONTENT
 1081:   return $filecontents;
 1082: }
 1083: 
 1084: 
 1085: sub inserteditinfo {
 1086:       my ($result,$filecontents,$filetype)=@_;
 1087:       $filecontents = &HTML::Entities::encode($filecontents);
 1088: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1089:       my $xml_help = '';
 1090:       if ($filetype eq 'html') {
 1091: 	  $xml_help=Apache::loncommon::helpLatexCheatsheet();
 1092:       }
 1093:       my $cleanbut = '';
 1094:       if ($filetype eq 'html') {
 1095: 	  $cleanbut='<input type="submit" name="attemptclean" 
 1096:                        value="Save and then attempt to clean HTML" />';
 1097:       }
 1098:       my $titledisplay=&display_title();
 1099:       my $buttons=(<<BUTTONS);
 1100: $cleanbut
 1101: <input type="submit" name="savethisfile" value="Save this" />
 1102: <input type="submit" name="viewmode" value="View" />
 1103: BUTTONS
 1104:       my $editfooter=(<<ENDFOOTER);
 1105: <hr />
 1106: <a name="editsection" />
 1107: <form method="post">
 1108: $xml_help
 1109: <input type="hidden" name="editmode" value="Edit" />
 1110: $buttons<br />
 1111: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
 1112: <br />$buttons
 1113: <br />
 1114: </form>
 1115: $titledisplay
 1116: ENDFOOTER
 1117: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1118:       $result=~s/(\<\/body\>)/$editfooter/is;
 1119:       return $result;
 1120: }
 1121: 
 1122: sub get_target {
 1123:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
 1124:   if ( $ENV{'request.state'} eq 'published') {
 1125:     if ( defined($ENV{'form.grade_target'})
 1126: 	 && ($viewgrades == 'F' )) {
 1127:       return ($ENV{'form.grade_target'});
 1128:     } elsif (defined($ENV{'form.grade_target'})) {
 1129:       if (($ENV{'form.grade_target'} eq 'web') ||
 1130: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
 1131: 	return $ENV{'form.grade_target'}
 1132:       } else {
 1133: 	return 'web';
 1134:       }
 1135:     } else {
 1136:       return 'web';
 1137:     }
 1138:   } elsif ($ENV{'request.state'} eq 'construct') {
 1139:     if ( defined($ENV{'form.grade_target'})) {
 1140:       return ($ENV{'form.grade_target'});
 1141:     } else {
 1142:       return 'web';
 1143:     }
 1144:   } else {
 1145:     return 'web';
 1146:   }
 1147: }
 1148: 
 1149: sub handler {
 1150:     my $request=shift;
 1151:     
 1152:     my $target=&get_target();
 1153:     
 1154:     $Apache::lonxml::debug=$ENV{'user.debug'};
 1155:     
 1156:     if ($ENV{'browser.mathml'}) {
 1157: 	$request->content_type('text/xml');
 1158:     } else {
 1159: 	$request->content_type('text/html');
 1160:     }
 1161:     &Apache::loncommon::no_cache($request);
 1162:     $request->send_http_header;
 1163:     
 1164:     return OK if $request->header_only;
 1165: 
 1166: 
 1167:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1168:     my $filetype;
 1169:     if ($file =~ /\.sty$/) {
 1170: 	$filetype='sty';
 1171:     } else {
 1172: 	$filetype='html';
 1173:     }
 1174: #
 1175: # Edit action? Save file.
 1176: #
 1177:     unless ($ENV{'request.state'} eq 'published') {
 1178: 	if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
 1179: 	    if (&storefile($file,$ENV{'form.filecont'})) {
 1180: 		$request->print("<font COLOR=\"#0000FF\">Updated: ". strftime("%d %b %H:%M:%S",localtime())." </font>");
 1181: 	    } 
 1182: 	}
 1183:     }
 1184:     my %mystyle;
 1185:     my $result = '';
 1186:     my $filecontents=&Apache::lonnet::getfile($file);
 1187:     if ($filecontents eq -1) {
 1188: 	$result=(<<ENDNOTFOUND);
 1189: <html>
 1190: <head>
 1191: <title>File not found</title>
 1192: </head>
 1193: <body bgcolor="#FFFFFF">
 1194: <b>File not found: $file</b>
 1195: </body>
 1196: </html>
 1197: ENDNOTFOUND
 1198:     $filecontents='';
 1199: 	if ($ENV{'request.state'} ne 'published') {
 1200: 	    if ($filetype eq 'sty') {
 1201: 		$filecontents=&createnewsty();
 1202: 	    } else {
 1203: 		$filecontents=&createnewhtml();
 1204: 	    }
 1205: 	    $ENV{'form.editmode'}='Edit'; #force edit mode
 1206: 	}
 1207:     } else {
 1208: 	unless ($ENV{'request.state'} eq 'published') {
 1209: 	    if ($ENV{'form.attemptclean'}) {
 1210: 		$filecontents=&htmlclean($filecontents,1);
 1211: 	    }
 1212: #
 1213: # we are in construction space, see if edit mode forced
 1214:             &Apache::loncommon::get_unprocessed_cgi
 1215:                           ($ENV{'QUERY_STRING'},['editmode']);
 1216: 	}
 1217: 	if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
 1218: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
 1219: 						'',%mystyle);
 1220: 	}
 1221:     }
 1222:     
 1223: #
 1224: # Edit action? Insert editing commands
 1225: #
 1226:     unless ($ENV{'request.state'} eq 'published') {
 1227: 	if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
 1228: 	    my $displayfile=$request->uri;
 1229: 	    $displayfile=~s/^\/[^\/]*//;
 1230: 	    $result='<html><body bgcolor="#FFFFFF"><h3>'.$displayfile.
 1231: 		'</h3></body></html>';
 1232: 	    $result=&inserteditinfo($result,$filecontents,$filetype);
 1233: 	}
 1234:     }
 1235:     if ($filetype eq 'html') { writeallows($request->uri); }
 1236: 	
 1237:     
 1238: 
 1239:     $request->print($result);
 1240:     
 1241:     return OK;
 1242: }
 1243: 
 1244: sub display_title {
 1245:     my $result;
 1246:     if ($ENV{'request.state'} eq 'construct') {
 1247: 	my $title=&Apache::lonnet::gettitle();
 1248: 	if (!defined($title) || $title eq '') {
 1249: 	    $title = $ENV{'request.filename'};
 1250: 	    $title = substr($title, rindex($title, '/') + 1);
 1251: 	}
 1252: 	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
 1253:     }
 1254:     return $result;
 1255: }
 1256: 
 1257: sub debug {
 1258:   if ($Apache::lonxml::debug eq 1) {
 1259:     $|=1;
 1260:     print('<font size="-2"<pre>DEBUG:'.&HTML::Entities::encode($_[0])."</pre></font>\n");
 1261:   }
 1262: }
 1263: 
 1264: sub error {
 1265:   $errorcount++;
 1266:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
 1267:     # If printing in construction space, put the error inside <pre></pre>
 1268:     print "<b>ERROR:</b>".join("\n",@_)."\n";
 1269:   } else {
 1270:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
 1271:     #notify author
 1272:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
 1273:     #notify course
 1274:     if ( $ENV{'request.course.id'} ) {
 1275:       my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
 1276:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
 1277:       foreach (keys %users) {
 1278: 	my ($user,$domain) = split(/:/, $_);
 1279: 	&Apache::lonmsg::user_normal_msg($user,$domain,
 1280:         "Error [$declutter]",join('<br />',@_));
 1281:       }
 1282:     }
 1283: 
 1284:     #FIXME probably shouldn't have me get everything forever.
 1285:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
 1286:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
 1287:   }
 1288: }
 1289: 
 1290: sub warning {
 1291:   $warningcount++;
 1292:   
 1293:   if ($ENV{'form.grade_target'} ne 'tex') {
 1294:       if ($ENV{'request.state'} eq 'construct' || $Apache::lonxml::debug) {
 1295:         print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
 1296:       }
 1297:   }
 1298: }
 1299: 
 1300: sub get_param {
 1301:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1302:     if ( ! $context ) { $context = -1; }
 1303:     my $args ='';
 1304:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1305:     if ( ! $args ) { return undef; }
 1306:     if ( $case_insensitive ) {
 1307: 	if ($args =~ s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei) {
 1308: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1309:                                      $safeeval); #'
 1310: 	} else {
 1311: 	    return undef;
 1312: 	}
 1313:     } else {
 1314: 	if ( $args =~ /my \$\Q$param\E=\"/ ) {
 1315: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1316:                                      $safeeval); #'
 1317: 	} else {
 1318: 	    return undef;
 1319: 	}
 1320:     }
 1321: }
 1322: 
 1323: sub get_param_var {
 1324:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1325:   if ( ! $context ) { $context = -1; }
 1326:   my $args ='';
 1327:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1328:   &Apache::lonxml::debug("Args are $args param is $param");
 1329:   if ($case_insensitive) {
 1330:       if (! ($args=~s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei)) {
 1331: 	  return undef;
 1332:       }
 1333:   } elsif ( $args !~ /my \$\Q$param\E=\"/ ) { return undef; }
 1334:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1335:   &Apache::lonxml::debug("first run is $value");
 1336:   if ($value =~ /^[\$\@\%]\w+$/) {
 1337:       &Apache::lonxml::debug("doing second");
 1338:       my @result=&Apache::run::run("return $value",$safeeval,1);
 1339:       if (!defined($result[0])) {
 1340: 	  return $value
 1341:       } else {
 1342: 	  if (wantarray) { return @result; } else { return $result[0]; }
 1343:       }
 1344:   } else {
 1345:     return $value;
 1346:   }
 1347: }
 1348: 
 1349: sub register_insert {
 1350:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1351:   my $i;
 1352:   my $tagnum=0;
 1353:   my @order;
 1354:   for ($i=0;$i < $#data; $i++) {
 1355:     my $line = $data[$i];
 1356:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1357:     if ( $line =~ /TABLE/ ) { last; }
 1358:     my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
 1359:     if ($tag) {
 1360:       $insertlist{"$tagnum.tag"} = $tag;
 1361:       $insertlist{"$tagnum.description"} = $descrip;
 1362:       $insertlist{"$tagnum.color"} = $color;
 1363:       $insertlist{"$tagnum.function"} = $function;
 1364:       if (!defined($show)) { $show='yes'; }
 1365:       $insertlist{"$tagnum.show"}= $show;
 1366:       $insertlist{"$tagnum.helpfile"} = $helpfile;
 1367:       $insertlist{"$tagnum.helpdesc"} = $helpdesc;
 1368:       $insertlist{"$tag.num"}=$tagnum;
 1369:       $tagnum++;
 1370:     }
 1371:   }
 1372:   $i++; #skipping TABLE line
 1373:   $tagnum = 0;
 1374:   for (;$i < $#data;$i++) {
 1375:     my $line = $data[$i];
 1376:     my ($mnemonic,@which) = split(/ +/,$line);
 1377:     my $tag = $insertlist{"$tagnum.tag"};
 1378:     for (my $j=0;$j <=$#which;$j++) {
 1379:       if ( $which[$j] eq 'Y' ) {
 1380: 	if ($insertlist{"$j.show"} ne 'no') {
 1381: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1382: 	}
 1383:       }
 1384:     }
 1385:     $tagnum++;
 1386:   }
 1387: }
 1388: 
 1389: sub description {
 1390:   my ($token)=@_;
 1391:   my $tagnum;
 1392:   my $tag=$token->[1];
 1393:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1394:     my $testtag=$namespace.'::'.$tag;
 1395:     $tagnum=$insertlist{"$testtag.num"};
 1396:     if (defined($tagnum)) { last; }
 1397:   }
 1398:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1399:   return $insertlist{$tagnum.'.description'};
 1400: }
 1401: 
 1402: # Returns a list containing the help file, and the description
 1403: sub helpinfo {
 1404:   my ($token)=@_;
 1405:   my $tagnum;
 1406:   my $tag=$token->[1];
 1407:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1408:     my $testtag=$namespace.'::'.$tag;
 1409:     $tagnum=$insertlist{"$testtag.num"};
 1410:     if (defined($tagnum)) { last; }
 1411:   }
 1412:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1413:   return ($insertlist{$tagnum.'.helpfile'}, $insertlist{$tagnum.'.helpdesc'});
 1414: }
 1415: 
 1416: # ----------------------------------------------------------------- whichuser
 1417: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1418: # calls to lonnet functions for this setup.
 1419: # - looks for form.grade_ parameters
 1420: sub whichuser {
 1421:   my ($passedsymb)=@_;
 1422:   my ($symb,$courseid,$domain,$name,$publicuser);
 1423:   if (defined($ENV{'form.grade_symb'})) {
 1424:     my $tmp_courseid=$ENV{'form.grade_courseid'};
 1425:     my $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid);
 1426:     if ($allowed) {
 1427:       $symb=$ENV{'form.grade_symb'};
 1428:       $courseid=$ENV{'form.grade_courseid'};
 1429:       $domain=$ENV{'form.grade_domain'};
 1430:       $name=$ENV{'form.grade_username'};
 1431:     }
 1432:   } else {
 1433:       if (!$passedsymb) {
 1434:           $symb=&Apache::lonnet::symbread();
 1435:       } else {
 1436:           $symb=$passedsymb;
 1437:       }
 1438:       $courseid=$ENV{'request.course.id'};
 1439:       $domain=$ENV{'user.domain'};
 1440:       $name=$ENV{'user.name'};
 1441:       if ($name eq 'public' && $domain eq 'public') {
 1442: 	  if (!defined($ENV{'form.username'})) {
 1443: 	      $ENV{'form.username'}.=time.rand(10000000);
 1444: 	  }
 1445: 	  $name.=$ENV{'form.username'};
 1446:       }
 1447:   }
 1448:   return ($symb,$courseid,$domain,$name,$publicuser);
 1449: }
 1450: 
 1451: 1;
 1452: __END__
 1453: 
 1454: 

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