File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.260: download - view: text, annotated - select for diffs
Thu May 29 18:42:22 2003 UTC (21 years ago) by albertel
Branches: MAIN
CVS tags: version_0_99_1, conference_2003, HEAD
- documenting some globals

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

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