File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.158: download - view: text, annotated - select for diffs
Mon Mar 18 21:51:34 2002 UTC (22 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Minor change to javascript: now use all parameters to window.open.

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

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