File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.184: download - view: text, annotated - select for diffs
Wed Jul 24 20:25:23 2002 UTC (21 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Toward new functionality:
announcements
calendar
chat
course documents

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

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