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

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

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