File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.211: download - view: text, annotated - select for diffs
Wed Nov 6 22:36:08 2002 UTC (21 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixes BUG#918
- allows \n inside <m>

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

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