File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.194: download - view: text, annotated - select for diffs
Tue Sep 10 20:53:36 2002 UTC (21 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Continuing work on simple pages and ad hoc bulletin boards.

Simple pages sort of work, bulletin boards not yet.

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

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