Annotation of loncom/xml/lonxml.pm, revision 1.448

1.2       sakharuk    1: # The LearningOnline Network with CAPA
1.3       sakharuk    2: # XML Parser Module 
1.2       sakharuk    3: #
1.448   ! albertel    4: # $Id: lonxml.pm,v 1.447 2007/05/31 04:15:59 albertel Exp $
1.139     www         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: #
1.316     albertel   39: 
1.2       sakharuk   40: 
1.4       albertel   41: package Apache::lonxml; 
1.33      www        42: use vars 
1.410     albertel   43: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount);
1.1       sakharuk   44: use strict;
1.444     albertel   45: use LONCAPA;
1.167     albertel   46: use HTML::LCParser();
1.161     albertel   47: use HTML::TreeBuilder();
                     48: use HTML::Entities();
                     49: use Safe();
                     50: use Safe::Hole();
                     51: use Math::Cephes();
                     52: use Math::Random();
                     53: use Opcode();
1.271     www        54: use POSIX qw(strftime);
1.339     albertel   55: use Time::HiRes qw( gettimeofday tv_interval );
1.393     albertel   56: use Symbol();
1.266     bowersj2   57: 
1.72      albertel   58: sub register {
1.141     albertel   59:   my ($space,@taglist) = @_;
                     60:   foreach my $temptag (@taglist) {
                     61:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
1.72      albertel   62:   }
                     63: }
                     64: 
1.141     albertel   65: sub deregister {
                     66:   my ($space,@taglist) = @_;
                     67:   foreach my $temptag (@taglist) {
                     68:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
                     69:     if ($tempspace eq $space) {
                     70:       pop(@{ $Apache::lonxml::alltags{$temptag} });
                     71:     }
                     72:   }
1.142     albertel   73:   #&printalltags();
1.141     albertel   74: }
                     75: 
1.46      www        76: use Apache::Constants qw(:common);
1.161     albertel   77: use Apache::lontexconvert();
                     78: use Apache::style();
                     79: use Apache::run();
                     80: use Apache::londefdef();
                     81: use Apache::scripttag();
1.285     www        82: use Apache::languagetags();
1.161     albertel   83: use Apache::edit();
1.266     bowersj2   84: use Apache::inputtags();
                     85: use Apache::outputtags();
1.372     albertel   86: use Apache::lonnet;
1.161     albertel   87: use Apache::File();
                     88: use Apache::loncommon();
1.198     www        89: use Apache::lonfeedback();
1.200     www        90: use Apache::lonmsg();
1.217     matthew    91: use Apache::loncacc();
1.431     www        92: use Apache::lonmaxima();
1.280     www        93: use Apache::lonlocal;
1.79      www        94: 
1.72      albertel   95: #==================================================   Main subroutine: xmlparse  
                     96: #debugging control, to turn on debugging modify the correct handler
                     97: $Apache::lonxml::debug=0;
1.206     albertel   98: 
                     99: # keeps count of the number of warnings and errors generated in a parse
                    100: $warningcount=0;
                    101: $errorcount=0;
1.72      albertel  102: 
                    103: #path to the directory containing the file currently being processed
                    104: @pwd=();
                    105: 
                    106: #these two are used for capturing a subset of the output for later processing,
                    107: #don't touch them directly use &startredirection and &endredirection
                    108: @outputstack = ();
                    109: $redirection = 0;
                    110: 
                    111: #controls wheter the <import> tag actually does
                    112: $import = 1;
                    113: @extlinks=();
                    114: 
                    115: # meta mode is a bit weird only some output is to be turned off
                    116: #<output> tag turns metamode off (defined in londefdef.pm)
                    117: $metamode = 0;
                    118: 
                    119: # turns on and of run::evaluate actually derefencing var refs
                    120: $evaluate = 1;
1.7       albertel  121: 
1.74      albertel  122: # data structure for eidt mode, determines what tags can go into what other tags
                    123: %insertlist=();
1.68      www       124: 
1.99      albertel  125: # stores the list of active tag namespaces
1.76      albertel  126: @namespace=();
                    127: 
1.448   ! albertel  128: # stores all Scrit Vars displays for later showing
        !           129: my @script_var_displays=();
        !           130: 
1.172     albertel  131: # a pointer the the Apache request object
                    132: $Apache::lonxml::request='';
                    133: 
1.216     sakharuk  134: # a problem number counter, and check on ether it is used
1.237     sakharuk  135: $Apache::lonxml::counter=1;
1.204     albertel  136: $Apache::lonxml::counter_changed=0;
                    137: 
1.212     albertel  138: #internal check on whether to look at style defs
                    139: $Apache::lonxml::usestyle=1;
1.260     albertel  140: 
                    141: #locations used to store the parameter string for style substitutions
                    142: $Apache::lonxml::style_values='';
                    143: $Apache::lonxml::style_end_values='';
1.212     albertel  144: 
1.281     albertel  145: #array of ssi calls that need to occur after we are done parsing
                    146: @Apache::lonxml::ssi_info=();
                    147: 
1.282     albertel  148: #should we do the postag variable interpolation
                    149: $Apache::lonxml::post_evaluate=1;
                    150: 
1.295     albertel  151: #a header message to emit in the case of any generated warning or errors
                    152: $Apache::lonxml::warnings_error_header='';
                    153: 
1.396     foxr      154: #  Control whether or not LaTeX symbols should be substituted for their
                    155: #  \ style equivalents...this may be turned off e.g. in an verbatim
                    156: #  environment.
                    157: 
                    158: $Apache::lonxml::substitute_LaTeX_symbols = 1; # Starts out on.
                    159: 
                    160: sub enable_LaTeX_substitutions {
                    161:     $Apache::lonxml::substitute_LaTeX_symbols = 1;
                    162: }
                    163: sub disable_LaTeX_substitutions {
                    164:     $Apache::lonxml::substitute_LaTeX_symbols = 0;
                    165: }
                    166: 
1.68      www       167: sub xmlend {
1.335     sakharuk  168:     my ($target,$parser)=@_;
1.278     www       169:     my $mode='xml';
                    170:     my $status='OPEN';
1.368     albertel  171:     if ($Apache::lonhomework::parsing_a_problem ||
                    172: 	$Apache::lonhomework::parsing_a_task ) {
1.278     www       173: 	$mode='problem';
                    174: 	$status=$Apache::inputtags::status[-1]; 
                    175:     }
1.362     matthew   176:     my $discussion;
1.379     albertel  177:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                    178: 					   ['LONCAPA_INTERNAL_no_discussion']);
1.372     albertel  179:     if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
                    180:         $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
1.362     matthew   181:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
                    182:     }
1.334     sakharuk  183:     if ($target eq 'tex') {
1.335     sakharuk  184: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
1.334     sakharuk  185: 	&Apache::lonxml::newparser($parser,\$discussion,'');
                    186: 	return '';
                    187:     }
1.405     albertel  188: 
1.407     albertel  189:     return $discussion;
1.119     www       190: }
                    191: 
                    192: sub tokeninputfield {
1.120     www       193:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
                    194:     $defhost=~tr/a-z/A-Z/;
1.119     www       195:     return (<<ENDINPUTFIELD)
1.226     albertel  196: <script type="text/javascript">
1.120     www       197:     function updatetoken() {
                    198: 	var comp=new Array;
                    199:         var barcode=unescape(document.tokeninput.barcode.value);
                    200:         comp=barcode.split('*');
                    201:         if (typeof(comp[0])!="undefined") {
                    202: 	    document.tokeninput.codeone.value=comp[0];
                    203: 	}
                    204:         if (typeof(comp[1])!="undefined") {
                    205: 	    document.tokeninput.codetwo.value=comp[1];
                    206: 	}
                    207:         if (typeof(comp[2])!="undefined") {
                    208:             comp[2]=comp[2].toUpperCase();
                    209: 	    document.tokeninput.codethree.value=comp[2];
                    210: 	}
                    211:         document.tokeninput.barcode.value='';
                    212:     }  
                    213: </script>
                    214: <form method="post" name="tokeninput">
1.119     www       215: <table border="2" bgcolor="#FFFFBB">
                    216: <tr><th>DocID Checkin</th></tr>
                    217: <tr><td>
                    218: <table>
                    219: <tr>
                    220: <td>Scan in Barcode</td>
1.120     www       221: <td><input type="text" size="22" name="barcode" 
                    222: onChange="updatetoken()"/></td>
1.119     www       223: </tr>
                    224: <tr><td><i>or</i> Type in DocID</td>
                    225: <td>
                    226: <input type="text" size="5" name="codeone" />
1.120     www       227: <b><font size="+2">*</font></b>
1.119     www       228: <input type="text" size="5" name="codetwo" />
1.120     www       229: <b><font size="+2">*</font></b>
                    230: <input type="text" size="10" name="codethree" value="$defhost" 
                    231: onChange="this.value=this.value.toUpperCase()" />
1.119     www       232: </td></tr>
                    233: </table>
                    234: </td></tr>
                    235: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
                    236: </table>
                    237: </form>
                    238: ENDINPUTFIELD
1.112     www       239: }
                    240: 
1.116     www       241: sub maketoken {
1.118     www       242:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
1.112     www       243:     unless ($symb) {
                    244: 	$symb=&Apache::lonnet::symbread();
                    245:     }
                    246:     unless ($tuname) {
1.372     albertel  247: 	$tuname=$env{'user.name'};
                    248:         $tudom=$env{'user.domain'};
                    249:         $tcrsid=$env{'request.course.id'};
1.112     www       250:     }
1.116     www       251: 
1.118     www       252:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
                    253: }
                    254: 
                    255: sub printtokenheader {
1.133     albertel  256:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
1.116     www       257:     unless ($token) { return ''; }
1.118     www       258: 
1.423     albertel  259:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
1.133     albertel  260:     unless ($tsymb) {
                    261: 	$tsymb=$symb;
1.118     www       262:     }
                    263:     unless ($tuname) {
1.133     albertel  264: 	$tuname=$name;
                    265:         $tudom=$domain;
                    266:         $tcrsid=$courseid;
1.118     www       267:     }
1.114     www       268: 
1.390     albertel  269:     my $plainname=&Apache::loncommon::plainname($tuname,$tudom);
1.114     www       270: 
1.112     www       271:     if ($target eq 'web') {
1.145     www       272:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
1.115     www       273: 	return 
1.221     albertel  274:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
1.284     www       275:                &mt('Checked out for').' '.$plainname.
                    276:                '<br />'.&mt('User').': '.$tuname.' at '.$tudom.
                    277: 	       '<br />'.&mt('ID').': '.$idhash{$tuname}.
                    278: 	       '<br />'.&mt('CourseID').': '.$tcrsid.
1.372     albertel  279: 	       '<br />'.&mt('Course').': '.$env{'course.'.$tcrsid.'.description'}.
1.284     www       280:                '<br />'.&mt('DocID').': '.$token.
                    281:                '<br />'.&mt('Time').': '.&Apache::lonlocal::locallocaltime().'<hr />';
1.112     www       282:     } else {
1.121     albertel  283:         return $token;
1.112     www       284:     }
1.68      www       285: }
                    286: 
