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

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

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