File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.139: download - view: text, annotated - select for diffs
Thu Nov 29 19:03:58 2001 UTC (22 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
GPL

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

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