1.48      albertel  287: sub printalltags {
                    288:   my $temp;
                    289:   foreach $temp (sort keys %Apache::lonxml::alltags) {
1.141     albertel  290:     &Apache::lonxml::debug("$temp -- ".
                    291: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
1.48      albertel  292:   }
                    293: }
1.31      sakharuk  294: 
1.3       sakharuk  295: sub xmlparse {
1.172     albertel  296:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
1.96      albertel  297: 
1.172     albertel  298:  &setup_globals($request,$target);
1.232     albertel  299:  &Apache::inputtags::initialize_inputtags();
1.370     albertel  300:  &Apache::bridgetask::initialize_bridgetask();
1.232     albertel  301:  &Apache::outputtags::initialize_outputtags();
                    302:  &Apache::edit::initialize_edit();
1.287     albertel  303:  &Apache::londefdef::initialize_londefdef();
1.244     albertel  304: 
1.178     www       305: #
                    306: # do we have a course style file?
                    307: #
                    308: 
1.372     albertel  309:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
1.178     www       310:      my $bodytext=
1.372     albertel  311: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
1.178     www       312:      if ($bodytext) {
1.337     albertel  313: 	 foreach my $file (split(',',$bodytext)) {
                    314: 	     my $location=&Apache::lonnet::filelocation('',$file);
                    315: 	     my $styletext=&Apache::lonnet::getfile($location);
                    316: 	     if ($styletext ne '-1') {
                    317: 		 %style_for_target = (%style_for_target,
                    318: 				      &Apache::style::styleparser($target,$styletext));
                    319: 	     }
                    320: 	 }
                    321:      }
1.372     albertel  322:  } elsif ($env{'construct.style'} && ($env{'request.state'} eq 'construct')) {
                    323:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
1.291     sakharuk  324:      my $styletext=&Apache::lonnet::getfile($location);
                    325:        if ($styletext ne '-1') {
                    326:           %style_for_target = (%style_for_target,
                    327:                           &Apache::style::styleparser($target,$styletext));
                    328:       }
1.178     www       329:  }
1.255     sakharuk  330: #&printalltags();
1.16      albertel  331:  my @pars = ();
1.372     albertel  332:  my $pwd=$env{'request.filename'};
1.23      albertel  333:  $pwd =~ s:/[^/]*$::;
                    334:  &newparser(\@pars,\$content_file_string,$pwd);
1.24      sakharuk  335: 
1.3       sakharuk  336:  my $safeeval = new Safe;
1.40      albertel  337:  my $safehole = new Safe::Hole;
1.82      ng        338:  &init_safespace($target,$safeeval,$safehole,$safeinit);
1.3       sakharuk  339: #-------------------- Redefinition of the target in the case of compound target
                    340: 
                    341:  ($target, my @tenta) = split('&&',$target);
                    342: 
1.150     albertel  343:  my @stack = ();
1.3       sakharuk  344:  my @parstack = ();
1.358     albertel  345:  &initdepth();
                    346:  &init_alarm();
1.101     albertel  347:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
1.394     albertel  348: 				   $safeeval,\%style_for_target,1);
1.255     sakharuk  349: 
1.425     albertel  350:  if (@stack) {
                    351:      &warning("At end of file some tags were still left unclosed, ".
                    352: 	      '<tt>&lt;'.join('&gt;</tt>, <tt>&lt;',reverse(@stack)).
                    353: 	      '&gt;</tt>');
                    354:  }
1.372     albertel  355:  if ($env{'request.uri'}) {
                    356:     &writeallows($env{'request.uri'});
1.125     www       357:  }
1.281     albertel  358:  &do_registered_ssi();
1.204     albertel  359:  if ($Apache::lonxml::counter_changed) { &store_counter() }
1.393     albertel  360: 
                    361:  &clean_safespace($safeeval);
                    362: 
1.448   ! albertel  363:  if (@script_var_displays) {
        !           364:      $finaloutput .= join('',@script_var_displays);
        !           365:      undef(@script_var_displays);
        !           366:  }
        !           367: 
1.372     albertel  368:  if ($env{'form.return_only_error_and_warning_counts'}) {
1.361     www       369:      return "$errorcount:$warningcount";
                    370:  }
1.3       sakharuk  371:  return $finaloutput;
1.106     www       372: }
                    373: 
1.191     albertel  374: sub latex_special_symbols {
1.272     albertel  375:     my ($string,$where)=@_;
1.396     foxr      376:     #
                    377:     #  If e.g. in verbatim mode, then don't substitute.
                    378:     #  but return original string.
                    379:     #
                    380:     if (!($Apache::lonxml::substitute_LaTeX_symbols)) {
                    381: 	return $string;
                    382:     }
1.235     sakharuk  383:     if ($where eq 'header') {
1.414     foxr      384: 	$string =~ s/\\/\$\\backslash\$/g; # \  -> $\backslash$ per LaTex line by line pg  10.
1.311     albertel  385: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
                    386: 	$string=&Apache::lonprintout::character_chart($string);
                    387: 	# any & or # leftover should be safe to just escape
                    388:         $string=~s/([^\\])\&/$1\\\&/g;
                    389:         $string=~s/([^\\])\#/$1\\\#/g;
1.415     foxr      390: 	$string =~ s/_/\\_/g;              # _ -> \_
                    391: 	$string =~ s/\^/\\\^{}/g;          # ^ -> \^{} 
1.229     sakharuk  392:     } else {
1.312     albertel  393: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
1.367     albertel  394: 	$string=~s/\\\%|\%/\\\%/g;
                    395: 	$string=~s/\\{|{/\\{/g;
                    396: 	$string=~s/\\}|}/\\}/g;
1.378     albertel  397: 	$string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
1.367     albertel  398: 	$string=~s/\\\$|\$/\\\$/g;
                    399: 	$string=~s/\\\_|\_/\\\_/g;
1.313     albertel  400:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
1.310     sakharuk  401: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
1.311     albertel  402: 	$string=&Apache::lonprintout::character_chart($string);
                    403: 	# any & or # leftover should be safe to just escape
1.367     albertel  404: 	$string=~s/\\\&|\&/\\\&/g;
                    405: 	$string=~s/\\\#|\#/\\\#/g;
1.332     sakharuk  406:         $string=~s/\|/\$\\mid\$/g;
1.310     sakharuk  407: #single { or } How to escape?
1.229     sakharuk  408:     }
1.272     albertel  409:     return $string;
1.188     sakharuk  410: }
                    411: 
1.101     albertel  412: sub inner_xmlparse {
1.394     albertel  413:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target,$start)=@_;
1.101     albertel  414:   my $finaloutput = '';
                    415:   my $result;
                    416:   my $token;
1.258     albertel  417:   my $dontpop=0;
1.389     albertel  418:   my $startredirection = $Apache::lonxml::redirection;
1.101     albertel  419:   while ( $#$pars > -1 ) {
                    420:     while ($token = $$pars['-1']->get_token) {
1.261     albertel  421:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
1.101     albertel  422: 	if ($metamode<1) {
1.190     albertel  423: 	    my $text=$token->[1];
1.193     albertel  424: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
1.239     sakharuk  425: 		$text = '';
                    426: #		$text = '%'.$text."\n";
1.182     sakharuk  427: 	    }
1.190     albertel  428: 	    $result.=$text;
1.101     albertel  429: 	}
1.261     albertel  430:       } elsif (($token->[0] eq 'D')) {
                    431: 	if ($metamode<1 && $target eq 'web') {
                    432: 	    my $text=$token->[1];
                    433: 	    $result.=$text;
                    434: 	}
1.101     albertel  435:       } elsif ($token->[0] eq 'PI') {
1.261     albertel  436: 	if ($metamode<1 && $target eq 'web') {
1.101     albertel  437: 	  $result=$token->[2];
                    438: 	}
                    439:       } elsif ($token->[0] eq 'S') {
1.140     albertel  440: 	# add tag to stack
1.101     albertel  441: 	push (@$stack,$token->[1]);
                    442: 	# add parameters list to another stack
                    443: 	push (@$parstack,&parstring($token));
1.140     albertel  444: 	&increasedepth($token);
1.212     albertel  445: 	if ($Apache::lonxml::usestyle &&
                    446: 	    exists($$style_for_target{$token->[1]})) {
                    447: 	    $Apache::lonxml::usestyle=0;
                    448: 	    my $string=$$style_for_target{$token->[1]}.
                    449: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
                    450: 	    &Apache::lonxml::newparser($pars,\$string);
1.257     albertel  451: 	    $Apache::lonxml::style_values=$$parstack[-1];
1.259     albertel  452: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
1.101     albertel  453: 	} else {
                    454: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
                    455: 			     $parstack, $pars, $safeeval, $style_for_target);
1.140     albertel  456: 	}
1.101     albertel  457:       } elsif ($token->[0] eq 'E') {
1.212     albertel  458: 	if ($Apache::lonxml::usestyle &&
                    459: 	    exists($$style_for_target{'/'."$token->[1]"})) {
                    460: 	    $Apache::lonxml::usestyle=0;
                    461: 	    my $string=$$style_for_target{'/'.$token->[1]}.
1.258     albertel  462: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
1.212     albertel  463: 	    &Apache::lonxml::newparser($pars,\$string);
1.259     albertel  464: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
                    465: 	    $Apache::lonxml::style_end_values='';
1.258     albertel  466: 	    $dontpop=1;
1.101     albertel  467: 	} else {
1.258     albertel  468: 	    #clear out any tags that didn't end
                    469: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
                    470: 		my $lasttag=$$stack[-1];
1.317     albertel  471: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
1.258     albertel  472: 		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
                    473: 		    last;
                    474: 		} else {
                    475: 		    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' when looking for &lt;/'.$$stack[-1].'&gt; in file');
                    476: 		    &end_tag($stack,$parstack,$token);
                    477: 		}
                    478: 	    }
                    479: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
                    480: 			       $parstack, $pars,$safeeval, $style_for_target);
