File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.205: download - view: text, annotated - select for diffs
Sun Oct 20 18:42:53 2002 UTC (21 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug 112

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

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