File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.278: download - view: text, annotated - select for diffs
Mon Sep 15 19:56:44 2003 UTC (20 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Getting status info into list_discussion.

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

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