1.101     albertel  481: 	}
                    482:       } else {
                    483: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
                    484:       }
                    485:       #evaluate variable refs in result
1.282     albertel  486:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
1.257     albertel  487: 	  my $extras;
                    488: 	  if (!$Apache::lonxml::usestyle) {
                    489: 	      $extras=$Apache::lonxml::style_values;
                    490: 	  }
1.101     albertel  491: 	if ( $#$parstack > -1 ) {
1.257     albertel  492: 	  $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
1.101     albertel  493: 	} else {
1.257     albertel  494: 	  $result= &Apache::run::evaluate($result,$safeeval,$extras);
1.101     albertel  495: 	}
1.163     albertel  496:       }
1.282     albertel  497:       $Apache::lonxml::post_evaluate=1;
                    498: 
1.190     albertel  499:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
1.249     albertel  500: 	  #Style file definitions should be correct
1.250     albertel  501: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
1.311     albertel  502: 	      $result=&latex_special_symbols($result);
1.249     albertel  503: 	  }
1.190     albertel  504:       }
                    505: 
1.169     albertel  506:       if ($Apache::lonxml::redirection) {
                    507: 	$Apache::lonxml::outputstack['-1'] .= $result;
                    508:       } else {
                    509: 	$finaloutput.=$result;
                    510:       }
                    511:       $result = '';
                    512: 
1.258     albertel  513:       if ($token->[0] eq 'E' && !$dontpop) {
1.101     albertel  514: 	&end_tag($stack,$parstack,$token);
                    515:       }
1.258     albertel  516:       $dontpop=0;
1.224     albertel  517:     }	
1.212     albertel  518:     if ($#$pars > -1) {
                    519: 	pop @$pars;
                    520: 	pop @Apache::lonxml::pwd;
                    521:     }
1.101     albertel  522:   }
                    523: 
                    524:   # if ($target eq 'meta') {
                    525:   #   $finaloutput.=&endredirection;
                    526:   # }
                    527: 
1.394     albertel  528:   if ( $start && $target eq 'grade') { &endredirection(); }
1.389     albertel  529:   if ( $Apache::lonxml::redirection > $startredirection) {
                    530:       while ($Apache::lonxml::redirection > $startredirection) {
                    531: 	  $finaloutput .= &endredirection();
1.387     albertel  532:       }
                    533:   }
1.101     albertel  534:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
                    535:     $finaloutput=&afterburn($finaloutput);
1.216     sakharuk  536:   }	    
1.101     albertel  537:   return $finaloutput;
                    538: }
1.67      www       539: 
1.318     matthew   540: ## 
                    541: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
                    542: ## otherwise do not call it as we do not know what it is.
                    543: ##
1.7       albertel  544: sub callsub {
1.84      albertel  545:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.7       albertel  546:   my $currentstring='';
1.72      albertel  547:   my $nodefault;
1.7       albertel  548:   {
1.59      albertel  549:     my $sub1;
1.7       albertel  550:     no strict 'refs';
1.68      www       551:     my $tag=$token->[1];
1.236     www       552: # get utterly rid of extended html tags
                    553:     if ($tag=~/^x\-/i) { return ''; }
1.141     albertel  554:     my $space=$Apache::lonxml::alltags{$tag}[-1];
1.68      www       555:     if (!$space) {
1.141     albertel  556:      	$tag=~tr/A-Z/a-z/;
1.68      www       557: 	$sub=~tr/A-Z/a-z/;
1.141     albertel  558: 	$space=$Apache::lonxml::alltags{$tag}[-1]
1.68      www       559:     }
1.97      albertel  560: 
                    561:     my $deleted=0;
                    562:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
                    563:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
                    564: 					     $parstack,$parser,$safeeval,
                    565: 					     $style);
                    566:     }
                    567:     if (!$deleted) {
                    568:       if ($space) {
1.220     albertel  569: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
1.97      albertel  570: 	$sub1="$space\:\:$sub";
                    571: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
                    572: 					     $parstack,$parser,$safeeval,
                    573: 					     $style);
                    574:       } else {
1.318     matthew   575:           if ($target eq 'tex') {
                    576:               # throw away tag name
                    577:               return '';
                    578:           }
1.220     albertel  579: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
1.97      albertel  580: 	if ($metamode <1) {
                    581: 	  if (defined($token->[4]) && ($metamode < 1)) {
                    582: 	    $currentstring = $token->[4];
                    583: 	  } else {
                    584: 	    $currentstring = $token->[2];
                    585: 	  }
1.62      sakharuk  586: 	}
1.7       albertel  587:       }
1.97      albertel  588:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
                    589:       if ($currentstring eq '' && $nodefault eq '') {
                    590: 	if ($target eq 'edit') {
1.220     albertel  591: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
1.97      albertel  592: 	  if ($token->[0] eq 'S') {
                    593: 	    $currentstring = &Apache::edit::tag_start($target,$token);
                    594: 	  } elsif ($token->[0] eq 'E') {
                    595: 	    $currentstring = &Apache::edit::tag_end($target,$token);
                    596: 	  }
1.441     albertel  597: 	}
                    598:       }
                    599:       if ($target eq 'modified' && $nodefault eq '') {
                    600: 	  if ($currentstring eq '') {
                    601: 	      if ($token->[0] eq 'S') {
                    602: 		  $currentstring = $token->[4];
                    603: 	      } elsif ($token->[0] eq 'E') {
                    604: 		  $currentstring = $token->[2];
                    605: 	      } else {
                    606: 		  $currentstring = $token->[2];
                    607: 	      }
                    608: 	  }
1.97      albertel  609: 	  if ($token->[0] eq 'S') {
1.447     albertel  610: 	      $currentstring.=&Apache::edit::handle_insert();
1.210     www       611: 	  } elsif ($token->[0] eq 'E') {
1.447     albertel  612: 	      $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
1.97      albertel  613: 	  }
1.72      albertel  614:       }
1.7       albertel  615:     }
                    616:     use strict 'refs';
                    617:   }
                    618:   return $currentstring;
1.82      ng        619: }
                    620: 
1.96      albertel  621: sub setup_globals {
1.172     albertel  622:   my ($request,$target)=@_;
                    623:   $Apache::lonxml::request=$request;
1.205     www       624:   $errorcount=0;
                    625:   $warningcount=0;
1.207     albertel  626:   $Apache::lonxml::default_homework_loaded=0;
1.212     albertel  627:   $Apache::lonxml::usestyle=1;
1.204     albertel  628:   &init_counter();
1.101     albertel  629:   @Apache::lonxml::pwd=();
1.124     albertel  630:   @Apache::lonxml::extlinks=();
1.448   ! albertel  631:   @script_var_displays=();
1.281     albertel  632:   @Apache::lonxml::ssi_info=();
1.282     albertel  633:   $Apache::lonxml::post_evaluate=1;
1.295     albertel  634:   $Apache::lonxml::warnings_error_header='';
1.397     albertel  635:   $Apache::lonxml::substitute_LaTeX_symbols = 1;
1.96      albertel  636:   if ($target eq 'meta') {
                    637:     $Apache::lonxml::redirection = 0;
                    638:     $Apache::lonxml::metamode = 1;
                    639:     $Apache::lonxml::evaluate = 1;
                    640:     $Apache::lonxml::import = 0;
1.129     albertel  641:   } elsif ($target eq 'answer') {
                    642:     $Apache::lonxml::redirection = 0;
                    643:     $Apache::lonxml::metamode = 1;
                    644:     $Apache::lonxml::evaluate = 1;
                    645:     $Apache::lonxml::import = 1;
1.96      albertel  646:   } elsif ($target eq 'grade') {
1.387     albertel  647:     &startredirection(); #ended in inner_xmlparse on exit
1.96      albertel  648:     $Apache::lonxml::metamode = 0;
                    649:     $Apache::lonxml::evaluate = 1;
                    650:     $Apache::lonxml::import = 1;
                    651:   } elsif ($target eq 'modified') {
                    652:     $Apache::lonxml::redirection = 0;
                    653:     $Apache::lonxml::metamode = 0;
                    654:     $Apache::lonxml::evaluate = 0;
                    655:     $Apache::lonxml::import = 0;
                    656:   } elsif ($target eq 'edit') {
                    657:     $Apache::lonxml::redirection = 0;
                    658:     $Apache::lonxml::metamode = 0;
                    659:     $Apache::lonxml::evaluate = 0;
                    660:     $Apache::lonxml::import = 0;
1.163     albertel  661:   } elsif ($target eq 'analyze') {
                    662:     $Apache::lonxml::redirection = 0;
                    663:     $Apache::lonxml::metamode = 0;
                    664:     $Apache::lonxml::evaluate = 1;
                    665:     $Apache::lonxml::import = 1;
1.96      albertel  666:   } else {
                    667:     $Apache::lonxml::redirection = 0;
                    668:     $Apache::lonxml::metamode = 0;
                    669:     $Apache::lonxml::evaluate = 1;
                    670:     $Apache::lonxml::import = 1;
                    671:   }
                    672: }
                    673: 
