File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.160: download - view: text, annotated - select for diffs
Thu Mar 21 22:10:31 2002 UTC (22 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Was logging out on Explorer because it opened up itself.

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

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