File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.144: download - view: text, annotated - select for diffs
Wed Jan 2 13:18:26 2002 UTC (22 years, 5 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
register_insert no longer ignores the last item in the array.

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

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