1.82      ng        674: sub init_safespace {
                    675:   my ($target,$safeeval,$safehole,$safeinit) = @_;
1.393     albertel  676:   $safeeval->deny_only(':dangerous');
                    677:   $safeeval->reval('use Math::Complex;');
1.383     albertel  678:   $safeeval->permit_only(":default");
1.82      ng        679:   $safeeval->permit("entereval");
                    680:   $safeeval->permit(":base_math");
                    681:   $safeeval->permit("sort");
1.286     albertel  682:   $safeeval->permit("time");
1.371     albertel  683:   $safeeval->deny("rand");
                    684:   $safeeval->deny("srand");
1.82      ng        685:   $safeeval->deny(":base_io");
1.102     albertel  686:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
1.251     albertel  687:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
1.82      ng        688:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
1.324     albertel  689:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
                    690: 		  '&chem_standard_order');
1.369     albertel  691:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
1.324     albertel  692: 
1.431     www       693:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
1.432     www       694:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
1.433     albertel  695:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
                    696: 		  '&maxima_cas_formula_fix');
                    697: 
                    698:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
                    699: 		  '&capa_formula_fix');
1.431     www       700: 
1.82      ng        701:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
                    702:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
                    703:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
                    704:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
                    705:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
                    706:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
                    707:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
                    708:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
                    709:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
                    710:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
                    711:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
                    712:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
                    713:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
                    714:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
                    715:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
                    716:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
                    717:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
                    718:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
                    719:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
1.215     albertel  720:   
                    721:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
                    722:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
                    723:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
                    724:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
                    725:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
                    726:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
                    727:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
                    728:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
                    729:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
                    730:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
                    731:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
                    732:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
                    733:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
                    734:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
                    735:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
                    736:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
                    737:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
                    738:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
                    739:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
                    740:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
                    741:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
                    742:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
                    743: 
1.383     albertel  744:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
                    745:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
                    746: 		  '&Math::Cephes::Matrix::new');
                    747:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
                    748: 		  '&Math::Cephes::Matrix::coef');
                    749:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
                    750: 		  '&Math::Cephes::Matrix::clr');
                    751:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
                    752: 		  '&Math::Cephes::Matrix::add');
                    753:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
                    754: 		  '&Math::Cephes::Matrix::sub');
                    755:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
                    756: 		  '&Math::Cephes::Matrix::mul');
                    757:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
                    758: 		  '&Math::Cephes::Matrix::div');
                    759:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
                    760: 		  '&Math::Cephes::Matrix::inv');
                    761:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
                    762: 		  '&Math::Cephes::Matrix::transp');
                    763:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
                    764: 		  '&Math::Cephes::Matrix::simq');
                    765:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
                    766: 		  '&Math::Cephes::Matrix::mat_to_vec');
                    767:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
                    768: 		  '&Math::Cephes::Matrix::vec_to_mat');
                    769:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
                    770: 		  '&Math::Cephes::Matrix::check');
                    771:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
                    772: 		  '&Math::Cephes::Matrix::check');
                    773: 
1.215     albertel  774: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
                    775: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
                    776: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
                    777: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
                    778: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
                    779: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
                    780: 
1.91      ng        781:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
                    782:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
                    783:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
                    784:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
                    785:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
                    786:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
                    787:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
                    788:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
                    789:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
                    790:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
                    791:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
1.93      ng        792:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
1.91      ng        793:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
                    794:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
                    795:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
                    796:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
                    797:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
                    798:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
                    799:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
                    800:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
                    801:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
1.305     albertel  802:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
1.311     albertel  803:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
1.420     albertel  804:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
                    805:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
1.322     albertel  806:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
1.430     albertel  807: #  use Data::Dumper;
                    808: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
1.82      ng        809: #need to inspect this class of ops
                    810: # $safeeval->deny(":base_orig");
1.331     albertel  811:   $safeeval->permit("require");
1.91      ng        812:   $safeinit .= ';$external::target="'.$target.'";';
1.82      ng        813:   &Apache::run::run($safeinit,$safeeval);
1.373     albertel  814:   &initialize_rndseed($safeeval);
                    815: }
1.303     albertel  816: 
1.393     albertel  817: sub clean_safespace {
                    818:     my ($safeeval) = @_;
                    819:     delete_package_recurse($safeeval->{Root});
                    820: }
                    821: 
                    822: sub delete_package_recurse {
                    823:      my ($package) = @_;
                    824:      my @subp;
                    825:      {
                    826: 	 no strict 'refs';
                    827: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
                    828: 	     if (!defined($val)) { next; }
                    829: 	     local (*ENTRY) = $val;
                    830: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
                    831: 		 $key ne "main::" && $key ne "<none>::")
                    832: 	     {
                    833: 		 my ($p) = $package ne "main" ? "$package\::" : "";
                    834: 		 ($p .= $key) =~ s/::$//;
                    835: 		 push(@subp,$p);
                    836: 	     }
                    837: 	 }
                    838:      }
                    839:      foreach my $p (@subp) {
                    840: 	 delete_package_recurse($p);
                    841:      }
                    842:      Symbol::delete_package($package);
                    843: }
                    844: 
1.373     albertel  845: sub initialize_rndseed {
                    846:     my ($safeeval)=@_;
                    847:     my $rndseed;
1.423     albertel  848:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
1.373     albertel  849:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
                    850:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
                    851:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
                    852:     &Apache::run::run($safeinit,$safeeval);
1.207     albertel  853: }
                    854: 
                    855: sub default_homework_load {
                    856:     my ($safeeval)=@_;
                    857:     &Apache::lonxml::debug('Loading default_homework');
                    858:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
1.241     albertel  859:     if ($default eq -1) {
1.207     albertel  860: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
                    861:     } else {
                    862: 	&Apache::run::run($default,$safeeval);
                    863: 	$Apache::lonxml::default_homework_loaded=1;
                    864:     }
1.17      albertel  865: }
                    866: 
1.358     albertel  867: {
                    868:     my $alarm_depth;
                    869:     sub init_alarm {
                    870: 	alarm(0);
                    871: 	$alarm_depth=0;
                    872:     }
                    873: 
                    874:     sub start_alarm {
                    875: 	if ($alarm_depth<1) {
                    876: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
                    877: 	    if ($old) {
                    878: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
                    879: 	    }
                    880: 	}
                    881: 	$alarm_depth++;
                    882:     }
                    883: 
                    884:     sub end_alarm {
                    885: 	$alarm_depth--;
                    886: 	if ($alarm_depth<1) { alarm(0); }
                    887:     }
                    888: }
1.328     albertel  889: my $metamode_was;
1.55      albertel  890: sub startredirection {
1.328     albertel  891:     if (!$Apache::lonxml::redirection) {
                    892: 	$metamode_was=$Apache::lonxml::metamode;
                    893:     }
                    894:     $Apache::lonxml::metamode=0;
                    895:     $Apache::lonxml::redirection++;
                    896:     push (@Apache::lonxml::outputstack, '');
1.55      albertel  897: }
                    898: 
                    899: sub endredirection {
1.328     albertel  900:     if (!$Apache::lonxml::redirection) {
1.380     www       901: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
1.328     albertel  902: 	return '';
                    903:     }
                    904:     $Apache::lonxml::redirection--;
                    905:     if (!$Apache::lonxml::redirection) {
                    906: 	$Apache::lonxml::metamode=$metamode_was;
                    907:     }
                    908:     pop @Apache::lonxml::outputstack;
1.97      albertel  909: }
                    910: 
                    911: sub end_tag {
                    912:   my ($tagstack,$parstack,$token)=@_;
                    913:   pop(@$tagstack);
                    914:   pop(@$parstack);
                    915:   &decreasedepth($token);
1.55      albertel  916: }
                    917: 
1.17      albertel  918: sub initdepth {
                    919:   @Apache::lonxml::depthcounter=();
1.439     albertel  920:   undef($Apache::lonxml::last_depth_count);
1.17      albertel  921: }
                    922: 
1.438     albertel  923: 
1.339     albertel  924: my @timers;
                    925: my $lasttime;
1.438     albertel  926: # @Apache::lonxml::depthcounter -> count of tags that exist so
                    927: #                                  far at each level
1.439     albertel  928: # $Apache::lonxml::last_depth_count -> when ascending, need to
                    929: # remember the count for the level below the current level (for
                    930: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
