File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.166: download - view: text, annotated - select for diffs
Wed Apr 10 14:46:30 2002 UTC (22 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Changes to make <script> errors print out cleaner.

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

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