File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.159: download - view: text, annotated - select for diffs
Thu Mar 21 20:51:10 2002 UTC (22 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Not clear out menu window

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.159 2002/03/21 20:51:10 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: 	return 
  324:          '<script>function LONCAPAreg(){} function LONCAPAstale(){}</script>';
  325:     }
  326:     if ($Apache::lonxml::registered && !$forcereg) { return ''; }
  327:     $Apache::lonxml::registered=1;
  328:     my $nothing='';
  329:     if ($ENV{'browser.type'} eq 'explorer') { $nothing='javascript:void(0);'; }
  330:     if (($ENV{'REQUEST_URI'}!~/^\/(res\/)*adm\//) || ($forcereg)) {
  331:         my $hwkadd='';
  332:         if ($ENV{'REQUEST_URI'}=~/\.(problem|exam|quiz|assess|survey|form)$/) {
  333: 	    if (&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) {
  334: 		$hwkadd.=(<<ENDSUBM);
  335:                      menu.switchbutton
  336:            (7,1,'subm.gif','view sub','missions',
  337:                 'gocmd("/adm/grades","submission")');
  338: ENDSUBM
  339:             }
  340: 	    if (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) {
  341: 		$hwkadd.=(<<ENDGRDS);
  342:                      menu.switchbutton
  343:            (7,2,'pgrd.gif','problem','grades',
  344:                 'gocmd("/adm/grades","viewgrades")');
  345: ENDGRDS
  346:             }
  347: 	    if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  348: 		$hwkadd.=(<<ENDPARM);
  349:                      menu.switchbutton
  350:            (7,3,'pparm.gif','problem','parms',
  351:                 'gocmd("/adm/parmset","set")');
  352: ENDPARM
  353:             }
  354: 	}
  355: 	$result = (<<ENDREGTHIS);
  356:      
  357: <script language="JavaScript">
  358: // BEGIN LON-CAPA Internal
  359: 
  360:     function LONCAPAreg() {
  361: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
  362:           menu.clearTimeout(menu.menucltim);
  363: 	  menu.currentURL=window.location.pathname;
  364:           menu.currentStale=0;
  365:           menu.clearbut(3,1);
  366:           menu.switchbutton
  367:        (6,3,'catalog.gif','catalog','info','catalog_info()');
  368:           menu.switchbutton
  369:        (8,1,'eval.gif','evaluate','this','gopost("/adm/evaluate",currentURL)');
  370:           menu.switchbutton
  371:     (8,2,'fdbk.gif','feedback','on this','gopost("/adm/feedback",currentURL)');
  372:           menu.switchbutton
  373:      (8,3,'prt.gif','prepare','printout','gopost("/adm/printout",currentURL)');
  374:           menu.switchbutton
  375:        (2,1,'back.gif','backward','','gopost("/adm/flip","back:"+currentURL)');
  376:           menu.switchbutton
  377:      (2,3,'forw.gif','forward','','gopost("/adm/flip","forward:"+currentURL)');
  378:           menu.switchbutton
  379:                             (9,1,'sbkm.gif','set','bookmark','set_bookmark()');
  380:           menu.switchbutton
  381:                          (9,2,'vbkm.gif','view','bookmark','edit_bookmarks()');
  382:           menu.switchbutton
  383:                                (9,3,'anot.gif','anno-','tations','annotate()');
  384:           $hwkadd
  385:     }
  386: 
  387:     function LONCAPAstale() {
  388: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
  389:           menu.currentStale=1;
  390:           menu.switchbutton
  391:              (3,1,'reload.gif','return','location','go(currentURL)');
  392:           menu.clearbut(7,1);
  393:           menu.clearbut(7,2);
  394:           menu.clearbut(7,3);
  395:           menu.menucltim=menu.setTimeout(
  396:  'clearbut(2,1);clearbut(2,3);clearbut(8,1);clearbut(8,2);clearbut(8,3);'+
  397:  'clearbut(9,1);clearbut(9,2);clearbut(9,3);clearbut(6,3)',
  398: 			  2000);
  399: 
  400:       }
  401: 
  402: // END LON-CAPA Internal
  403: </script>
  404: ENDREGTHIS
  405: 
  406:     } else {
  407:         $result = (<<ENDDONOTREGTHIS);
  408: 
  409: <script language="JavaScript">
  410: // BEGIN LON-CAPA Internal
  411: 
  412:     function LONCAPAreg() {
  413: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
  414:           menu.currentStale=1;
  415:           menu.clearbut(2,1);
  416:           menu.clearbut(2,3);
  417:           menu.clearbut(8,1);
  418:           menu.clearbut(8,2);
  419:           menu.clearbut(8,3);
  420:           if (menu.currentURL) {
  421:              menu.switchbutton
  422:               (3,1,'reload.gif','return','location','go(currentURL)');
  423:  	  } else {
  424: 	      menu.clearbut(3,1);
  425:           }
  426:     }
  427: 
  428:     function LONCAPAstale() {
  429:     }
  430: 
  431: // END LON-CAPA Internal
  432: </script>
  433: ENDDONOTREGTHIS
  434:     }
  435:     if ($target eq 'edit') {
  436: 	# Javascript routines for construction space:
  437: 	# openbrowser and opensearcher will start the file browser
  438: 	# (lonindexer) and searcher (lonsearchcat) respectively.
  439: 	# Inputs are the name of the html form being used
  440: 	# and the name of the element the selected URL should
  441: 	# be placed in.
  442:         $result .=<<"ENDBROWSERSCRIPT";
  443: <script>
  444:     var editbrowser;
  445:     function openbrowser(formname,elementname) {
  446:         var url = '/res/?';
  447:         if (editbrowser == null) {
  448:             url += 'launch=1&';
  449:         }
  450:         url += 'catalogmode=interactive&';
  451:         url += 'mode=edit&';
  452:         url += 'form=' + formname + '&';
  453:         url += 'element=' + elementname + '';
  454:         var title = 'Browser';
  455:         var options = 'scrollbars=1,resizable=1,menubar=0';
  456:         options += ',width=700,height=600';
  457:         editbrowser = open(url,title,options,'1');
  458:         editbrowser.focus();
  459:     }
  460:     var editsearcher;
  461:     function opensearcher(formname,elementname) {
  462:         var url = '/adm/searchcat?';
  463:         if (editsearcher == null) {
  464:             url += 'launch=1&';
  465:         }
  466:         url += 'catalogmode=interactive&';
  467:         url += 'mode=edit&';
  468:         url += 'form=' + formname + '&';
  469:         url += 'element=' + elementname + '';
  470:         var title = 'Search';
  471:         var options = 'scrollbars=1,resizable=1,menubar=0';
  472:         options += ',width=700,height=600';
  473:         editsearcher = open(url,title,options,'1');
  474:         editsearcher.focus();
  475:     }
  476: </script>
  477: ENDBROWSERSCRIPT
  478:     }
  479:     return $result;
  480: }
  481: 
  482: sub loadevents() {
  483:     return 'LONCAPAreg();';
  484: }
  485: 
  486: sub unloadevents() {
  487:     return 'LONCAPAstale();';
  488: }
  489: 
  490: sub printalltags {
  491:   my $temp;
  492:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  493:     &Apache::lonxml::debug("$temp -- ".
  494: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  495:   }
  496: }
  497: 
  498: sub xmlparse {
  499:  my ($target,$content_file_string,$safeinit,%style_for_target) = @_;
  500: 
  501:  &setup_globals($target);
  502:  #&printalltags();
  503:  my @pars = ();
  504:  my $pwd=$ENV{'request.filename'};
  505:  $pwd =~ s:/[^/]*$::;
  506:  &newparser(\@pars,\$content_file_string,$pwd);
  507: 
  508:  my $safeeval = new Safe;
  509:  my $safehole = new Safe::Hole;
  510:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  511: #-------------------- Redefinition of the target in the case of compound target
  512: 
  513:  ($target, my @tenta) = split('&&',$target);
  514: 
  515:  my @stack = ();
  516:  my @parstack = ();
  517:  &initdepth;
  518: 
  519:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  520: 				   $safeeval,\%style_for_target);
  521:  if ($ENV{'request.uri'}) {
  522:     &writeallows($ENV{'request.uri'});
  523:  }
  524:  return $finaloutput;
  525: }
  526: 
  527: sub htmlclean {
  528:     my ($raw,$full)=@_;
  529: 
  530:     my $tree = HTML::TreeBuilder->new;
  531:     $tree->ignore_unknown(0);
  532: 
  533:     $tree->parse($raw);
  534: 
  535:     my $output= $tree->as_HTML(undef,' ');
  536: 
  537:     $output=~s/\<(br|hr|img|meta|allow)([^\>\/]*)\>/\<$1$2 \/\>/gis;
  538:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
  539:     unless ($full) {
  540:        $output=~s/\<[\/]*(body|head|html)\>//gis;
  541:     }
  542: 
  543:     $tree = $tree->delete;
  544: 
  545:     return $output;
  546: }
  547: 
  548: sub inner_xmlparse {
  549:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  550:   my $finaloutput = '';
  551:   my $result;
  552:   my $token;
  553:   while ( $#$pars > -1 ) {
  554:     while ($token = $$pars['-1']->get_token) {
  555:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  556: 	if ($metamode<1) {
  557: 	  $result=$token->[1];
  558: 	}
  559:       } elsif ($token->[0] eq 'PI') {
  560: 	if ($metamode<1) {
  561: 	  $result=$token->[2];
  562: 	}
  563:       } elsif ($token->[0] eq 'S') {
  564: 	# add tag to stack
  565: 	push (@$stack,$token->[1]);
  566: 	# add parameters list to another stack
  567: 	push (@$parstack,&parstring($token));
  568: 	&increasedepth($token);
  569: 	if (exists $$style_for_target{$token->[1]}) {
  570: 	  if ($Apache::lonxml::redirection) {
  571: 	    $Apache::lonxml::outputstack['-1'] .=
  572: 	      &recurse($$style_for_target{$token->[1]},$target,$safeeval,
  573: 		       $style_for_target,@$parstack);
  574: 	  } else {
  575: 	    $finaloutput .= &recurse($$style_for_target{$token->[1]},$target,
  576: 				     $safeeval,$style_for_target,@$parstack);
  577: 	  }
  578: 	} else {
  579: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  580: 			     $parstack, $pars, $safeeval, $style_for_target);
  581: 	}
  582:       } elsif ($token->[0] eq 'E') {
  583: 	#clear out any tags that didn't end
  584: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  585: 	  my $lasttag=$$stack[-1];
  586: 	  if ($token->[1] =~ /^$lasttag$/i) {
  587: 	    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; as end tag to &lt;'.$$stack[-1].'&gt;');
  588: 	    last;
  589: 	  } else {
  590: 	    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; when looking for &lt;/'.$$stack[-1].'&gt; in file');
  591: 	    &end_tag($stack,$parstack,$token);
  592: 	  }
  593: 	}
  594: 
  595: 	if (exists($$style_for_target{'/'."$token->[1]"})) {
  596: 	  if ($Apache::lonxml::redirection) {
  597: 	    $Apache::lonxml::outputstack['-1'] .=  
  598: 	      &recurse($$style_for_target{'/'."$token->[1]"},
  599: 		       $target,$safeeval,$style_for_target,@$parstack);
  600: 	  } else {
  601: 	    $finaloutput .= &recurse($$style_for_target{'/'."$token->[1]"},
  602: 				     $target,$safeeval,$style_for_target,
  603: 				     @$parstack);
  604: 	  }
  605: 	} else {
  606: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
  607: 			     $parstack, $pars,$safeeval, $style_for_target);
  608: 	}
  609:       } else {
  610: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  611:       }
  612:       #evaluate variable refs in result
  613:       if ($result ne "") {
  614: 	if ( $#$parstack > -1 ) {
  615: 	  if ($Apache::lonxml::redirection) {
  616: 	    $Apache::lonxml::outputstack['-1'] .= 
  617: 	      &Apache::run::evaluate($result,$safeeval,$$parstack['-1']);
  618: 	  } else {
  619: 	    $finaloutput .= &Apache::run::evaluate($result,$safeeval,
  620: 						   $$parstack['-1']);
  621: 	  }
  622: 	} else {
  623: 	  $finaloutput .= &Apache::run::evaluate($result,$safeeval,'');
  624: 	}
  625: 	$result = '';
  626:       } 
  627:       if ($token->[0] eq 'E') { 
  628: 	&end_tag($stack,$parstack,$token);
  629:       }
  630:     }
  631:     pop @$pars;
  632:     pop @Apache::lonxml::pwd;
  633:   }
  634: 
  635:   # if ($target eq 'meta') {
  636:   #   $finaloutput.=&endredirection;
  637:   # }
  638: 
  639:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  640:     $finaloutput=&afterburn($finaloutput);
  641:   }
  642:   return $finaloutput;
  643: }
  644: 
  645: sub recurse {
  646:   my @innerstack = (); 
  647:   my @innerparstack = ();
  648:   my ($newarg,$target,$safeeval,$style_for_target,@parstack) = @_;
  649:   my @pat = ();
  650:   &newparser(\@pat,\$newarg);
  651:   my $tokenpat;
  652:   my $partstring = '';
  653:   my $output='';
  654:   my $decls='';
  655:   &Apache::lonxml::debug("Recursing");
  656:   while ( $#pat > -1 ) {
  657:     while  ($tokenpat = $pat[$#pat]->get_token) {
  658:       if (($tokenpat->[0] eq 'T') || ($tokenpat->[0] eq 'C') || ($tokenpat->[0] eq 'D') ) {
  659: 	if ($metamode<1) { $partstring=$tokenpat->[1]; }
  660:       } elsif ($tokenpat->[0] eq 'PI') {
  661: 	if ($metamode<1) { $partstring=$tokenpat->[2]; }
  662:       } elsif ($tokenpat->[0] eq 'S') {
  663: 	push (@innerstack,$tokenpat->[1]);
  664: 	push (@innerparstack,&parstring($tokenpat));
  665: 	&increasedepth($tokenpat);
  666: 	$partstring = &callsub("start_$tokenpat->[1]", $target, $tokenpat,
  667: 			       \@innerstack, \@innerparstack, \@pat,
  668: 			       $safeeval, $style_for_target);
  669:       } elsif ($tokenpat->[0] eq 'E') {
  670: 	#clear out any tags that didn't end
  671: 	while ($tokenpat->[1] ne $innerstack[$#innerstack]
  672: 	       && ($#innerstack > -1)) {
  673: 	  my $lasttag=$innerstack[-1];
  674: 	  if ($tokenpat->[1] =~ /^$lasttag$/i) {
  675: 	    &Apache::lonxml::warning('Using tag &lt;/'.$tokenpat->[1].'&gt; as end tag to &lt;'.$innerstack[-1].'&gt;');
  676: 	    last;
  677: 	  } else {
  678: 	    &Apache::lonxml::warning('Found tag &lt;/'.$tokenpat->[1].'&gt; when looking for &lt;/'.$innerstack[-1].'&gt; in file');
  679: 	    &end_tag(\@innerstack,\@innerparstack,$tokenpat);
  680: 	  }
  681: 	}
  682: 	$partstring = &callsub("end_$tokenpat->[1]", $target, $tokenpat,
  683: 			       \@innerstack, \@innerparstack, \@pat,
  684: 			       $safeeval, $style_for_target);
  685:       } else {
  686: 	&Apache::lonxml::error("Unknown token event :$tokenpat->[0]:$tokenpat->[1]:");
  687:       }
  688:       #pass both the variable to the style tag, and the tag we 
  689:       #are processing inside the <definedtag>
  690:       if ( $partstring ne "" ) {
  691: 	if ( $#parstack > -1 ) { 
  692: 	  if ( $#innerparstack > -1 ) { 
  693: 	    $decls= $parstack[$#parstack].$innerparstack[$#innerparstack];
  694: 	  } else {
  695: 	    $decls= $parstack[$#parstack];
  696: 	  }
  697: 	} else {
  698: 	  if ( $#innerparstack > -1 ) { 
  699: 	    $decls=$innerparstack[$#innerparstack];
  700: 	  } else {
  701: 	    $decls='';
  702: 	  }
  703: 	}
  704: 	$output .= &Apache::run::evaluate($partstring,$safeeval,$decls);
  705: 	$partstring = '';
  706:       }
  707:       if ($tokenpat->[0] eq 'E') { pop @innerstack;pop @innerparstack;
  708: 				 &decreasedepth($tokenpat);}
  709:     }
  710:     pop @pat;
  711:     pop @Apache::lonxml::pwd;
  712:   }
  713:   &Apache::lonxml::debug("Exiting Recursing");
  714:   return $output;
  715: }
  716: 
  717: sub callsub {
  718:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  719:   my $currentstring='';
  720:   my $nodefault;
  721:   {
  722:     my $sub1;
  723:     no strict 'refs';
  724:     my $tag=$token->[1];
  725:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  726:     if (!$space) {
  727:      	$tag=~tr/A-Z/a-z/;
  728: 	$sub=~tr/A-Z/a-z/;
  729: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  730:     }
  731: 
  732:     my $deleted=0;
  733:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  734:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  735:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  736: 					     $parstack,$parser,$safeeval,
  737: 					     $style);
  738:     }
  739:     if (!$deleted) {
  740:       if ($space) {
  741: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  742: 	$sub1="$space\:\:$sub";
  743: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  744: 					     $parstack,$parser,$safeeval,
  745: 					     $style);
  746:       } else {
  747: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  748: 	if ($metamode <1) {
  749: 	  if (defined($token->[4]) && ($metamode < 1)) {
  750: 	    $currentstring = $token->[4];
  751: 	  } else {
  752: 	    $currentstring = $token->[2];
  753: 	  }
  754: 	}
  755:       }
  756:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  757:       if ($currentstring eq '' && $nodefault eq '') {
  758: 	if ($target eq 'edit') {
  759: 	  &Apache::lonxml::debug("doing default edit for $token->[1]");
  760: 	  if ($token->[0] eq 'S') {
  761: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  762: 	  } elsif ($token->[0] eq 'E') {
  763: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  764: 	  }
  765: 	} elsif ($target eq 'modified') {
  766: 	  if ($token->[0] eq 'S') {
  767: 	    $currentstring = $token->[4];
  768: 	    $currentstring.=&Apache::edit::handle_insert();
  769: 	  } else {
  770: 	    $currentstring = $token->[2];
  771: 	  }
  772: 	}
  773:       }
  774:     }
  775:     use strict 'refs';
  776:   }
  777:   return $currentstring;
  778: }
  779: 
  780: sub setup_globals {
  781:   my ($target)=@_;
  782:   $Apache::lonxml::registered = 0;
  783:   @Apache::lonxml::pwd=();
  784:   @Apache::lonxml::extlinks=();
  785:   if ($target eq 'meta') {
  786:     $Apache::lonxml::redirection = 0;
  787:     $Apache::lonxml::metamode = 1;
  788:     $Apache::lonxml::evaluate = 1;
  789:     $Apache::lonxml::import = 0;
  790:   } elsif ($target eq 'answer') {
  791:     $Apache::lonxml::redirection = 0;
  792:     $Apache::lonxml::metamode = 1;
  793:     $Apache::lonxml::evaluate = 1;
  794:     $Apache::lonxml::import = 1;
  795:   } elsif ($target eq 'grade') {
  796:     &startredirection;
  797:     $Apache::lonxml::metamode = 0;
  798:     $Apache::lonxml::evaluate = 1;
  799:     $Apache::lonxml::import = 1;
  800:   } elsif ($target eq 'modified') {
  801:     $Apache::lonxml::redirection = 0;
  802:     $Apache::lonxml::metamode = 0;
  803:     $Apache::lonxml::evaluate = 0;
  804:     $Apache::lonxml::import = 0;
  805:   } elsif ($target eq 'edit') {
  806:     $Apache::lonxml::redirection = 0;
  807:     $Apache::lonxml::metamode = 0;
  808:     $Apache::lonxml::evaluate = 0;
  809:     $Apache::lonxml::import = 0;
  810:   } else {
  811:     $Apache::lonxml::redirection = 0;
  812:     $Apache::lonxml::metamode = 0;
  813:     $Apache::lonxml::evaluate = 1;
  814:     $Apache::lonxml::import = 1;
  815:   }
  816: }
  817: 
  818: sub init_safespace {
  819:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  820:   $safeeval->permit("entereval");
  821:   $safeeval->permit(":base_math");
  822:   $safeeval->permit("sort");
  823:   $safeeval->deny(":base_io");
  824:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  825:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  826:   
  827:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  828:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  829:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  830:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  831:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  832:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  833:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  834:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  835:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  836:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  837:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  838:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  839:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  840:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  841:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  842:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  843:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  844:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  845:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  846:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  847:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  848:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  849:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  850:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  851:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  852:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  853:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  854:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  855:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  856:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  857:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  858:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  859:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  860:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  861:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  862:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  863:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  864:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  865:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  866:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  867: 
  868: #need to inspect this class of ops
  869: # $safeeval->deny(":base_orig");
  870:   $safeinit .= ';$external::target="'.$target.'";';
  871:   my $rndseed;
  872:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  873:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  874:   $safeinit .= ';$external::randomseed='.$rndseed.';';
  875:   &Apache::run::run($safeinit,$safeeval);
  876: }
  877: 
  878: sub startredirection {
  879:   $Apache::lonxml::redirection++;
  880:   push (@Apache::lonxml::outputstack, '');
  881: }
  882: 
  883: sub endredirection {
  884:   if (!$Apache::lonxml::redirection) {
  885:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  886:     return '';
  887:   }
  888:   $Apache::lonxml::redirection--;
  889:   pop @Apache::lonxml::outputstack;
  890: }
  891: 
  892: sub end_tag {
  893:   my ($tagstack,$parstack,$token)=@_;
  894:   pop(@$tagstack);
  895:   pop(@$parstack);
  896:   &decreasedepth($token);
  897: }
  898: 
  899: sub initdepth {
  900:   @Apache::lonxml::depthcounter=();
  901:   $Apache::lonxml::depth=-1;
  902:   $Apache::lonxml::olddepth=-1;
  903: }
  904: 
  905: sub increasedepth {
  906:   my ($token) = @_;
  907:   $Apache::lonxml::depth++;
  908:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  909:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  910:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  911:   }
  912:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  913:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  914: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  915: }
  916: 
  917: sub decreasedepth {
  918:   my ($token) = @_;
  919:   $Apache::lonxml::depth--;
  920:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  921:     $#Apache::lonxml::depthcounter--;
  922:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  923:   }
  924:   if (  $Apache::lonxml::depth < -1) {
  925:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
  926:     $Apache::lonxml::depth='-1';
  927:   }
  928:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  929:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  930: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  931: }
  932: 
  933: sub get_all_text {
  934: 
  935:  my($tag,$pars)= @_;
  936:  my $depth=0;
  937:  my $token;
  938:  my $result='';
  939:  if ( $tag =~ m:^/: ) { 
  940:    my $tag=substr($tag,1); 
  941: #   &Apache::lonxml::debug("have:$tag:");
  942:    while (($depth >=0) && ($token = $pars->get_token)) {
  943: #     &Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]");
  944:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  945:        $result.=$token->[1];
  946:      } elsif ($token->[0] eq 'PI') {
  947:        $result.=$token->[2];
  948:      } elsif ($token->[0] eq 'S') {
  949:        if ($token->[1] =~ /^$tag$/i) { $depth++; }
  950:        $result.=$token->[4];
  951:      } elsif ($token->[0] eq 'E')  {
  952:        if ( $token->[1] =~ /^$tag$/i) { $depth--; }
  953:        #skip sending back the last end tag
  954:        if ($depth > -1) { $result.=$token->[2]; } else {
  955: 	 $pars->unget_token($token);
  956:        }
  957:      }
  958:    }
  959:  } else {
  960:    while ($token = $pars->get_token) {
  961: #     &Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
  962:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  963:        $result.=$token->[1];
  964:      } elsif ($token->[0] eq 'PI') {
  965:        $result.=$token->[2];
  966:      } elsif ($token->[0] eq 'S') {
  967:        if ( $token->[1] =~ /^$tag$/i) {
  968: 	 $pars->unget_token($token); last;
  969:        } else {
  970: 	 $result.=$token->[4];
  971:        }
  972:      } elsif ($token->[0] eq 'E')  {
  973:        $result.=$token->[2];
  974:      }
  975:    }
  976:  }
  977: # &Apache::lonxml::debug("Exit:$result:");
  978:  return $result
  979: }
  980: 
  981: sub newparser {
  982:   my ($parser,$contentref,$dir) = @_;
  983:   push (@$parser,HTML::TokeParser->new($contentref));
  984:   $$parser['-1']->xml_mode('1');
  985:   if ( $dir eq '' ) {
  986:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
  987:   } else {
  988:     push (@Apache::lonxml::pwd, $dir);
  989:   } 
  990: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
  991: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
  992: }
  993: 
  994: sub parstring {
  995:   my ($token) = @_;
  996:   my $temp='';
  997:   foreach (@{$token->[3]}) {
  998:     unless ($_=~/\W/) {
  999:       my $val=$token->[2]->{$_};
 1000:       $val =~ s/([\%\@\\\"])/\\$1/g;
 1001:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1002:       $temp .= "my \$$_=\"$val\";"
 1003:     }
 1004:   }
 1005:   return $temp;
 1006: }
 1007: 
 1008: sub writeallows {
 1009:     unless ($#extlinks>=0) { return; }
 1010:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
 1011:     if ($ENV{'httpref.'.$thisurl}) {
 1012: 	$thisurl=$ENV{'httpref.'.$thisurl};
 1013:     }
 1014:     my $thisdir=$thisurl;
 1015:     $thisdir=~s/\/[^\/]+$//;
 1016:     my %httpref=();
 1017:     foreach (@extlinks) {
 1018:        $httpref{'httpref.'.
 1019:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1020:     }
 1021:     @extlinks=();
 1022:     &Apache::lonnet::appenv(%httpref);
 1023: }
 1024: 
 1025: #
 1026: # Afterburner handles anchors, highlights and links
 1027: #
 1028: sub afterburn {
 1029:     my $result=shift;
 1030:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1031: 					    ['highlight','anchor','link']);
 1032:     if ($ENV{'form.highlight'}) {
 1033:        foreach (split(/\,/,$ENV{'form.highlight'})) {
 1034:            my $anchorname=$_;
 1035: 	   my $matchthis=$anchorname;
 1036:            $matchthis=~s/\_+/\\s\+/g;
 1037:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1038:        }
 1039:     }
 1040:     if ($ENV{'form.link'}) {
 1041:        foreach (split(/\,/,$ENV{'form.link'})) {
 1042:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1043: 	   my $matchthis=$anchorname;
 1044:            $matchthis=~s/\_+/\\s\+/g;
 1045:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1046:        }
 1047:     }
 1048:     if ($ENV{'form.anchor'}) {
 1049:         my $anchorname=$ENV{'form.anchor'};
 1050: 	my $matchthis=$anchorname;
 1051:         $matchthis=~s/\_+/\\s\+/g;
 1052:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1053:         $result.=(<<"ENDSCRIPT");
 1054: <script>
 1055:     document.location.hash='$anchorname';
 1056: </script>
 1057: ENDSCRIPT
 1058:     }
 1059:     return $result;
 1060: }
 1061: 
 1062: sub storefile {
 1063:     my ($file,$contents)=@_;
 1064:     if (my $fh=Apache::File->new('>'.$file)) {
 1065: 	print $fh $contents;
 1066:         $fh->close();
 1067:     } else {
 1068:       &warning("Unable to save file $file");
 1069:     }
 1070: }
 1071: 
 1072: sub createnewhtml {
 1073:   my $filecontents=(<<SIMPLECONTENT);
 1074: <html>
 1075: <head>
 1076: <title>
 1077:                            Title of Document Goes Here
 1078: </title>
 1079: </head>
 1080: <body bgcolor="#FFFFFF">
 1081: 
 1082:                            Body of Document Goes Here
 1083: 
 1084: </body>
 1085: </html>
 1086: SIMPLECONTENT
 1087:   return $filecontents;
 1088: }
 1089: 
 1090: 
 1091: sub inserteditinfo {
 1092:       my ($result,$filecontents)=@_;
 1093:       $filecontents = &HTML::Entities::encode($filecontents);
 1094: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1095:       my $editfooter=(<<ENDFOOTER);
 1096: <hr />
 1097: <a name="editsection" />
 1098: <form method="post">
 1099: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
 1100: <br />
 1101: <input type="hidden" name="showmode" value="Edit" />
 1102: <input type="submit" name="attemptclean" 
 1103:        value="Save and then attempt to clean HTML" />
 1104: <input type="submit" name="savethisfile" value="Save this" />
 1105: <input type="submit" name="showmode" value="View" />
 1106: </form>
 1107: ENDFOOTER
 1108: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1109:       $result=~s/(\<\/body\>)/$editfooter/is;
 1110:       return $result;
 1111: }
 1112: 
 1113: sub get_target {
 1114:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
 1115:   if ( $ENV{'request.state'} eq 'published') {
 1116:     if ( defined($ENV{'form.grade_target'})
 1117: 	 && ($viewgrades == 'F' )) {
 1118:       return ($ENV{'form.grade_target'});
 1119:     } elsif (defined($ENV{'form.grade_target'})) {
 1120:       if (($ENV{'form.grade_target'} eq 'web') ||
 1121: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
 1122: 	return $ENV{'form.grade_target'}
 1123:       } else {
 1124: 	return 'web';
 1125:       }
 1126:     } else {
 1127:       return 'web';
 1128:     }
 1129:   } elsif ($ENV{'request.state'} eq 'construct') {
 1130:     if ( defined($ENV{'form.grade_target'})) {
 1131:       return ($ENV{'form.grade_target'});
 1132:     } else {
 1133:       return 'web';
 1134:     }
 1135:   } else {
 1136:     return 'web';
 1137:   }
 1138: }
 1139: 
 1140: sub handler {
 1141:   my $request=shift;
 1142: 
 1143:   my $target=&get_target();
 1144: 
 1145:   $Apache::lonxml::debug=0;
 1146: 
 1147:   if ($ENV{'browser.mathml'}) {
 1148:     $request->content_type('text/xml');
 1149:   } else {
 1150:     $request->content_type('text/html');
 1151:   }
 1152:   &Apache::loncommon::no_cache($request);
 1153:   $request->send_http_header;
 1154: 
 1155:   return OK if $request->header_only;
 1156: 
 1157: 
 1158:   my $file=&Apache::lonnet::filelocation("",$request->uri);
 1159: #
 1160: # Edit action? Save file.
 1161: #
 1162:   unless ($ENV{'request.state'} eq 'published') {
 1163:       if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
 1164: 	  &storefile($file,$ENV{'form.filecont'});
 1165:       }
 1166:   }
 1167:   my %mystyle;
 1168:   my $result = '';
 1169:   my $filecontents=&Apache::lonnet::getfile($file);
 1170:   if ($filecontents == -1) {
 1171:     $result=(<<ENDNOTFOUND);
 1172: <html>
 1173: <head>
 1174: <title>File not found</title>
 1175: </head>
 1176: <body bgcolor="#FFFFFF">
 1177: <b>File not found: $file</b>
 1178: </body>
 1179: </html>
 1180: ENDNOTFOUND
 1181:     $filecontents='';
 1182:     if ($ENV{'request.state'} ne 'published') {
 1183:       $filecontents=&createnewhtml();
 1184:       $ENV{'form.showmode'}='Edit'; #force edit mode
 1185:     }
 1186:   } else {
 1187:     unless ($ENV{'request.state'} eq 'published') {
 1188:       if ($ENV{'form.attemptclean'}) {
 1189: 	$filecontents=&htmlclean($filecontents,1);
 1190:       }
 1191:     }
 1192:     if ($ENV{'form.showmode'} ne 'Edit') {
 1193:       $result = &Apache::lonxml::xmlparse($target,$filecontents,'',%mystyle);
 1194:     }
 1195:   }
 1196: 
 1197: #
 1198: # Edit action? Insert editing commands
 1199: #
 1200:   unless ($ENV{'request.state'} eq 'published') {
 1201:     if ($ENV{'form.showmode'} eq 'Edit') {
 1202:       $result='<html><body bgcolor="#FFFFFF"></body></html>';
 1203:       $result=&inserteditinfo($result,$filecontents);
 1204:     }
 1205:   }
 1206: 
 1207:   writeallows($request->uri);
 1208: 
 1209:   $request->print($result);
 1210: 
 1211:   return OK;
 1212: }
 1213: 
 1214: sub debug {
 1215:   if ($Apache::lonxml::debug eq 1) {
 1216:     $|=1;
 1217:     print("DEBUG:".join('<br />',@_)."<br />\n");
 1218:   }
 1219: }
 1220: 
 1221: sub error {
 1222:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
 1223:     print "<b>ERROR:</b>".join('<br />',@_)."<br />\n";
 1224:   } else {
 1225:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
 1226:     #notify author
 1227:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
 1228:     #notify course
 1229:     if ( $ENV{'request.course.id'} ) {
 1230:       my $users=$ENV{'course.'.$ENV{'request.course.id'}.'.comment.email'};
 1231:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
 1232:       foreach my $user (split /\,/, $users) {
 1233: 	($user,my $domain) = split /:/, $user;
 1234: 	&Apache::lonmsg::user_normal_msg($user,$domain,
 1235:         "Error [$declutter]",join('<br />',@_));
 1236:       }
 1237:     }
 1238: 
 1239:     #FIXME probably shouldn't have me get everything forever.
 1240:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
 1241:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
 1242:   }
 1243: }
 1244: 
 1245: sub warning {
 1246:   if ($ENV{'request.state'} eq 'construct') {
 1247:     print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
 1248:   }
 1249: }
 1250: 
 1251: sub get_param {
 1252:   my ($param,$parstack,$safeeval,$context) = @_;
 1253:   if ( ! $context ) { $context = -1; }
 1254:   my $args ='';
 1255:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1256:   if ( ! $args ) { return undef; }
 1257:   if ( $args =~ /my \$$param=\"/ ) {
 1258:     return &Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1259:   } else {
 1260:     return undef;
 1261:   }
 1262: }
 1263: 
 1264: sub get_param_var {
 1265:   my ($param,$parstack,$safeeval,$context) = @_;
 1266:   if ( ! $context ) { $context = -1; }
 1267:   my $args ='';
 1268:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1269:   if ( $args !~ /my \$$param=\"/ ) { return undef; }
 1270:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1271:   if ($value =~ /^[\$\@\%]/) {
 1272:     return &Apache::run::run("return $value",$safeeval,1);
 1273:   } else {
 1274:     return $value;
 1275:   }
 1276: }
 1277: 
 1278: sub register_insert {
 1279:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1280:   my $i;
 1281:   my $tagnum=0;
 1282:   my @order;
 1283:   for ($i=0;$i < $#data; $i++) {
 1284:     my $line = $data[$i];
 1285:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1286:     if ( $line =~ /TABLE/ ) { last; }
 1287:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
 1288:     if ($tag) {
 1289:       $insertlist{"$tagnum.tag"} = $tag;
 1290:       $insertlist{"$tagnum.description"} = $descrip;
 1291:       $insertlist{"$tagnum.color"} = $color;
 1292:       $insertlist{"$tagnum.function"} = $function;
 1293:       if (!defined($show)) { $show='yes'; }
 1294:       $insertlist{"$tagnum.show"}= $show;
 1295:       $insertlist{"$tag.num"}=$tagnum;
 1296:       $tagnum++;
 1297:     }
 1298:   }
 1299:   $i++; #skipping TABLE line
 1300:   $tagnum = 0;
 1301:   for (;$i < $#data;$i++) {
 1302:     my $line = $data[$i];
 1303:     my ($mnemonic,@which) = split(/ +/,$line);
 1304:     my $tag = $insertlist{"$tagnum.tag"};
 1305:     for (my $j=0;$j <=$#which;$j++) {
 1306:       if ( $which[$j] eq 'Y' ) {
 1307: 	if ($insertlist{"$j.show"} ne 'no') {
 1308: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1309: 	}
 1310:       }
 1311:     }
 1312:     $tagnum++;
 1313:   }
 1314: }
 1315: 
 1316: sub description {
 1317:   my ($token)=@_;
 1318:   my $tagnum;
 1319:   my $tag=$token->[1];
 1320:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1321:     my $testtag=$namespace.'::'.$tag;
 1322:     $tagnum=$insertlist{"$testtag.num"};
 1323:     if (defined($tagnum)) { last; }
 1324:   }
 1325:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1326:   return $insertlist{$tagnum.'.description'};
 1327: }
 1328: 
 1329: # ----------------------------------------------------------------- whichuser
 1330: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1331: # calls to lonnet functions for this setup.
 1332: # - looks for form.grade_ parameters
 1333: sub whichuser {
 1334:   my ($symb,$courseid,$domain,$name);
 1335:   if (defined($ENV{'form.grade_symb'})) {
 1336:     my $tmp_courseid=$ENV{'form.grade_courseid'};
 1337:     my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
 1338:     if ($allowed) {
 1339:       $symb=$ENV{'form.grade_symb'};
 1340:       $courseid=$ENV{'form.grade_courseid'};
 1341:       $domain=$ENV{'form.grade_domain'};
 1342:       $name=$ENV{'form.grade_username'};
 1343:     }
 1344:   } else {
 1345:     $symb=&Apache::lonnet::symbread();
 1346:     $courseid=$ENV{'request.course.id'};
 1347:     $domain=$ENV{'user.domain'};
 1348:     $name=$ENV{'user.name'};
 1349:   }
 1350:   return ($symb,$courseid,$domain,$name);
 1351: }
 1352: 
 1353: 1;
 1354: __END__
 1355: 
 1356: 

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