File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.142: download - view: text, annotated - select for diffs
Fri Dec 21 22:44:06 2001 UTC (22 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
 - map -> foreach conversion
-  removed some debuggin messages

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.142 2001/12/21 22:44:06 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: # last modified 06/26/00 by Alexander Sakharuk
   40: # 11/6 Gerd Kortemeyer
   41: # 6/1/1 Gerd Kortemeyer
   42: # 2/21,3/13 Guy
   43: # 3/29,5/4 Gerd Kortemeyer
   44: # 5/10 Scott Harrison
   45: # 5/26 Gerd Kortemeyer
   46: # 5/27 H. K. Ng
   47: # 6/2,6/3,6/8,6/9 Gerd Kortemeyer
   48: # 6/12,6/13 H. K. Ng
   49: # 6/16 Gerd Kortemeyer
   50: # 7/27 H. K. Ng
   51: # 8/7,8/9,8/10,8/11,8/15,8/16,8/17,8/18,8/20,8/23,8/24 Gerd Kortemeyer
   52: # Guy Albertelli
   53: # 9/26 Gerd Kortemeyer
   54: 
   55: 
   56: package Apache::lonxml; 
   57: use vars 
   58: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace);
   59: use strict;
   60: use HTML::TokeParser;
   61: use HTML::TreeBuilder;
   62: use Safe;
   63: use Safe::Hole;
   64: use Math::Cephes qw(:trigs :hypers :bessels erf erfc);
   65: use Math::Random qw(:all);
   66: use Opcode;
   67: 
   68: sub register {
   69:   my ($space,@taglist) = @_;
   70:   foreach my $temptag (@taglist) {
   71:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   72:   }
   73: }
   74: 
   75: sub deregister {
   76:   my ($space,@taglist) = @_;
   77:   foreach my $temptag (@taglist) {
   78:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   79:     if ($tempspace eq $space) {
   80:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   81:     }
   82:   }
   83:   #&printalltags();
   84: }
   85: 
   86: use Apache::Constants qw(:common);
   87: use Apache::lontexconvert;
   88: use Apache::style;
   89: use Apache::run;
   90: use Apache::londefdef;
   91: use Apache::scripttag;
   92: use Apache::edit;
   93: use Apache::lonnet;
   94: use Apache::File;
   95: use Apache::loncommon;
   96: 
   97: #==================================================   Main subroutine: xmlparse  
   98: #debugging control, to turn on debugging modify the correct handler
   99: $Apache::lonxml::debug=0;
  100: 
  101: #path to the directory containing the file currently being processed
  102: @pwd=();
  103: 
  104: #these two are used for capturing a subset of the output for later processing,
  105: #don't touch them directly use &startredirection and &endredirection
  106: @outputstack = ();
  107: $redirection = 0;
  108: 
  109: #controls wheter the <import> tag actually does
  110: $import = 1;
  111: @extlinks=();
  112: 
  113: # meta mode is a bit weird only some output is to be turned off
  114: #<output> tag turns metamode off (defined in londefdef.pm)
  115: $metamode = 0;
  116: 
  117: # turns on and of run::evaluate actually derefencing var refs
  118: $evaluate = 1;
  119: 
  120: # data structure for eidt mode, determines what tags can go into what other tags
  121: %insertlist=();
  122: 
  123: # stores the list of active tag namespaces
  124: @namespace=();
  125: 
  126: # has the dynamic menu been updated to know about this resource
  127: $Apache::lonxml::registered=0;
  128: 
  129: sub xmlbegin {
  130:   my $output='';
  131:   if ($ENV{'browser.mathml'}) {
  132:       $output='<?xml version="1.0"?>'
  133:             .'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'
  134:             .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
  135:             .'[<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">]>'
  136:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
  137: 		.'xmlns="http://www.w3.org/TR/REC-html40">';
  138:   } else {
  139:       $output='<html>';
  140:   }
  141:   return $output;
  142: }
  143: 
  144: sub xmlend {
  145:     my $discussion='';
  146:     if ($ENV{'request.course.id'}) {
  147:        my $crs='/'.$ENV{'request.course.id'};
  148:        if ($ENV{'request.course.sec'}) {
  149:           $crs.='_'.$ENV{'request.course.sec'};
  150:        }                 
  151:        $crs=~s/\_/\//g;
  152:        my $seeid=&Apache::lonnet::allowed('rin',$crs);
  153:        my $symb=&Apache::lonnet::symbread();
  154:        if ($symb) {
  155:           my %contrib=&Apache::lonnet::restore($symb,$ENV{'request.course.id'},
  156:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  157: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  158:           if ($contrib{'version'}) {
  159:               $discussion.=
  160:                   '<address><hr /><h2>Course Discussion of Resource</h2>';
  161:               my $idx;
  162:               for ($idx=1;$idx<=$contrib{'version'};$idx++) {
  163: 		my $hidden=($contrib{'hidden'}=~/\.$idx\./);
  164: 		unless (($hidden) && (!$seeid)) {
  165:                  my $message=$contrib{$idx.':message'};
  166:                  $message=~s/\n/\<br \/\>/g;
  167:                  if ($message) {
  168:                   if ($hidden) {
  169: 		      $message='<font color="#888888">'.$message.'</font>';
  170:                   }
  171:                   my $sender='Anonymous';
  172:                   if ((!$contrib{$idx.':anonymous'}) || ($seeid)) {
  173:                       $sender=$contrib{$idx.':sendername'}.' at '.
  174: 		      $contrib{$idx.':senderdomain'};
  175:                       if ($contrib{$idx.':anonymous'}) {
  176: 			  $sender.=' (anonymous)';
  177:                       }
  178:                       if ($seeid) {
  179: 			  if ($hidden) {
  180:                              $sender.=' <a href="/adm/feedback?unhide='.
  181: 				 $symb.':::'.$idx.'">Make Visible</a>';
  182:                           } else {
  183:                              $sender.=' <a href="/adm/feedback?hide='.
  184: 				 $symb.':::'.$idx.'">Hide</a>';
  185: 			  }
  186:                       }                   
  187:                   }
  188: 		  $discussion.='<p><b>'.$sender.'</b> ('.
  189:                       localtime($contrib{$idx.':timestamp'}).
  190:                       '):<blockquote>'.$message.
  191:                       '</blockquote></p>';
  192: 	        }
  193:                } 
  194:               }
  195:               $discussion.='</address>';
  196:           }
  197:        }
  198:     }
  199:     return $discussion.'</html>';
  200: }
  201: 
  202: sub tokeninputfield {
  203:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  204:     $defhost=~tr/a-z/A-Z/;
  205:     return (<<ENDINPUTFIELD)
  206: <script>
  207:     function updatetoken() {
  208: 	var comp=new Array;
  209:         var barcode=unescape(document.tokeninput.barcode.value);
  210:         comp=barcode.split('*');
  211:         if (typeof(comp[0])!="undefined") {
  212: 	    document.tokeninput.codeone.value=comp[0];
  213: 	}
  214:         if (typeof(comp[1])!="undefined") {
  215: 	    document.tokeninput.codetwo.value=comp[1];
  216: 	}
  217:         if (typeof(comp[2])!="undefined") {
  218:             comp[2]=comp[2].toUpperCase();
  219: 	    document.tokeninput.codethree.value=comp[2];
  220: 	}
  221:         document.tokeninput.barcode.value='';
  222:     }  
  223: </script>
  224: <form method="post" name="tokeninput">
  225: <table border="2" bgcolor="#FFFFBB">
  226: <tr><th>DocID Checkin</th></tr>
  227: <tr><td>
  228: <table>
  229: <tr>
  230: <td>Scan in Barcode</td>
  231: <td><input type="text" size="22" name="barcode" 
  232: onChange="updatetoken()"/></td>
  233: </tr>
  234: <tr><td><i>or</i> Type in DocID</td>
  235: <td>
  236: <input type="text" size="5" name="codeone" />
  237: <b><font size="+2">*</font></b>
  238: <input type="text" size="5" name="codetwo" />
  239: <b><font size="+2">*</font></b>
  240: <input type="text" size="10" name="codethree" value="$defhost" 
  241: onChange="this.value=this.value.toUpperCase()" />
  242: </td></tr>
  243: </table>
  244: </td></tr>
  245: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  246: </table>
  247: </form>
  248: ENDINPUTFIELD
  249: }
  250: 
  251: sub maketoken {
  252:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  253:     unless ($symb) {
  254: 	$symb=&Apache::lonnet::symbread();
  255:     }
  256:     unless ($tuname) {
  257: 	$tuname=$ENV{'user.name'};
  258:         $tudom=$ENV{'user.domain'};
  259:         $tcrsid=$ENV{'request.course.id'};
  260:     }
  261: 
  262:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  263: }
  264: 
  265: sub printtokenheader {
  266:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  267:     unless ($token) { return ''; }
  268: 
  269:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  270:     unless ($tsymb) {
  271: 	$tsymb=$symb;
  272:     }
  273:     unless ($tuname) {
  274: 	$tuname=$name;
  275:         $tudom=$domain;
  276:         $tcrsid=$courseid;
  277:     }
  278: 
  279:     my %reply=&Apache::lonnet::get('environment',
  280:               ['firstname','middlename','lastname','generation'],
  281:               $tudom,$tuname);
  282:     my $plainname=$reply{'firstname'}.' '. 
  283:                   $reply{'middlename'}.' '.
  284:                   $reply{'lastname'}.' '.
  285: 		  $reply{'generation'};
  286: 
  287:     if ($target eq 'web') {
  288: 	return 
  289:  '<img align="right" src="/cgi-bin/barcode.gif?encode='.$token.'" />'.
  290:                'Checked out for '.$plainname.
  291:                '<br />User: '.$tuname.' at '.$tudom.
  292: 	       '<br />CourseID: '.$tcrsid.
  293:                '<br />DocID: '.$token.
  294:                '<br />Time: '.localtime().'<hr />';
  295:     } else {
  296:         return $token;
  297:     }
  298: }
  299: 
  300: sub fontsettings() {
  301:     my $headerstring='';
  302:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
  303:          $headerstring.=
  304:              '<meta Content-Type="text/html; charset=x-mac-roman">';
  305:     }
  306:     return $headerstring;
  307: }
  308: 
  309: sub registerurl {
  310:     my $forcereg=shift;
  311:     if ($ENV{'request.publicaccess'}) {
  312: 	return 
  313:          '<script>function LONCAPAreg(){} function LONCAPAstale(){}</script>';
  314:     }
  315:     if ($Apache::lonxml::registered && !$forcereg) { return ''; }
  316:     $Apache::lonxml::registered=1;
  317:     if (($ENV{'REQUEST_URI'}!~/^\/(res\/)*adm\//) || ($forcereg)) {
  318:         my $hwkadd='';
  319:         if ($ENV{'REQUEST_URI'}=~/\.(problem|exam|quiz|assess|survey|form)$/) {
  320: 	    if (&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) {
  321: 		$hwkadd.=(<<ENDSUBM);
  322:                      menu.switchbutton
  323:            (7,1,'subm.gif','view sub','missions',
  324:                 'gocmd("/adm/grades","submission")');
  325: ENDSUBM
  326:             }
  327: 	    if (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) {
  328: 		$hwkadd.=(<<ENDGRDS);
  329:                      menu.switchbutton
  330:            (7,2,'pgrd.gif','problem','grades',
  331:                 'gocmd("/adm/grades","viewgrades")');
  332: ENDGRDS
  333:             }
  334: 	    if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  335: 		$hwkadd.=(<<ENDPARM);
  336:                      menu.switchbutton
  337:            (7,3,'pparm.gif','problem','parms',
  338:                 'gocmd("/adm/parmset","set")');
  339: ENDPARM
  340:             }
  341: 	}
  342: 	return (<<ENDREGTHIS);
  343:      
  344: <script language="JavaScript">
  345: // BEGIN LON-CAPA Internal
  346: 
  347:     function LONCAPAreg() {
  348: 	  menu=window.open("","LONCAPAmenu");
  349:           menu.clearTimeout(menu.menucltim);
  350: 	  menu.currentURL=window.location.pathname;
  351:           menu.currentStale=0;
  352:           menu.clearbut(3,1);
  353:           menu.switchbutton
  354:        (6,3,'catalog.gif','catalog','info','catalog_info()');
  355:           menu.switchbutton
  356:        (8,1,'eval.gif','evaluate','this','gopost("/adm/evaluate",currentURL)');
  357:           menu.switchbutton
  358:     (8,2,'fdbk.gif','feedback','on this','gopost("/adm/feedback",currentURL)');
  359:           menu.switchbutton
  360:      (8,3,'prt.gif','prepare','printout','gopost("/adm/printout",currentURL)');
  361:           menu.switchbutton
  362:        (2,1,'back.gif','backward','','gopost("/adm/flip","back:"+currentURL)');
  363:           menu.switchbutton
  364:      (2,3,'forw.gif','forward','','gopost("/adm/flip","forward:"+currentURL)');
  365:           menu.switchbutton
  366:                             (9,1,'sbkm.gif','set','bookmark','set_bookmark()');
  367:           menu.switchbutton
  368:                          (9,2,'vbkm.gif','view','bookmark','edit_bookmarks()');
  369:           menu.switchbutton
  370:                                (9,3,'anot.gif','anno-','tations','annotate()');
  371:           $hwkadd
  372:     }
  373: 
  374:     function LONCAPAstale() {
  375: 	  menu=window.open("","LONCAPAmenu");
  376:           menu.currentStale=1;
  377:           menu.switchbutton
  378:              (3,1,'reload.gif','return','location','go(currentURL)');
  379:           menu.clearbut(7,1);
  380:           menu.clearbut(7,2);
  381:           menu.clearbut(7,3);
  382:           menu.menucltim=menu.setTimeout(
  383:  'clearbut(2,1);clearbut(2,3);clearbut(8,1);clearbut(8,2);clearbut(8,3);'+
  384:  'clearbut(9,1);clearbut(9,2);clearbut(9,3);clearbut(6,3)',
  385: 			  2000);
  386: 
  387:       }
  388: 
  389: // END LON-CAPA Internal
  390: </script>
  391: ENDREGTHIS
  392: 
  393:     } else {
  394:         return (<<ENDDONOTREGTHIS);
  395: 
  396: <script language="JavaScript">
  397: // BEGIN LON-CAPA Internal
  398: 
  399:     function LONCAPAreg() {
  400: 	  menu=window.open("","LONCAPAmenu");
  401:           menu.currentStale=1;
  402:           menu.clearbut(2,1);
  403:           menu.clearbut(2,3);
  404:           menu.clearbut(8,1);
  405:           menu.clearbut(8,2);
  406:           menu.clearbut(8,3);
  407:           if (menu.currentURL) {
  408:              menu.switchbutton
  409:               (3,1,'reload.gif','return','location','go(currentURL)');
  410:  	  } else {
  411: 	      menu.clearbut(3,1);
  412:           }
  413:     }
  414: 
  415:     function LONCAPAstale() {
  416:     }
  417: 
  418: // END LON-CAPA Internal
  419: </script>
  420: ENDDONOTREGTHIS
  421: 
  422:     }
  423: }
  424: 
  425: sub loadevents() {
  426:     return 'LONCAPAreg();';
  427: }
  428: 
  429: sub unloadevents() {
  430:     return 'LONCAPAstale();';
  431: }
  432: 
  433: sub printalltags {
  434:   my $temp;
  435:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  436:     &Apache::lonxml::debug("$temp -- ".
  437: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  438:   }
  439: }
  440: 
  441: sub xmlparse {
  442:  my ($target,$content_file_string,$safeinit,%style_for_target) = @_;
  443: 
  444:  &setup_globals($target);
  445:  #&printalltags();
  446:  my @pars = ();
  447:  my $pwd=$ENV{'request.filename'};
  448:  $pwd =~ s:/[^/]*$::;
  449:  &newparser(\@pars,\$content_file_string,$pwd);
  450: 
  451:  my $safeeval = new Safe;
  452:  my $safehole = new Safe::Hole;
  453:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  454: #-------------------- Redefinition of the target in the case of compound target
  455: 
  456:  ($target, my @tenta) = split('&&',$target);
  457: 
  458:  my @stack = (); 
  459:  my @parstack = ();
  460:  &initdepth;
  461: 
  462:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  463: 				   $safeeval,\%style_for_target);
  464:  if ($ENV{'request.uri'}) {
  465:     &writeallows($ENV{'request.uri'});
  466:  }
  467:  return $finaloutput;
  468: }
  469: 
  470: sub htmlclean {
  471:     my ($raw,$full)=@_;
  472: 
  473:     my $tree = HTML::TreeBuilder->new;
  474:     $tree->ignore_unknown(0);
  475: 
  476:     $tree->parse($raw);
  477: 
  478:     my $output= $tree->as_HTML(undef,' ');
  479: 
  480:     $output=~s/\<(br|hr|img|meta|allow)([^\>\/]*)\>/\<$1$2 \/\>/gis;
  481:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
  482:     unless ($full) {
  483:        $output=~s/\<[\/]*(body|head|html)\>//gis;
  484:     }
  485: 
  486:     $tree = $tree->delete;
  487: 
  488:     return $output;
  489: }
  490: 
  491: sub inner_xmlparse {
  492:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  493:   my $finaloutput = '';
  494:   my $result;
  495:   my $token;
  496:   while ( $#$pars > -1 ) {
  497:     while ($token = $$pars['-1']->get_token) {
  498:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  499: 	if ($metamode<1) {
  500: 	  $result=$token->[1];
  501: 	}
  502:       } elsif ($token->[0] eq 'PI') {
  503: 	if ($metamode<1) {
  504: 	  $result=$token->[2];
  505: 	}
  506:       } elsif ($token->[0] eq 'S') {
  507: 	# add tag to stack
  508: 	push (@$stack,$token->[1]);
  509: 	# add parameters list to another stack
  510: 	push (@$parstack,&parstring($token));
  511: 	&increasedepth($token);
  512: 	if (exists $$style_for_target{$token->[1]}) {
  513: 	  if ($Apache::lonxml::redirection) {
  514: 	    $Apache::lonxml::outputstack['-1'] .=
  515: 	      &recurse($$style_for_target{$token->[1]},$target,$safeeval,
  516: 		       $style_for_target,@$parstack);
  517: 	  } else {
  518: 	    $finaloutput .= &recurse($$style_for_target{$token->[1]},$target,
  519: 				     $safeeval,$style_for_target,@$parstack);
  520: 	  }
  521: 	} else {
  522: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  523: 			     $parstack, $pars, $safeeval, $style_for_target);
  524: 	}
  525:       } elsif ($token->[0] eq 'E') {
  526: 	#clear out any tags that didn't end
  527: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  528: 	  &Apache::lonxml::warning('Missing tag &lt;/'.$$stack['-1'].'&gt; in file');
  529: 	  &end_tag($stack,$parstack,$token);
  530: 	}
  531: 
  532: 	if (exists($$style_for_target{'/'."$token->[1]"})) {
  533: 	  if ($Apache::lonxml::redirection) {
  534: 	    $Apache::lonxml::outputstack['-1'] .=  
  535: 	      &recurse($$style_for_target{'/'."$token->[1]"},
  536: 		       $target,$safeeval,$style_for_target,@$parstack);
  537: 	  } else {
  538: 	    $finaloutput .= &recurse($$style_for_target{'/'."$token->[1]"},
  539: 				     $target,$safeeval,$style_for_target,
  540: 				     @$parstack);
  541: 	  }
  542: 	} else {
  543: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
  544: 			     $parstack, $pars,$safeeval, $style_for_target);
  545: 	}
  546:       } else {
  547: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  548:       }
  549:       #evaluate variable refs in result
  550:       if ($result ne "") {
  551: 	if ( $#$parstack > -1 ) {
  552: 	  if ($Apache::lonxml::redirection) {
  553: 	    $Apache::lonxml::outputstack['-1'] .= 
  554: 	      &Apache::run::evaluate($result,$safeeval,$$parstack['-1']);
  555: 	  } else {
  556: 	    $finaloutput .= &Apache::run::evaluate($result,$safeeval,
  557: 						   $$parstack['-1']);
  558: 	  }
  559: 	} else {
  560: 	  $finaloutput .= &Apache::run::evaluate($result,$safeeval,'');
  561: 	}
  562: 	$result = '';
  563:       } 
  564:       if ($token->[0] eq 'E') { 
  565: 	&end_tag($stack,$parstack,$token);
  566:       }
  567:     }
  568:     pop @$pars;
  569:     pop @Apache::lonxml::pwd;
  570:   }
  571: 
  572:   # if ($target eq 'meta') {
  573:   #   $finaloutput.=&endredirection;
  574:   # }
  575: 
  576:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  577:     $finaloutput=&afterburn($finaloutput);
  578:   }
  579:   return $finaloutput;
  580: }
  581: 
  582: sub recurse {
  583:   my @innerstack = (); 
  584:   my @innerparstack = ();
  585:   my ($newarg,$target,$safeeval,$style_for_target,@parstack) = @_;
  586:   my @pat = ();
  587:   &newparser(\@pat,\$newarg);
  588:   my $tokenpat;
  589:   my $partstring = '';
  590:   my $output='';
  591:   my $decls='';
  592:   &Apache::lonxml::debug("Recursing");
  593:   while ( $#pat > -1 ) {
  594:     while  ($tokenpat = $pat[$#pat]->get_token) {
  595:       if (($tokenpat->[0] eq 'T') || ($tokenpat->[0] eq 'C') || ($tokenpat->[0] eq 'D') ) {
  596: 	if ($metamode<1) { $partstring=$tokenpat->[1]; }
  597:       } elsif ($tokenpat->[0] eq 'PI') {
  598: 	if ($metamode<1) { $partstring=$tokenpat->[2]; }
  599:       } elsif ($tokenpat->[0] eq 'S') {
  600: 	push (@innerstack,$tokenpat->[1]);
  601: 	push (@innerparstack,&parstring($tokenpat));
  602: 	&increasedepth($tokenpat);
  603: 	$partstring = &callsub("start_$tokenpat->[1]", $target, $tokenpat,
  604: 			       \@innerstack, \@innerparstack, \@pat,
  605: 			       $safeeval, $style_for_target);
  606:       } elsif ($tokenpat->[0] eq 'E') {
  607: 	#clear out any tags that didn't end
  608: 	while ($tokenpat->[1] ne $innerstack[$#innerstack] 
  609: 	       && ($#innerstack > -1)) {
  610: 	  &Apache::lonxml::warning('Missing tag &lt;/'.$innerstack['-1'].'&gt; in style');
  611: 	  &end_tag(\@innerstack,\@innerparstack,$tokenpat);
  612: 	}
  613: 	$partstring = &callsub("end_$tokenpat->[1]", $target, $tokenpat,
  614: 			       \@innerstack, \@innerparstack, \@pat,
  615: 			       $safeeval, $style_for_target);
  616:       } else {
  617: 	&Apache::lonxml::error("Unknown token event :$tokenpat->[0]:$tokenpat->[1]:");
  618:       }
  619:       #pass both the variable to the style tag, and the tag we 
  620:       #are processing inside the <definedtag>
  621:       if ( $partstring ne "" ) {
  622: 	if ( $#parstack > -1 ) { 
  623: 	  if ( $#innerparstack > -1 ) { 
  624: 	    $decls= $parstack[$#parstack].$innerparstack[$#innerparstack];
  625: 	  } else {
  626: 	    $decls= $parstack[$#parstack];
  627: 	  }
  628: 	} else {
  629: 	  if ( $#innerparstack > -1 ) { 
  630: 	    $decls=$innerparstack[$#innerparstack];
  631: 	  } else {
  632: 	    $decls='';
  633: 	  }
  634: 	}
  635: 	$output .= &Apache::run::evaluate($partstring,$safeeval,$decls);
  636: 	$partstring = '';
  637:       }
  638:       if ($tokenpat->[0] eq 'E') { pop @innerstack;pop @innerparstack;
  639: 				 &decreasedepth($tokenpat);}
  640:     }
  641:     pop @pat;
  642:     pop @Apache::lonxml::pwd;
  643:   }
  644:   &Apache::lonxml::debug("Exiting Recursing");
  645:   return $output;
  646: }
  647: 
  648: sub callsub {
  649:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  650:   my $currentstring='';
  651:   my $nodefault;
  652:   {
  653:     my $sub1;
  654:     no strict 'refs';
  655:     my $tag=$token->[1];
  656:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  657:     if (!$space) {
  658:      	$tag=~tr/A-Z/a-z/;
  659: 	$sub=~tr/A-Z/a-z/;
  660: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  661:     }
  662: 
  663:     my $deleted=0;
  664:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  665:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  666:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  667: 					     $parstack,$parser,$safeeval,
  668: 					     $style);
  669:     }
  670:     if (!$deleted) {
  671:       if ($space) {
  672: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode<br />\n");
  673: 	$sub1="$space\:\:$sub";
  674: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  675: 					     $parstack,$parser,$safeeval,
  676: 					     $style);
  677:       } else {
  678: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode<br />\n");
  679: 	if ($metamode <1) {
  680: 	  if (defined($token->[4]) && ($metamode < 1)) {
  681: 	    $currentstring = $token->[4];
  682: 	  } else {
  683: 	    $currentstring = $token->[2];
  684: 	  }
  685: 	}
  686:       }
  687:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  688:       if ($currentstring eq '' && $nodefault eq '') {
  689: 	if ($target eq 'edit') {
  690: 	  &Apache::lonxml::debug("doing default edit for $token->[1]");
  691: 	  if ($token->[0] eq 'S') {
  692: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  693: 	  } elsif ($token->[0] eq 'E') {
  694: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  695: 	  }
  696: 	} elsif ($target eq 'modified') {
  697: 	  if ($token->[0] eq 'S') {
  698: 	    $currentstring = $token->[4];
  699: 	    $currentstring.=&Apache::edit::handle_insert();
  700: 	  } else {
  701: 	    $currentstring = $token->[2];
  702: 	  }
  703: 	}
  704:       }
  705:     }
  706:     use strict 'refs';
  707:   }
  708:   return $currentstring;
  709: }
  710: 
  711: sub setup_globals {
  712:   my ($target)=@_;
  713:   $Apache::lonxml::registered = 0;
  714:   @Apache::lonxml::pwd=();
  715:   @Apache::lonxml::extlinks=();
  716:   if ($target eq 'meta') {
  717:     $Apache::lonxml::redirection = 0;
  718:     $Apache::lonxml::metamode = 1;
  719:     $Apache::lonxml::evaluate = 1;
  720:     $Apache::lonxml::import = 0;
  721:   } elsif ($target eq 'answer') {
  722:     $Apache::lonxml::redirection = 0;
  723:     $Apache::lonxml::metamode = 1;
  724:     $Apache::lonxml::evaluate = 1;
  725:     $Apache::lonxml::import = 1;
  726:   } elsif ($target eq 'grade') {
  727:     &startredirection;
  728:     $Apache::lonxml::metamode = 0;
  729:     $Apache::lonxml::evaluate = 1;
  730:     $Apache::lonxml::import = 1;
  731:   } elsif ($target eq 'modified') {
  732:     $Apache::lonxml::redirection = 0;
  733:     $Apache::lonxml::metamode = 0;
  734:     $Apache::lonxml::evaluate = 0;
  735:     $Apache::lonxml::import = 0;
  736:   } elsif ($target eq 'edit') {
  737:     $Apache::lonxml::redirection = 0;
  738:     $Apache::lonxml::metamode = 0;
  739:     $Apache::lonxml::evaluate = 0;
  740:     $Apache::lonxml::import = 0;
  741:   } else {
  742:     $Apache::lonxml::redirection = 0;
  743:     $Apache::lonxml::metamode = 0;
  744:     $Apache::lonxml::evaluate = 1;
  745:     $Apache::lonxml::import = 1;
  746:   }
  747: }
  748: 
  749: sub init_safespace {
  750:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  751:   $safeeval->permit("entereval");
  752:   $safeeval->permit(":base_math");
  753:   $safeeval->permit("sort");
  754:   $safeeval->deny(":base_io");
  755:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  756:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  757:   
  758:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  759:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  760:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  761:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  762:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  763:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  764:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  765:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  766:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  767:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  768:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  769:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  770:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  771:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  772:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  773:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  774:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  775:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  776:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  777:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  778:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  779:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  780:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  781:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  782:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  783:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  784:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  785:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  786:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  787:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  788:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  789:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  790:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  791:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  792:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  793:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  794:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  795:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  796:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  797:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  798: 
  799: #need to inspect this class of ops
  800: # $safeeval->deny(":base_orig");
  801:   $safeinit .= ';$external::target="'.$target.'";';
  802:   my $rndseed;
  803:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  804:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  805:   $safeinit .= ';$external::randomseed='.$rndseed.';';
  806:   &Apache::run::run($safeinit,$safeeval);
  807: }
  808: 
  809: sub startredirection {
  810:   $Apache::lonxml::redirection++;
  811:   push (@Apache::lonxml::outputstack, '');
  812: }
  813: 
  814: sub endredirection {
  815:   if (!$Apache::lonxml::redirection) {
  816:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  817:     return '';
  818:   }
  819:   $Apache::lonxml::redirection--;
  820:   pop @Apache::lonxml::outputstack;
  821: }
  822: 
  823: sub end_tag {
  824:   my ($tagstack,$parstack,$token)=@_;
  825:   pop(@$tagstack);
  826:   pop(@$parstack);
  827:   &decreasedepth($token);
  828: }
  829: 
  830: sub initdepth {
  831:   @Apache::lonxml::depthcounter=();
  832:   $Apache::lonxml::depth=-1;
  833:   $Apache::lonxml::olddepth=-1;
  834: }
  835: 
  836: sub increasedepth {
  837:   my ($token) = @_;
  838:   $Apache::lonxml::depth++;
  839:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  840:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  841:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  842:   }
  843:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  844:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  845: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  846: }
  847: 
  848: sub decreasedepth {
  849:   my ($token) = @_;
  850:   $Apache::lonxml::depth--;
  851:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  852:     $#Apache::lonxml::depthcounter--;
  853:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  854:   }
  855:   if (  $Apache::lonxml::depth < -1) {
  856:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
  857:     $Apache::lonxml::depth='-1';
  858:   }
  859:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  860:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  861: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  862: }
  863: 
  864: sub get_all_text {
  865: 
  866:  my($tag,$pars)= @_;
  867:  my $depth=0;
  868:  my $token;
  869:  my $result='';
  870:  if ( $tag =~ m:^/: ) { 
  871:    my $tag=substr($tag,1); 
  872: #   &Apache::lonxml::debug("have:$tag:");
  873:    while (($depth >=0) && ($token = $pars->get_token)) {
  874: #     &Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]");
  875:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  876:        $result.=$token->[1];
  877:      } elsif ($token->[0] eq 'PI') {
  878:        $result.=$token->[2];
  879:      } elsif ($token->[0] eq 'S') {
  880:        if ($token->[1] eq $tag) { $depth++; }
  881:        $result.=$token->[4];
  882:      } elsif ($token->[0] eq 'E')  {
  883:        if ( $token->[1] eq $tag) { $depth--; }
  884:        #skip sending back the last end tag
  885:        if ($depth > -1) { $result.=$token->[2]; } else {
  886: 	 $pars->unget_token($token);
  887:        }
  888:      }
  889:    }
  890:  } else {
  891:    while ($token = $pars->get_token) {
  892: #     &Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
  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] eq $tag) { 
  899: 	 $pars->unget_token($token); last;
  900:        } else {
  901: 	 $result.=$token->[4];
  902:        }
  903:      } elsif ($token->[0] eq 'E')  {
  904:        $result.=$token->[2];
  905:      }
  906:    }
  907:  }
  908: # &Apache::lonxml::debug("Exit:$result:");
  909:  return $result
  910: }
  911: 
  912: sub newparser {
  913:   my ($parser,$contentref,$dir) = @_;
  914:   push (@$parser,HTML::TokeParser->new($contentref));
  915:   $$parser['-1']->xml_mode('1');
  916:   if ( $dir eq '' ) {
  917:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
  918:   } else {
  919:     push (@Apache::lonxml::pwd, $dir);
  920:   } 
  921: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
  922: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
  923: }
  924: 
  925: sub parstring {
  926:   my ($token) = @_;
  927:   my $temp='';
  928:   foreach (@{$token->[3]}) {
  929:     unless ($_=~/\W/) {
  930:       my $val=$token->[2]->{$_};
  931:       $val =~ s/([\%\@\\])/\\$1/g;
  932:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
  933:       $temp .= "my \$$_=\"$val\";"
  934:     }
  935:   }
  936:   return $temp;
  937: }
  938: 
  939: sub writeallows {
  940:     unless ($#extlinks>=0) { return; }
  941:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
  942:     if ($ENV{'httpref.'.$thisurl}) {
  943: 	$thisurl=$ENV{'httpref.'.$thisurl};
  944:     }
  945:     my $thisdir=$thisurl;
  946:     $thisdir=~s/\/[^\/]+$//;
  947:     my %httpref=();
  948:     foreach (@extlinks) {
  949:        $httpref{'httpref.'.
  950:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
  951:     }
  952:     @extlinks=();
  953:     &Apache::lonnet::appenv(%httpref);
  954: }
  955: 
  956: #
  957: # Afterburner handles anchors, highlights and links
  958: #
  959: sub afterburn {
  960:     my $result=shift;
  961:     foreach (split(/&/,$ENV{'QUERY_STRING'})) {
  962:        my ($name, $value) = split(/=/,$_);
  963:        $value =~ tr/+/ /;
  964:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  965:        if (($name eq 'highlight')||($name eq 'anchor')||($name eq 'link')) {
  966:            unless ($ENV{'form.'.$name}) {
  967:               $ENV{'form.'.$name}=$value;
  968: 	   }
  969:        }
  970:     }
  971:     if ($ENV{'form.highlight'}) {
  972:        foreach (split(/\,/,$ENV{'form.highlight'})) {
  973:            my $anchorname=$_;
  974: 	   my $matchthis=$anchorname;
  975:            $matchthis=~s/\_+/\\s\+/g;
  976:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
  977:        }
  978:     }
  979:     if ($ENV{'form.link'}) {
  980:        foreach (split(/\,/,$ENV{'form.link'})) {
  981:            my ($anchorname,$linkurl)=split(/\>/,$_);
  982: 	   my $matchthis=$anchorname;
  983:            $matchthis=~s/\_+/\\s\+/g;
  984:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
  985:        }
  986:     }
  987:     if ($ENV{'form.anchor'}) {
  988:         my $anchorname=$ENV{'form.anchor'};
  989: 	my $matchthis=$anchorname;
  990:         $matchthis=~s/\_+/\\s\+/g;
  991:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
  992:         $result.=(<<"ENDSCRIPT");
  993: <script>
  994:     document.location.hash='$anchorname';
  995: </script>
  996: ENDSCRIPT
  997:     }
  998:     return $result;
  999: }
 1000: 
 1001: sub storefile {
 1002:     my ($file,$contents)=@_;
 1003:     if (my $fh=Apache::File->new('>'.$file)) {
 1004: 	print $fh $contents;
 1005:         $fh->close();
 1006:     }
 1007: }
 1008: 
 1009: sub inserteditinfo {
 1010:       my ($result,$filecontents)=@_;
 1011:       unless ($filecontents) {
 1012: 	  $filecontents=(<<SIMPLECONTENT);
 1013: <html>
 1014: <head>
 1015: <title>
 1016:                            Title of Document Goes Here
 1017: </title>
 1018: </head>
 1019: <body bgcolor="#FFFFFF">
 1020: 
 1021:                            Body of Document Goes Here
 1022: 
 1023: </body>
 1024: </html>
 1025: SIMPLECONTENT
 1026:       }
 1027:       my $editheader='<a href="#editsection">Edit below</a><hr />';
 1028:       my $editfooter=(<<ENDFOOTER);
 1029: <hr />
 1030: <a name="editsection" />
 1031: <form method="post">
 1032: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
 1033: <br />
 1034: <input type="submit" name="attemptclean" 
 1035:        value="Save and then attempt to clean HTML" />
 1036: <input type="submit" name="savethisfile" value="Save this" />
 1037: </form>
 1038: ENDFOOTER
 1039:       $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1040:       $result=~s/(\<\/body\>)/$editfooter/is;
 1041:       return $result;
 1042: }
 1043: 
 1044: sub handler {
 1045:   my $request=shift;
 1046: 
 1047:   my $target='web';
 1048: 
 1049:   $Apache::lonxml::debug=0;
 1050: 
 1051:   if ($ENV{'browser.mathml'}) {
 1052:     $request->content_type('text/xml');
 1053:   } else {
 1054:     $request->content_type('text/html');
 1055:   }
 1056:   &Apache::loncommon::no_cache($request);
 1057:   $request->send_http_header;
 1058: 
 1059:   return OK if $request->header_only;
 1060: 
 1061: 
 1062:   my $file=&Apache::lonnet::filelocation("",$request->uri);
 1063: #
 1064: # Edit action? Save file.
 1065: #
 1066:   unless ($ENV{'request.state'} eq 'published') {
 1067:       if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
 1068: 	  &storefile($file,$ENV{'form.filecont'});
 1069:       }
 1070:   }
 1071:   my %mystyle;
 1072:   my $result = ''; 
 1073:   my $filecontents=&Apache::lonnet::getfile($file);
 1074:   if ($filecontents == -1) {
 1075:     $result=(<<ENDNOTFOUND);
 1076: <html>
 1077: <head>
 1078: <title>File not found</title>
 1079: </head>
 1080: <body bgcolor="#FFFFFF">
 1081: <b>File not found: $file</b>
 1082: </body>
 1083: </html>
 1084: ENDNOTFOUND
 1085:     $filecontents='';
 1086:   } else {
 1087:       unless ($ENV{'request.state'} eq 'published') {
 1088:          if ($ENV{'form.attemptclean'}) {
 1089: 	    $filecontents=&htmlclean($filecontents,1);
 1090:          }
 1091:       }
 1092:     $result = &Apache::lonxml::xmlparse($target,$filecontents,'',%mystyle);
 1093:   }
 1094: 
 1095: #
 1096: # Edit action? Insert editing commands
 1097: #
 1098:   unless ($ENV{'request.state'} eq 'published') {
 1099:       $result=&inserteditinfo($result,$filecontents);
 1100:   }
 1101:   
 1102:   writeallows($request->uri);
 1103: 
 1104:   $request->print($result);
 1105: 
 1106:   return OK;
 1107: }
 1108:  
 1109: sub debug {
 1110:   if ($Apache::lonxml::debug eq 1) {
 1111:     print("DEBUG:".$_[0]."<br />\n");
 1112:   }
 1113: }
 1114: 
 1115: sub error {
 1116:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
 1117:     print "<b>ERROR:</b>".$_[0]."<br />\n";
 1118:   } else {
 1119:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
 1120:     #notify author
 1121:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},$_[0]);
 1122:     #notify course
 1123:     if ( $ENV{'request.course.id'} ) {
 1124:       my $users=$ENV{'course.'.$ENV{'request.course.id'}.'.comment.email'};
 1125:       foreach my $user (split /\,/, $users) {
 1126: 	($user,my $domain) = split /:/, $user;
 1127: 	&Apache::lonmsg::user_normal_msg($user,$domain,"Error in $ENV{'request.filename'}",$_[0]);
 1128:       }
 1129:     }
 1130: 
 1131:     #FIXME probably shouldn't have me get everything forever.
 1132:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",$_[0]);
 1133:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
 1134:   }
 1135: }
 1136: 
 1137: sub warning {
 1138:   if ($ENV{'request.state'} eq 'construct') {
 1139:     print "<b>W</b>ARNING<b>:</b>".$_[0]."<br />\n";
 1140:   }
 1141: }
 1142: 
 1143: sub get_param {
 1144:   my ($param,$parstack,$safeeval,$context) = @_;
 1145:   if ( ! $context ) { $context = -1; }
 1146:   my $args ='';
 1147:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1148:   if ( $args =~ /my \$$param=\"/ ) {
 1149:     return &Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1150:   } else {
 1151:     return undef;
 1152:   }
 1153: }
 1154: 
 1155: sub get_param_var {
 1156:   my ($param,$parstack,$safeeval,$context) = @_;
 1157:   if ( ! $context ) { $context = -1; }
 1158:   my $args ='';
 1159:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1160:   if ( $args !~ /my \$$param=\"/ ) { return undef; }
 1161:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1162:   if ($value =~ /^[\$\@\%]/) {
 1163:     return &Apache::run::run("return $value",$safeeval,1);
 1164:   } else {
 1165:     return $value;
 1166:   }
 1167: }
 1168: 
 1169: sub register_insert {
 1170:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1171:   my $i;
 1172:   my $tagnum=0;
 1173:   my @order;
 1174:   for ($i=0;$i < $#data; $i++) {
 1175:     my $line = $data[$i];
 1176:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1177:     if ( $line =~ /TABLE/ ) { last; }
 1178:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
 1179:     if ($tag) {
 1180:       $insertlist{"$tagnum.tag"} = $tag;
 1181:       $insertlist{"$tagnum.description"} = $descrip;
 1182:       $insertlist{"$tagnum.color"} = $color;
 1183:       $insertlist{"$tagnum.function"} = $function;
 1184:       if (!defined($show)) { $show='yes'; }
 1185:       $insertlist{"$tagnum.show"}= $show;
 1186:       $insertlist{"$tag.num"}=$tagnum;
 1187:       $tagnum++;
 1188:     }
 1189:   }
 1190:   $i++; #skipping TABLE line
 1191:   $tagnum = 0;
 1192:   for (;$i < $#data;$i++) {
 1193:     my $line = $data[$i];
 1194:     my ($mnemonic,@which) = split(/ +/,$line);
 1195:     my $tag = $insertlist{"$tagnum.tag"};
 1196:     for (my $j=0;$j <$#which;$j++) {
 1197:       if ( $which[$j] eq 'Y' ) {
 1198: 	if ($insertlist{"$j.show"} ne 'no') {
 1199: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1200: 	}
 1201:       }
 1202:     }
 1203:     $tagnum++;
 1204:   }
 1205: }
 1206: 
 1207: sub description {
 1208:   my ($token)=@_;
 1209:   my $tagnum;
 1210:   my $tag=$token->[1];
 1211:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1212:     my $testtag=$namespace.'::'.$tag;
 1213:     $tagnum=$insertlist{"$testtag.num"};
 1214:     if (defined($tagnum)) { last; }
 1215:   }
 1216:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1217:   return $insertlist{$tagnum.'.description'};
 1218: }
 1219: 
 1220: # ----------------------------------------------------------------- whichuser
 1221: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1222: # calls to lonnet functions for this setup.
 1223: # - looks for form.grade_ parameters
 1224: sub whichuser {
 1225:   my ($symb,$courseid,$domain,$name);
 1226:   if (defined($ENV{'form.grade_symb'})) {
 1227:     my $tmp_courseid=$ENV{'form.grade_courseid'};
 1228:     my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
 1229:     if ($allowed) {
 1230:       $symb=$ENV{'form.grade_symb'};
 1231:       $courseid=$ENV{'form.grade_courseid'};
 1232:       $domain=$ENV{'form.grade_domain'};
 1233:       $name=$ENV{'form.grade_username'};
 1234:     }
 1235:   } else {
 1236:     $symb=&Apache::lonnet::symbread();
 1237:     $courseid=$ENV{'request.course.id'};
 1238:     $domain=$ENV{'user.domain'};
 1239:     $name=$ENV{'user.name'};
 1240:   }
 1241:   return ($symb,$courseid,$domain,$name);
 1242: }
 1243: 
 1244: 1;
 1245: __END__
 1246: 
 1247: 

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