File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.141: download - view: text, annotated - select for diffs
Fri Dec 14 22:59:34 2001 UTC (22 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- &Apache::lonxml::register now stacks up tag registrations
- &Apache::lonxml::deregister exists

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

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