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

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

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