1.438     albertel  931: 
1.17      albertel  932: sub increasedepth {
1.19      albertel  933:   my ($token) = @_;
1.439     albertel  934:   push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
                    935:   undef($Apache::lonxml::last_depth_count);
1.340     albertel  936:   my $time;
                    937:   if ($Apache::lonxml::debug eq "1") {
                    938:       push(@timers,[&gettimeofday()]);
                    939:       $time=&tv_interval($lasttime);
                    940:       $lasttime=[&gettimeofday()];
                    941:   }
1.439     albertel  942:   my $spacing='  'x($#Apache::lonxml::depthcounter);
1.438     albertel  943:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
1.439     albertel  944: #  &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
1.54      albertel  945: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
1.17      albertel  946: }
                    947: 
                    948: sub decreasedepth {
1.19      albertel  949:   my ($token) = @_;
1.439     albertel  950:   if (  $#Apache::lonxml::depthcounter == -1) {
                    951:       &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
1.43      albertel  952:   }
1.439     albertel  953:   $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
                    954: 
1.340     albertel  955:   my ($timer,$time);
                    956:   if ($Apache::lonxml::debug eq "1") {
                    957:       $timer=pop(@timers);
                    958:       $time=&tv_interval($lasttime);
                    959:       $lasttime=[&gettimeofday()];
                    960:   }
1.439     albertel  961:   my $spacing='  'x($#Apache::lonxml::depthcounter);
                    962:   $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
                    963: #  &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
1.54      albertel  964: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
1.1       sakharuk  965: }
1.19      albertel  966: 
1.399     albertel  967: sub get_id {
                    968:     my ($parstack,$safeeval)=@_;
                    969:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
                    970:     if ($env{'request.state'} eq 'construct' && $id =~ /(\.|_)/) {
                    971: 	&error(&mt("IDs are not allowed to contain &quot;<tt>_</tt>&quot; or &quot;<tt>.</tt>&quot;"));
                    972:     }
                    973:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
                    974:     return $id;
                    975: }
                    976: 
1.180     albertel  977: sub get_all_text_unbalanced {
1.190     albertel  978: #there is a copy of this in lonpublisher.pm
1.326     albertel  979:     my($tag,$pars)= @_;
                    980:     my $token;
                    981:     my $result='';
                    982:     $tag='<'.$tag.'>';
                    983:     while ($token = $$pars[-1]->get_token) {
                    984: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1.386     albertel  985: 	    if ($token->[0] eq 'T' && $token->[2]) {
1.382     albertel  986: 		$result.='<![CDATA['.$token->[1].']]>';
                    987: 	    } else {
                    988: 		$result.=$token->[1];
                    989: 	    }
1.326     albertel  990: 	} elsif ($token->[0] eq 'PI') {
                    991: 	    $result.=$token->[2];
                    992: 	} elsif ($token->[0] eq 'S') {
                    993: 	    $result.=$token->[4];
                    994: 	} elsif ($token->[0] eq 'E')  {
                    995: 	    $result.=$token->[2];
                    996: 	}
                    997: 	if ($result =~ /\Q$tag\E/is) {
                    998: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
                    999: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
                   1000: 	    #&Apache::lonxml::debug('Result is :'.$1);
                   1001: 	    $redo=$tag.$redo;
                   1002: 	    &Apache::lonxml::newparser($pars,\$redo);
                   1003: 	    last;
                   1004: 	}
                   1005:     }
                   1006:     return $result
1.204     albertel 1007: }
                   1008: 
1.447     albertel 1009: =pod
                   1010: 
                   1011: For bubble grading mode and exam bubble printing mode, the tracking of
                   1012: the current 'bubble line number' is stored in the %env element
                   1013: 'form.counter', and is modifed and handled by the following routines.
                   1014: 
                   1015: The value of it is stored in $Apache:lonxml::counter when live and
                   1016: stored back to env after done.
                   1017: 
                   1018: =item &increment_counter($increment);
                   1019: 
                   1020: Increments the internal counter environment variable a specified amount
                   1021: 
                   1022: Optional Arguments:
                   1023:   $increment - amount to increment by (defaults to 1)
                   1024: 
                   1025: =cut
                   1026: 
1.204     albertel 1027: sub increment_counter {
1.247     albertel 1028:     my ($increment) = @_;
1.289     sakharuk 1029:     if (defined($increment) && $increment gt 0) {
                   1030: 	$Apache::lonxml::counter+=$increment;
                   1031:     } else {
                   1032: 	$Apache::lonxml::counter++;
1.247     albertel 1033:     }
1.289     sakharuk 1034:     $Apache::lonxml::counter_changed=1;
1.204     albertel 1035: }
                   1036: 
1.447     albertel 1037: =pod
                   1038: 
                   1039: =item &init_counter($increment);
                   1040: 
                   1041: Initialize the internal counter environment variable
                   1042: 
                   1043: =cut
                   1044: 
1.204     albertel 1045: sub init_counter {
1.391     albertel 1046:     if ($env{'request.state'} eq 'construct') {
                   1047: 	$Apache::lonxml::counter=1;
                   1048: 	$Apache::lonxml::counter_changed=1;
                   1049:     } elsif (defined($env{'form.counter'})) {
1.372     albertel 1050: 	$Apache::lonxml::counter=$env{'form.counter'};
1.247     albertel 1051: 	$Apache::lonxml::counter_changed=0;
1.237     sakharuk 1052:     } else {
1.204     albertel 1053: 	$Apache::lonxml::counter=1;
1.247     albertel 1054: 	$Apache::lonxml::counter_changed=1;
1.204     albertel 1055:     }
                   1056: }
                   1057: 
                   1058: sub store_counter {
                   1059:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
1.401     albertel 1060:     $Apache::lonxml::counter_changed=0;
1.204     albertel 1061:     return '';
1.180     albertel 1062: }
                   1063: 
1.398     albertel 1064: {
                   1065:     my $state;
                   1066:     sub clear_problem_counter {
                   1067: 	undef($state);
                   1068: 	&Apache::lonnet::delenv('form.counter');
                   1069: 	&Apache::lonxml::init_counter();
                   1070: 	&Apache::lonxml::store_counter();
                   1071:     }
                   1072: 
                   1073:     sub remember_problem_counter {
1.422     albertel 1074: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1.398     albertel 1075: 	$state = $env{'form.counter'};
                   1076:     }
                   1077: 
                   1078:     sub restore_problem_counter {
                   1079: 	if (defined($state)) {
                   1080: 	    &Apache::lonnet::appenv(('form.counter' => $state));
                   1081: 	}
                   1082:     }
1.401     albertel 1083:     sub get_problem_counter {
                   1084: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
1.422     albertel 1085: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1.401     albertel 1086: 	return $env{'form.counter'};
                   1087:     }
1.398     albertel 1088: }
                   1089: 
1.19      albertel 1090: sub get_all_text {
1.270     albertel 1091:     my($tag,$pars,$style)= @_;
                   1092:     my $gotfullstack=1;
                   1093:     if (ref($pars) ne 'ARRAY') {
                   1094: 	$gotfullstack=0;
                   1095: 	$pars=[$pars];
                   1096:     }
                   1097:     if (ref($style) ne 'HASH') {
                   1098: 	$style={};
                   1099:     }
                   1100:     my $depth=0;
                   1101:     my $token;
                   1102:     my $result='';
                   1103:     if ( $tag =~ m:^/: ) { 
                   1104: 	my $tag=substr($tag,1); 
                   1105: 	#&Apache::lonxml::debug("have:$tag:");
                   1106: 	my $top_empty=0;
                   1107: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
                   1108: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
                   1109: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
                   1110: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1.382     albertel 1111: 		    if ($token->[2]) {
                   1112: 			$result.='<![CDATA['.$token->[1].']]>';
                   1113: 		    } else {
                   1114: 			$result.=$token->[1];
                   1115: 		    }
1.270     albertel 1116: 		} elsif ($token->[0] eq 'PI') {
                   1117: 		    $result.=$token->[2];
                   1118: 		} elsif ($token->[0] eq 'S') {
1.316     albertel 1119: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
                   1120: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
                   1121: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1.270     albertel 1122: 		    $result.=$token->[4];
                   1123: 		} elsif ($token->[0] eq 'E')  {
1.316     albertel 1124: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
1.270     albertel 1125: 		    #skip sending back the last end tag
1.283     albertel 1126: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
1.270     albertel 1127: 			my $string=
                   1128: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
                   1129: 				$$style{'/'.$token->[1]}.
                   1130: 				    $token->[2].
                   1131: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
                   1132: 			&Apache::lonxml::newparser($pars,\$string);
                   1133: 			#&Apache::lonxml::debug("reParsing $string");
                   1134: 			next;
                   1135: 		    }
                   1136: 		    if ($depth > -1) {
                   1137: 			$result.=$token->[2];
                   1138: 		    } else {
                   1139: 			$$pars[-1]->unget_token($token);
                   1140: 		    }
                   1141: 		}
                   1142: 	    }
                   1143: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
                   1144: 	    if (($depth >=0) && ($#$pars > 0) ) {
                   1145: 		pop(@$pars);
                   1146: 		pop(@Apache::lonxml::pwd);
                   1147: 	    }
                   1148: 	}
                   1149: 	if ($top_empty && $depth >= 0) {
                   1150: 	    #never found the end tag ran out of text, throw error send back blank
                   1151: 	    &error('Never found end tag for &lt;'.$tag.
                   1152: 		   '&gt; current string <pre>'.
1.314     albertel 1153: 		   &HTML::Entities::encode($result,'<>&"').
1.270     albertel 1154: 		   '</pre>');
                   1155: 	    if ($gotfullstack) {
                   1156: 		my $newstring='</'.$tag.'>'.$result;
                   1157: 		&Apache::lonxml::newparser($pars,\$newstring);
                   1158: 	    }
                   1159: 	    $result='';
                   1160: 	}
                   1161:     } else {
                   1162: 	while ($#$pars > -1) {
                   1163: 	    while ($token = $$pars[-1]->get_token) {
                   1164: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
                   1165: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
                   1166: 		    ($token->[0] eq 'D')) {
1.382     albertel 1167: 		    if ($token->[2]) {
                   1168: 			$result.='<![CDATA['.$token->[1].']]>';
                   1169: 		    } else {
                   1170: 			$result.=$token->[1];
                   1171: 		    }
1.270     albertel 1172: 		} elsif ($token->[0] eq 'PI') {
                   1173: 		    $result.=$token->[2];
                   1174: 		} elsif ($token->[0] eq 'S') {
1.316     albertel 1175: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
1.270     albertel 1176: 			$$pars[-1]->unget_token($token); last;
                   1177: 		    } else {
                   1178: 			$result.=$token->[4];
                   1179: 		    }
1.316     albertel 1180: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
                   1181: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1.270     albertel 1182: 		} elsif ($token->[0] eq 'E')  {
                   1183: 		    $result.=$token->[2];
                   1184: 		}
                   1185: 	    }
                   1186: 	    if (($#$pars > 0) ) {
                   1187: 		pop(@$pars);
                   1188: 		pop(@Apache::lonxml::pwd);
                   1189: 	    } else { last; }
                   1190: 	}
                   1191:     }
                   1192:     #&Apache::lonxml::debug("Exit:$result:");
                   1193:     return $result
1.19      albertel 1194: }
                   1195: 
1.23      albertel 1196: sub newparser {
                   1197:   my ($parser,$contentref,$dir) = @_;
1.167     albertel 1198:   push (@$parser,HTML::LCParser->new($contentref));
1.365     albertel 1199:   $$parser[-1]->xml_mode(1);
                   1200:   $$parser[-1]->marked_sections(1);
1.23      albertel 1201:   if ( $dir eq '' ) {
                   1202:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
                   1203:   } else {
                   1204:     push (@Apache::lonxml::pwd, $dir);
                   1205:   } 
                   1206: }
