File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.140: download - view: text, annotated - select for diffs
Thu Nov 29 21:38:17 2001 UTC (22 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- cleaned out some blanks
- updated the error messages to be more readable

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

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