File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.288: download - view: text, annotated - select for diffs
Mon Oct 27 19:00:11 2003 UTC (20 years, 7 months ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
Bug 2323 (problem numbering when printing exam with answers) is fixed for resources from sequence (not for selected students yet). I want to know the Guy's opinion.

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

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