1.1       sakharuk 1207: 
1.8       albertel 1208: sub parstring {
1.417     albertel 1209:     my ($token) = @_;
                   1210:     my (@vars,@values);
                   1211:     foreach my $attr (@{$token->[3]}) {
                   1212: 	if ($attr!~/\W/) {
                   1213: 	    my $val=$token->[2]->{$attr};
                   1214: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
                   1215: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
                   1216: 	    $val =~ s/(\$)$/\\$1/;
                   1217: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
                   1218: 	    push(@vars,"\$$attr");
                   1219: 	    push(@values,"\"$val\"");
                   1220: 	}
                   1221:     }
                   1222:     my $var_init = 
                   1223: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
                   1224: 	        : '';
                   1225:     return $var_init;
1.8       albertel 1226: }
1.22      albertel 1227: 
1.384     albertel 1228: sub extlink {
                   1229:     my ($res,$exact)=@_;
                   1230:     if (!$exact) {
                   1231: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
                   1232:     }
                   1233:     push(@Apache::lonxml::extlinks,$res)	 
                   1234: }
                   1235: 
1.34      www      1236: sub writeallows {
1.126     www      1237:     unless ($#extlinks>=0) { return; }
1.377     albertel 1238:     my $thisurl = &Apache::lonnet::clutter(shift);
1.372     albertel 1239:     if ($env{'httpref.'.$thisurl}) {
                   1240: 	$thisurl=$env{'httpref.'.$thisurl};
1.111     www      1241:     }
1.34      www      1242:     my $thisdir=$thisurl;
                   1243:     $thisdir=~s/\/[^\/]+$//;
                   1244:     my %httpref=();
1.142     albertel 1245:     foreach (@extlinks) {
1.34      www      1246:        $httpref{'httpref.'.
1.444     albertel 1247:  	        &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
1.142     albertel 1248:     }
1.126     www      1249:     @extlinks=();
1.34      www      1250:     &Apache::lonnet::appenv(%httpref);
                   1251: }
                   1252: 
1.281     albertel 1253: sub register_ssi {
                   1254:     my ($url,%form)=@_;
                   1255:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
                   1256:     return '';
                   1257: }
                   1258: 
                   1259: sub do_registered_ssi {
                   1260:     foreach my $info (@Apache::lonxml::ssi_info) {
                   1261: 	my %form=%{ $info->{'form'}};
                   1262: 	my $url=$info->{'url'};
                   1263: 	&Apache::lonnet::ssi($url,%form);
                   1264:     }
                   1265: }
1.448   ! albertel 1266: 
        !          1267: sub add_script_result {
        !          1268:     my ($display) = @_;
        !          1269:     push(@script_var_displays, $display);
        !          1270: }
        !          1271: 
1.66      www      1272: #
                   1273: # Afterburner handles anchors, highlights and links
                   1274: #
                   1275: sub afterburn {
                   1276:     my $result=shift;
1.154     albertel 1277:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1278: 					    ['highlight','anchor','link']);
1.372     albertel 1279:     if ($env{'form.highlight'}) {
                   1280:        foreach (split(/\,/,$env{'form.highlight'})) {
1.66      www      1281:            my $anchorname=$_;
                   1282: 	   my $matchthis=$anchorname;
                   1283:            $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1284:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
1.142     albertel 1285:        }
1.66      www      1286:     }
1.372     albertel 1287:     if ($env{'form.link'}) {
                   1288:        foreach (split(/\,/,$env{'form.link'})) {
1.66      www      1289:            my ($anchorname,$linkurl)=split(/\>/,$_);
                   1290: 	   my $matchthis=$anchorname;
                   1291:            $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1292:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1.142     albertel 1293:        }
1.66      www      1294:     }
1.372     albertel 1295:     if ($env{'form.anchor'}) {
                   1296:         my $anchorname=$env{'form.anchor'};
1.66      www      1297: 	my $matchthis=$anchorname;
                   1298:         $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1299:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
1.66      www      1300:         $result.=(<<"ENDSCRIPT");
1.226     albertel 1301: <script type="text/javascript">
1.66      www      1302:     document.location.hash='$anchorname';
                   1303: </script>
                   1304: ENDSCRIPT
                   1305:     }
                   1306:     return $result;
                   1307: }
                   1308: 
1.79      www      1309: sub storefile {
                   1310:     my ($file,$contents)=@_;
1.290     albertel 1311:     &Apache::lonnet::correct_line_ends(\$contents);
1.79      www      1312:     if (my $fh=Apache::File->new('>'.$file)) {
                   1313: 	print $fh $contents;
                   1314:         $fh->close();
1.271     www      1315:         return 1;
1.147     albertel 1316:     } else {
1.271     www      1317: 	&warning("Unable to save file $file");
                   1318: 	return 0;
1.79      www      1319:     }
                   1320: }
                   1321: 
1.151     albertel 1322: sub createnewhtml {
1.321     www      1323:     my $title=&mt('Title of document goes here');
                   1324:     my $body=&mt('Body of document goes here');
                   1325:     my $filecontents=(<<SIMPLECONTENT);
1.78      www      1326: <html>
                   1327: <head>
1.321     www      1328: <title>$title</title>
1.78      www      1329: </head>
                   1330: <body bgcolor="#FFFFFF">
1.321     www      1331: $body
1.78      www      1332: </body>
                   1333: </html>
                   1334: SIMPLECONTENT
1.321     www      1335:     return $filecontents;
1.151     albertel 1336: }
                   1337: 
1.274     albertel 1338: sub createnewsty {
                   1339:   my $filecontents=(<<SIMPLECONTENT);
                   1340: <definetag name="">
                   1341:     <render>
                   1342:        <web></web>
                   1343:        <tex></tex>
                   1344:     </render>
                   1345: </definetag>
                   1346: SIMPLECONTENT
                   1347:   return $filecontents;
                   1348: }
                   1349: 
1.147     albertel 1350: 
1.151     albertel 1351: sub inserteditinfo {
1.274     albertel 1352:       my ($result,$filecontents,$filetype)=@_;
1.314     albertel 1353:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
1.147     albertel 1354: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
1.274     albertel 1355:       my $xml_help = '';
1.321     www      1356:       my $initialize='';
1.274     albertel 1357:       if ($filetype eq 'html') {
1.323     www      1358: 	  my $addbuttons=&Apache::lonhtmlcommon::htmlareaaddbuttons();
1.410     albertel 1359: 	  $initialize=&Apache::lonhtmlcommon::spellheader();
1.347     albertel 1360: 	  if (!&Apache::lonhtmlcommon::htmlareablocked() &&
                   1361: 	      &Apache::lonhtmlcommon::htmlareabrowser()) {
                   1362: 	      $initialize.=(<<FULLPAGE);
1.321     www      1363: <script type="text/javascript">
1.323     www      1364: $addbuttons
                   1365: 
1.321     www      1366:     HTMLArea.loadPlugin("FullPage");
                   1367: 
                   1368:     function initDocument() {
1.323     www      1369: 	var editor=new HTMLArea("filecont",config);
1.321     www      1370: 	editor.registerPlugin(FullPage);
                   1371: 	editor.generate();
                   1372:     }
                   1373: </script>
                   1374: FULLPAGE
1.347     albertel 1375:           } else {
                   1376: 	      $initialize.=(<<FULLPAGE);
                   1377: <script type="text/javascript">
                   1378: $addbuttons
                   1379:     function initDocument() {
                   1380:     }
                   1381: </script>
                   1382: FULLPAGE
                   1383: 	  }
1.321     www      1384:           $result=~s/\<body([^\>]*)\>/\<body onload="initDocument()" $1\>/i;
                   1385: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
1.274     albertel 1386:       }
                   1387:       my $cleanbut = '';
1.374     www      1388: 
1.254     albertel 1389:       my $titledisplay=&display_title();
1.426     banghart 1390:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
                   1391: 					 'vi' => 'Save and View',
1.427     banghart 1392: 					 'dv' => 'Discard Edits and View',
1.428     banghart 1393: 					 'un' => 'undo',
1.280     www      1394: 					 'ed' => 'Edit');
1.161     albertel 1395:       my $buttons=(<<BUTTONS);
1.274     albertel 1396: $cleanbut
1.428     banghart 1397: <input type="submit" name="discardview" accesskey="d"  value="$lt{'dv'}" />
                   1398: <input type="submit" name="Undo" accesskey="u"  value="$lt{'un'}" /><hr>
1.304     matthew  1399: <input type="submit" name="savethisfile" accesskey="s"  value="$lt{'st'}" />
                   1400: <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
1.161     albertel 1401: BUTTONS
1.333     www      1402:       $buttons.=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
1.78      www      1403:       my $editfooter=(<<ENDFOOTER);
1.321     www      1404: $initialize
1.78      www      1405: <hr />
                   1406: <a name="editsection" />
1.333     www      1407: <form method="post" name="xmledit">
1.240     albertel 1408: $xml_help
1.280     www      1409: <input type="hidden" name="editmode" value="$lt{'ed'}" />
1.170     www      1410: $buttons<br />
1.366     albertel 1411: <textarea style="width:100%" cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
1.170     www      1412: <br />$buttons
1.78      www      1413: <br />
                   1414: </form>
1.254     albertel 1415: $titledisplay
1.321     www      1416: </body>
1.78      www      1417: ENDFOOTER
1.147     albertel 1418: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
1.78      www      1419:       $result=~s/(\<\/body\>)/$editfooter/is;
                   1420:       return $result;
                   1421: }
                   1422: 
1.152     albertel 1423: sub get_target {
1.372     albertel 1424:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
                   1425:   if ( $env{'request.state'} eq 'published') {
                   1426:     if ( defined($env{'form.grade_target'})
1.152     albertel 1427: 	 && ($viewgrades == 'F' )) {
1.372     albertel 1428:       return ($env{'form.grade_target'});
                   1429:     } elsif (defined($env{'form.grade_target'})) {
                   1430:       if (($env{'form.grade_target'} eq 'web') ||
                   1431: 	  ($env{'form.grade_target'} eq 'tex') ) {
                   1432: 	return $env{'form.grade_target'}
1.153     albertel 1433:       } else {
                   1434: 	return 'web';
                   1435:       }
1.152     albertel 1436:     } else {
                   1437:       return 'web';
                   1438:     }
1.372     albertel 1439:   } elsif ($env{'request.state'} eq 'construct') {
                   1440:     if ( defined($env{'form.grade_target'})) {
                   1441:       return ($env{'form.grade_target'});
1.152     albertel 1442:     } else {
                   1443:       return 'web';
                   1444:     }
                   1445:   } else {
                   1446:     return 'web';
                   1447:   }
                   1448: }
                   1449: 
