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

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

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