File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.154: download - view: text, annotated - select for diffs
Tue Feb 26 21:00:38 2002 UTC (22 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- use the newly updated loncommon::get_unprocessed_cgi command

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

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