1.24      sakharuk 1450: sub handler {
1.255     sakharuk 1451:     my $request=shift;
                   1452:     
                   1453:     my $target=&get_target();
                   1454:     
1.372     albertel 1455:     $Apache::lonxml::debug=$env{'user.debug'};
1.255     sakharuk 1456:     
1.364     albertel 1457:     &Apache::loncommon::content_type($request,'text/html');
1.255     sakharuk 1458:     &Apache::loncommon::no_cache($request);
1.372     albertel 1459:     if ($env{'request.state'} eq 'published') {
1.363     albertel 1460: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                   1461: 							      'lastrevisiondate'));
                   1462:     }
1.255     sakharuk 1463:     $request->send_http_header;
                   1464:     
                   1465:     return OK if $request->header_only;
1.68      www      1466: 
                   1467: 
1.255     sakharuk 1468:     my $file=&Apache::lonnet::filelocation("",$request->uri);
1.274     albertel 1469:     my $filetype;
                   1470:     if ($file =~ /\.sty$/) {
                   1471: 	$filetype='sty';
                   1472:     } else {
                   1473: 	$filetype='html';
                   1474:     }
1.78      www      1475: #
                   1476: # Edit action? Save file.
                   1477: #
1.428     banghart 1478:     if (!($env{'request.state'} eq 'published')) {
                   1479: 	if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
1.429     albertel 1480: 	    my $html_file=&Apache::lonnet::getfile($file);
                   1481: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
1.255     sakharuk 1482: 	}
                   1483:     }
                   1484:     my %mystyle;
                   1485:     my $result = '';
                   1486:     my $filecontents=&Apache::lonnet::getfile($file);
                   1487:     if ($filecontents eq -1) {
1.402     albertel 1488: 	my $start_page=&Apache::loncommon::start_page('File Error');
1.412     albertel 1489: 	my $end_page=&Apache::loncommon::end_page();
1.284     www      1490: 	my $fnf=&mt('File not found');
1.255     sakharuk 1491: 	$result=(<<ENDNOTFOUND);
1.402     albertel 1492: $start_page
1.284     www      1493: <b>$fnf: $file</b>
1.402     albertel 1494: $end_page
1.78      www      1495: ENDNOTFOUND
1.343     albertel 1496:         $filecontents='';
1.372     albertel 1497: 	if ($env{'request.state'} ne 'published') {
1.274     albertel 1498: 	    if ($filetype eq 'sty') {
                   1499: 		$filecontents=&createnewsty();
                   1500: 	    } else {
                   1501: 		$filecontents=&createnewhtml();
                   1502: 	    }
1.372     albertel 1503: 	    $env{'form.editmode'}='Edit'; #force edit mode
1.255     sakharuk 1504: 	}
                   1505:     } else {
1.372     albertel 1506: 	unless ($env{'request.state'} eq 'published') {
1.343     albertel 1507: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
1.381     www      1508: 		&Apache::lonxml::error(&mt('This file appears to be a rendering of a LON-CAPA resource. If this is correct, this resource will act very oddly and incorrectly.'));
1.343     albertel 1509: 	    }
1.264     www      1510: #
                   1511: # we are in construction space, see if edit mode forced
1.385     albertel 1512:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1513: 						    ['editmode']);
1.255     sakharuk 1514: 	}
1.427     banghart 1515: 	if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
1.255     sakharuk 1516: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
                   1517: 						'',%mystyle);
1.368     albertel 1518: 	    undef($Apache::lonhomework::parsing_a_task);
1.385     albertel 1519: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1520: 						    ['rawmode']);
1.395     albertel 1521: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
1.255     sakharuk 1522: 	}
1.147     albertel 1523:     }
1.255     sakharuk 1524:     
1.78      www      1525: #
                   1526: # Edit action? Insert editing commands
                   1527: #
1.372     albertel 1528:     unless ($env{'request.state'} eq 'published') {
1.427     banghart 1529: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
                   1530: 	    {
1.255     sakharuk 1531: 	    my $displayfile=$request->uri;
                   1532: 	    $displayfile=~s/^\/[^\/]*//;
1.402     albertel 1533: 	    my %options = ();
                   1534: 	    if ($env{'environment.remote'} ne 'off') {
                   1535: 		$options{'bgcolor'}   = '#FFFFFF';
1.349     albertel 1536: 	    }
1.402     albertel 1537: 	    my $start_page = &Apache::loncommon::start_page(undef,undef,
                   1538: 							    \%options);
                   1539: 	    $result=$start_page.
1.309     albertel 1540: 		&Apache::lonxml::message_location().'<h3>'.
                   1541: 		$displayfile.
1.402     albertel 1542: 		'</h3>'.&Apache::loncommon::end_page();
1.274     albertel 1543: 	    $result=&inserteditinfo($result,$filecontents,$filetype);
1.255     sakharuk 1544: 	}
1.147     albertel 1545:     }
1.402     albertel 1546:     if ($filetype eq 'html') { &writeallows($request->uri); }
1.274     albertel 1547: 	
1.255     sakharuk 1548:     
1.309     albertel 1549:     &Apache::lonxml::add_messages(\$result);
1.255     sakharuk 1550:     $request->print($result);
                   1551:     
                   1552:     return OK;
1.253     albertel 1553: }
                   1554: 
                   1555: sub display_title {
                   1556:     my $result;
1.372     albertel 1557:     if ($env{'request.state'} eq 'construct') {
1.253     albertel 1558: 	my $title=&Apache::lonnet::gettitle();
                   1559: 	if (!defined($title) || $title eq '') {
1.372     albertel 1560: 	    $title = $env{'request.filename'};
1.253     albertel 1561: 	    $title = substr($title, rindex($title, '/') + 1);
                   1562: 	}
                   1563: 	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
                   1564:     }
                   1565:     return $result;
1.24      sakharuk 1566: }
1.147     albertel 1567: 
1.22      albertel 1568: sub debug {
1.298     albertel 1569:     if ($Apache::lonxml::debug eq "1") {
                   1570: 	$|=1;
1.300     albertel 1571: 	my $request=$Apache::lonxml::request;
1.388     albertel 1572: 	if (!$request) {
                   1573: 	    eval { $request=Apache->request; };
                   1574: 	}
                   1575: 	if (!$request) {
                   1576: 	    eval { $request=Apache2::RequestUtil->request; };
                   1577: 	}
1.314     albertel 1578: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
1.346     albertel 1579: 	#&Apache::lonnet::logthis($_[0]);
1.298     albertel 1580:     }
1.22      albertel 1581: }
1.49      albertel 1582: 
1.348     albertel 1583: sub show_error_warn_msg {
1.372     albertel 1584:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
                   1585: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
1.351     albertel 1586: 	return 1;
                   1587:     }
1.348     albertel 1588:     return (($Apache::lonxml::debug eq 1) ||
1.372     albertel 1589: 	    ($env{'request.state'} eq 'construct') ||
1.348     albertel 1590: 	    ($Apache::lonhomework::browse eq 'F'
                   1591: 	     &&
1.372     albertel 1592: 	     $env{'form.show_errors'} eq 'on'));
1.348     albertel 1593: }
                   1594: 
1.22      albertel 1595: sub error {
1.336     albertel 1596:     $errorcount++;
1.348     albertel 1597:     if ( &show_error_warn_msg() ) {
1.336     albertel 1598: 	# If printing in construction space, put the error inside <pre></pre>
                   1599: 	push(@Apache::lonxml::error_messages,
                   1600: 	     $Apache::lonxml::warnings_error_header.
                   1601: 	     "<b>ERROR:</b>".join("<br />\n",@_)."<br />\n");
                   1602: 	$Apache::lonxml::warnings_error_header='';
                   1603:     } else {
                   1604: 	my $errormsg;
                   1605: 	my ($symb)=&Apache::lonnet::symbread();
                   1606: 	if ( !$symb ) {
                   1607: 	    #public or browsers
                   1608: 	    $errormsg=&mt("An error occured while processing this resource. The author has been notified.");
1.403     albertel 1609: 	}
1.413     albertel 1610: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
1.416     albertel 1611: 	my $msg = join('<br />',(@_,"The error occurred on host <tt>$host</tt>"));
1.336     albertel 1612: 	#notify author
1.403     albertel 1613: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
1.336     albertel 1614: 	#notify course
1.372     albertel 1615: 	if ( $symb && $env{'request.course.id'} ) {
1.380     www      1616: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1617: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.440     albertel 1618: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
1.372     albertel 1619: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
1.435     raeburn  1620:             my $baseurl = &Apache::lonnet::clutter($declutter);
1.336     albertel 1621: 	    my @userlist;
                   1622: 	    foreach (keys %users) {
                   1623: 		my ($user,$domain) = split(/:/, $_);
                   1624: 		push(@userlist,"$user\@$domain");
1.380     www      1625: 		my $key=$declutter.'_'.$user.'_'.$domain;
                   1626: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
                   1627: 						      [$key],
                   1628: 						      $cdom,$cnum);
                   1629: 		my $now=time;
                   1630: 		if ($now-$lastnotified{$key}>86400) {
1.434     raeburn  1631:                     my $title = &Apache::lonnet::gettitle($symb);
                   1632:                     my $sentmessage;
1.380     www      1633: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
1.435     raeburn  1634: 		        "Error [$title]",$msg,'',$baseurl,'','',
1.434     raeburn  1635:                         \$sentmessage,$symb,$title,1);
1.380     www      1636: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
                   1637: 					 {$key => $now},
                   1638: 					 $cdom,$cnum);		
                   1639: 		}
1.336     albertel 1640: 	    }
1.372     albertel 1641: 	    if ($env{'request.role.adv'}) {
1.336     albertel 1642: 		$errormsg=&mt("An error occured while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
                   1643: 	    } else {
                   1644: 		$errormsg=&mt("An error occured while processing this resource. The instructor has been notified.");
                   1645: 	    }
                   1646: 	}
                   1647: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
