File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.178: download - view: text, annotated - select for diffs
Sat Jun 15 18:59:26 2002 UTC (21 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug 532
Expand style_for_target hash by default style file at beginning of xmlparse
call.

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

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