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

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

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