1.52      albertel 1648:     }
1.22      albertel 1649: }
1.49      albertel 1650: 
1.22      albertel 1651: sub warning {
1.295     albertel 1652:     $warningcount++;
1.261     albertel 1653:   
1.372     albertel 1654:     if ($env{'form.grade_target'} ne 'tex') {
1.348     albertel 1655: 	if ( &show_error_warn_msg() ) {
1.309     albertel 1656: 	    push(@Apache::lonxml::warning_messages,
                   1657: 		 $Apache::lonxml::warnings_error_header.
                   1658: 		 "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n");
1.295     albertel 1659: 	    $Apache::lonxml::warnings_error_header='';
                   1660: 	}
                   1661:     }
1.309     albertel 1662: }
                   1663: 
                   1664: sub info {
1.372     albertel 1665:     if ($env{'form.grade_target'} ne 'tex' 
                   1666: 	&& $env{'request.state'} eq 'construct') {
1.309     albertel 1667: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
                   1668:     }
                   1669: }
                   1670: 
                   1671: sub message_location {
                   1672:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
                   1673: }
                   1674: 
                   1675: sub add_messages {
                   1676:     my ($msg)=@_;
                   1677:     my $result=join(' ',
                   1678: 		    @Apache::lonxml::info_messages,
                   1679: 		    @Apache::lonxml::error_messages,
                   1680: 		    @Apache::lonxml::warning_messages);
                   1681:     undef(@Apache::lonxml::info_messages);
                   1682:     undef(@Apache::lonxml::error_messages);
                   1683:     undef(@Apache::lonxml::warning_messages);
                   1684:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
                   1685:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
1.83      albertel 1686: }
                   1687: 
                   1688: sub get_param {
1.213     albertel 1689:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
                   1690:     if ( ! $context ) { $context = -1; }
                   1691:     my $args ='';
                   1692:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 1693:     if ( ! $Apache::lonxml::usestyle ) {
                   1694: 	$args=$Apache::lonxml::style_values.$args;
                   1695:     }
1.213     albertel 1696:     if ( ! $args ) { return undef; }
                   1697:     if ( $case_insensitive ) {
1.417     albertel 1698: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
1.213     albertel 1699: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   1700:                                      $safeeval); #'
                   1701: 	} else {
                   1702: 	    return undef;
                   1703: 	}
                   1704:     } else {
1.417     albertel 1705: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
1.213     albertel 1706: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   1707:                                      $safeeval); #'
                   1708: 	} else {
                   1709: 	    return undef;
                   1710: 	}
                   1711:     }
1.22      albertel 1712: }
                   1713: 
1.132     albertel 1714: sub get_param_var {
1.213     albertel 1715:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1.132     albertel 1716:   if ( ! $context ) { $context = -1; }
                   1717:   my $args ='';
                   1718:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 1719:   if ( ! $Apache::lonxml::usestyle ) {
                   1720:       $args=$Apache::lonxml::style_values.$args;
                   1721:   }
1.230     albertel 1722:   &Apache::lonxml::debug("Args are $args param is $param");
1.213     albertel 1723:   if ($case_insensitive) {
1.419     albertel 1724:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
1.213     albertel 1725: 	  return undef;
                   1726:       }
1.419     albertel 1727:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
1.132     albertel 1728:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
1.230     albertel 1729:   &Apache::lonxml::debug("first run is $value");
1.341     albertel 1730:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
1.230     albertel 1731:       &Apache::lonxml::debug("doing second");
                   1732:       my @result=&Apache::run::run("return $value",$safeeval,1);
                   1733:       if (!defined($result[0])) {
                   1734: 	  return $value
                   1735:       } else {
                   1736: 	  if (wantarray) { return @result; } else { return $result[0]; }
                   1737:       }
1.132     albertel 1738:   } else {
                   1739:     return $value;
                   1740:   }
                   1741: }
                   1742: 
1.438     albertel 1743: sub register_insert_xml {
                   1744:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
                   1745: 				     .'/insertlist.xml');
                   1746:     my ($tagnum,$in_help)=(0,0);
1.442     albertel 1747:     my @alltags;
1.438     albertel 1748:     my $tag;
                   1749:     while (my $token = $parser->get_token()) {
                   1750: 	if ($token->[0] eq 'S') {
                   1751: 	    my $key;
                   1752: 	    if      ($token->[1] eq 'tag') {
                   1753: 		$tag = $token->[2]{'name'};
                   1754: 		$insertlist{"$tagnum.tag"} = $tag;
                   1755: 		$insertlist{"$tag.num"}   = $tagnum;
1.442     albertel 1756: 		push(@alltags,$tag);
1.438     albertel 1757: 	    } elsif ($in_help && $token->[1] eq 'file') {
                   1758: 		$key = $tag.'.helpfile';
                   1759: 	    } elsif ($in_help && $token->[1] eq 'description') {
                   1760: 		$key = $tag.'.helpdesc';
                   1761: 	    } elsif ($token->[1] eq 'description' ||
                   1762: 		     $token->[1] eq 'color'       ||
                   1763: 		     $token->[1] eq 'show'          ) {
                   1764: 		$key = $tag.'.'.$token->[1];
                   1765: 	    } elsif ($token->[1] eq 'insert_sub') {
                   1766: 		$key = $tag.'.function';
                   1767: 	    } elsif ($token->[1] eq 'help') {
                   1768: 		$in_help=1;
                   1769: 	    } elsif ($token->[1] eq 'allow') {
1.442     albertel 1770: 		$key = $tag.'.allow';
1.438     albertel 1771: 	    }
                   1772: 	    if (defined($key)) {
                   1773: 		$insertlist{$key} = $parser->get_text();
                   1774: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
                   1775: 	    }
                   1776: 	} elsif ($token->[0] eq 'E') {
                   1777: 	    if      ($token->[1] eq 'tag') {
                   1778: 		undef($tag);
                   1779: 		$tagnum++;
                   1780: 	    } elsif ($token->[1] eq 'help') {
                   1781: 		undef($in_help);
                   1782: 	    }
                   1783: 	}
                   1784:     }
1.442     albertel 1785:     
                   1786:     # parse the allows and ignore tags set to <show>no</show>
                   1787:     foreach my $tag (@alltags) {	
1.445     albertel 1788:         next if (!exists($insertlist{"$tag.allow"}));
1.442     albertel 1789: 	my $allow =  $insertlist{"$tag.allow"};
                   1790:        	foreach my $element (split(',',$allow)) {
                   1791: 	    $element =~ s/(^\s*|\s*$ )//gx;
1.446     albertel 1792: 	    if (!exists($insertlist{"$element.show"})
                   1793:                 || $insertlist{"$element.show"} ne 'no') {
1.442     albertel 1794: 		push(@{ $insertlist{$tag.'.which'} },$element);
                   1795: 	    }
                   1796: 	}
                   1797:     }
1.438     albertel 1798: }
                   1799: 
                   1800: sub register_insert {
                   1801:     return &register_insert_xml(@_);
                   1802: #    &dump_insertlist('2');
                   1803: }
                   1804: 
                   1805: sub dump_insertlist {
                   1806:     my ($ext) = @_;
                   1807:     open(XML,">/tmp/insertlist.xml.$ext");
                   1808:     print XML ("<insertlist>");
                   1809:     my $i=0;
                   1810: 
                   1811:     while (exists($insertlist{"$i.tag"})) {
                   1812: 	my $tag = $insertlist{"$i.tag"};
                   1813: 	print XML ("
                   1814: \t<tag name=\"$tag\">");
                   1815: 	if (defined($insertlist{"$tag.description"})) {
                   1816: 	    print XML ("
                   1817: \t\t<description>".$insertlist{"$tag.description"}."</description>");
                   1818: 	}
                   1819: 	if (defined($insertlist{"$tag.color"})) {
                   1820: 	    print XML ("
                   1821: \t\t<color>".$insertlist{"$tag.color"}."</color>");
                   1822: 	}
                   1823: 	if (defined($insertlist{"$tag.function"})) {
                   1824: 	    print XML ("
                   1825: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
                   1826: 	}
                   1827: 	if (defined($insertlist{"$tag.show"})
                   1828: 	    && $insertlist{"$tag.show"} ne 'yes') {
                   1829: 	    print XML ("
                   1830: \t\t<show>".$insertlist{"$tag.show"}."</show>");
                   1831: 	}
                   1832: 	if (defined($insertlist{"$tag.helpfile"})) {
                   1833: 	    print XML ("
                   1834: \t\t<help>
                   1835: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
                   1836: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
                   1837: 		print XML ("
                   1838: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
                   1839: 	    }
                   1840: 	    print XML ("
                   1841: \t\t</help>");
                   1842: 	}
                   1843: 	if (defined($insertlist{"$tag.which"})) {
                   1844: 	    print XML ("
                   1845: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
                   1846: 	}
                   1847: 	print XML ("
                   1848: \t</tag>");
                   1849: 	$i++;
                   1850:     }
                   1851:     print XML ("\n</insertlist>\n");
                   1852:     close(XML);
                   1853: }
                   1854: 
1.98      albertel 1855: sub description {
1.437     albertel 1856:     my ($token)=@_;
                   1857:     my $tag = &get_tag($token);
                   1858:     return $insertlist{$tag.'.description'};
1.268     bowersj2 1859: }
                   1860: 
                   1861: # Returns a list containing the help file, and the description
                   1862: sub helpinfo {
1.437     albertel 1863:     my ($token)=@_;
                   1864:     my $tag = &get_tag($token);
                   1865:     return ($insertlist{$tag.'.helpfile'}, $insertlist{$tag.'.helpdesc'});
                   1866: }
                   1867: 
                   1868: sub get_tag {
                   1869:     my ($token)=@_;
                   1870:     my $tagnum;
                   1871:     my $tag=$token->[1];
                   1872:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
                   1873: 	my $testtag = $namespace.'::'.$tag;
                   1874: 	$tagnum = $insertlist{"$testtag.num"};
                   1875: 	last if (defined($tagnum));
                   1876:     }
                   1877:     if (!defined($tagnum)) {
                   1878: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
                   1879:     }
                   1880:     return $insertlist{"$tagnum.tag"};
1.98      albertel 1881: }
1.123     albertel 1882: 
1.1       sakharuk 1883: 1;
                   1884: __END__
1.68      www      1885: 
                   1886: 

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