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

1.2       sakharuk    1: # The LearningOnline Network with CAPA
1.3       sakharuk    2: # XML Parser Module 
1.2       sakharuk    3: #
1.531.2.28! raeburn     4: # $Id: lonxml.pm,v 1.531.2.27 2024/07/08 01:05:55 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");
1.531.2.28! raeburn   771:   $safeeval->permit("hintseval");
1.82      ng        772:   $safeeval->permit(":base_math");
                    773:   $safeeval->permit("sort");
1.286     albertel  774:   $safeeval->permit("time");
1.480     www       775:   $safeeval->permit("caller");
1.371     albertel  776:   $safeeval->deny("rand");
                    777:   $safeeval->deny("srand");
1.82      ng        778:   $safeeval->deny(":base_io");
1.102     albertel  779:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
1.251     albertel  780:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
1.82      ng        781:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
1.324     albertel  782:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
                    783: 		  '&chem_standard_order');
1.369     albertel  784:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
1.471     bisitz    785:   $safehole->wrap(\&Apache::response::implicit_multiplication,$safeeval,'&implicit_multiplication');
1.324     albertel  786: 
1.431     www       787:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
1.432     www       788:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
1.433     albertel  789:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
                    790: 		  '&maxima_cas_formula_fix');
                    791: 
1.494     www       792:   $safehole->wrap(\&Apache::lonr::r_eval,$safeeval,'&r_eval');
1.497     www       793:   $safehole->wrap(\&Apache::lonr::Rentry,$safeeval,'&Rentry');
                    794:   $safehole->wrap(\&Apache::lonr::Rarray,$safeeval,'&Rarray');
1.494     www       795:   $safehole->wrap(\&Apache::lonr::r_check,$safeeval,'&r_check');
                    796:   $safehole->wrap(\&Apache::lonr::r_cas_formula_fix,$safeeval,
                    797:                   '&r_cas_formula_fix');
                    798:  
1.433     albertel  799:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
                    800: 		  '&capa_formula_fix');
1.431     www       801: 
1.480     www       802:   $safehole->wrap(\&Apache::lonlocal::locallocaltime,$safeeval,
                    803:                   '&locallocaltime');
                    804: 
1.82      ng        805:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
                    806:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
                    807:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
                    808:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
                    809:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
                    810:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
                    811:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
                    812:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
                    813:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
                    814:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
                    815:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
                    816:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
                    817:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
                    818:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
                    819:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
                    820:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
                    821:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
                    822:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
                    823:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
1.215     albertel  824:   
                    825:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
                    826:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
                    827:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
                    828:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
                    829:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
                    830:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
                    831:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
                    832:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
                    833:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
                    834:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
                    835:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
                    836:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
                    837:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
                    838:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
                    839:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
                    840:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
                    841:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
                    842:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
                    843:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
                    844:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
                    845:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
                    846:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
                    847: 
1.383     albertel  848:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
                    849:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
                    850: 		  '&Math::Cephes::Matrix::new');
                    851:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
                    852: 		  '&Math::Cephes::Matrix::coef');
                    853:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
                    854: 		  '&Math::Cephes::Matrix::clr');
                    855:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
                    856: 		  '&Math::Cephes::Matrix::add');
                    857:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
                    858: 		  '&Math::Cephes::Matrix::sub');
                    859:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
                    860: 		  '&Math::Cephes::Matrix::mul');
                    861:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
                    862: 		  '&Math::Cephes::Matrix::div');
                    863:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
                    864: 		  '&Math::Cephes::Matrix::inv');
                    865:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
                    866: 		  '&Math::Cephes::Matrix::transp');
                    867:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
                    868: 		  '&Math::Cephes::Matrix::simq');
                    869:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
                    870: 		  '&Math::Cephes::Matrix::mat_to_vec');
                    871:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
                    872: 		  '&Math::Cephes::Matrix::vec_to_mat');
                    873:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
                    874: 		  '&Math::Cephes::Matrix::check');
                    875:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
                    876: 		  '&Math::Cephes::Matrix::check');
                    877: 
1.215     albertel  878: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
                    879: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
                    880: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
                    881: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
                    882: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
                    883: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
                    884: 
1.91      ng        885:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
                    886:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
                    887:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
                    888:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
                    889:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
                    890:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
                    891:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
                    892:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
                    893:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
                    894:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
                    895:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
1.93      ng        896:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
1.91      ng        897:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
                    898:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
                    899:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
                    900:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
                    901:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
                    902:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
                    903:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
                    904:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
                    905:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
1.458     albertel  906:   $safehole->wrap(\&Apache::loncommon::languages,$safeeval,'&languages');
1.305     albertel  907:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
1.311     albertel  908:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
1.420     albertel  909:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
                    910:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
1.322     albertel  911:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
1.521     www       912:   $safehole->wrap(\&Apache::functionplotresponse::fpr_val,$safeeval,'&fpr_val');
1.520     www       913:   $safehole->wrap(\&Apache::functionplotresponse::fpr_f,$safeeval,'&fpr_f');
                    914:   $safehole->wrap(\&Apache::functionplotresponse::fpr_dfdx,$safeeval,'&fpr_dfdx');
                    915:   $safehole->wrap(\&Apache::functionplotresponse::fpr_d2fdx2,$safeeval,'&fpr_d2fdx2');
1.524     www       916:   $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorcoords,$safeeval,'&fpr_vectorcoords');
                    917:   $safehole->wrap(\&Apache::functionplotresponse::fpr_objectcoords,$safeeval,'&fpr_objectcoords');
                    918:   $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorlength,$safeeval,'&fpr_vectorlength');
                    919:   $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorangle,$safeeval,'&fpr_vectorangle');
1.531.2.23  raeburn   920:   $safehole->wrap(\&Math::Calculus::Expression::math_calculus_expression,$safeeval,'&math_calculus_expression');
1.531.2.24  raeburn   921:   $safehole->wrap(\&Number::FormatEng::format_eng,$safeeval,'&number_format_eng');
                    922:   $safehole->wrap(\&Number::FormatEng::format_pref,$safeeval,'&number_format_pref');
1.520     www       923: 
1.430     albertel  924: #  use Data::Dumper;
                    925: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
1.82      ng        926: #need to inspect this class of ops
                    927: # $safeeval->deny(":base_orig");
1.331     albertel  928:   $safeeval->permit("require");
1.91      ng        929:   $safeinit .= ';$external::target="'.$target.'";';
1.82      ng        930:   &Apache::run::run($safeinit,$safeeval);
1.531.2.18  raeburn   931:   my $rawrndseed = &initialize_rndseed($safeeval);
                    932:   if ($target eq 'grade') {
                    933:       $Apache::lonhomework::rawrndseed = $rawrndseed;
                    934:   }
1.373     albertel  935: }
1.303     albertel  936: 
1.393     albertel  937: sub clean_safespace {
                    938:     my ($safeeval) = @_;
                    939:     delete_package_recurse($safeeval->{Root});
                    940: }
                    941: 
                    942: sub delete_package_recurse {
                    943:      my ($package) = @_;
                    944:      my @subp;
                    945:      {
                    946: 	 no strict 'refs';
                    947: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
                    948: 	     if (!defined($val)) { next; }
                    949: 	     local (*ENTRY) = $val;
                    950: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
                    951: 		 $key ne "main::" && $key ne "<none>::")
                    952: 	     {
                    953: 		 my ($p) = $package ne "main" ? "$package\::" : "";
                    954: 		 ($p .= $key) =~ s/::$//;
                    955: 		 push(@subp,$p);
                    956: 	     }
                    957: 	 }
                    958:      }
                    959:      foreach my $p (@subp) {
                    960: 	 delete_package_recurse($p);
                    961:      }
                    962:      Symbol::delete_package($package);
                    963: }
                    964: 
1.373     albertel  965: sub initialize_rndseed {
                    966:     my ($safeeval)=@_;
                    967:     my $rndseed;
1.423     albertel  968:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
1.373     albertel  969:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
                    970:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
                    971:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
                    972:     &Apache::run::run($safeinit,$safeeval);
1.531.2.18  raeburn   973:     return $rndseed;
1.207     albertel  974: }
                    975: 
                    976: sub default_homework_load {
                    977:     my ($safeeval)=@_;
                    978:     &Apache::lonxml::debug('Loading default_homework');
1.522     raeburn   979:     my $default=&Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonIncludes'}.
                    980:                                          '/default_homework.lcpm');
1.241     albertel  981:     if ($default eq -1) {
1.207     albertel  982: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
                    983:     } else {
                    984: 	&Apache::run::run($default,$safeeval);
                    985: 	$Apache::lonxml::default_homework_loaded=1;
                    986:     }
1.17      albertel  987: }
                    988: 
1.358     albertel  989: {
                    990:     my $alarm_depth;
                    991:     sub init_alarm {
                    992: 	alarm(0);
                    993: 	$alarm_depth=0;
                    994:     }
                    995: 
                    996:     sub start_alarm {
                    997: 	if ($alarm_depth<1) {
                    998: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
                    999: 	    if ($old) {
                   1000: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
                   1001: 	    }
                   1002: 	}
                   1003: 	$alarm_depth++;
                   1004:     }
                   1005: 
                   1006:     sub end_alarm {
                   1007: 	$alarm_depth--;
                   1008: 	if ($alarm_depth<1) { alarm(0); }
                   1009:     }
                   1010: }
1.328     albertel 1011: my $metamode_was;
1.55      albertel 1012: sub startredirection {
1.328     albertel 1013:     if (!$Apache::lonxml::redirection) {
                   1014: 	$metamode_was=$Apache::lonxml::metamode;
                   1015:     }
                   1016:     $Apache::lonxml::metamode=0;
                   1017:     $Apache::lonxml::redirection++;
                   1018:     push (@Apache::lonxml::outputstack, '');
1.55      albertel 1019: }
                   1020: 
                   1021: sub endredirection {
1.328     albertel 1022:     if (!$Apache::lonxml::redirection) {
1.380     www      1023: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
1.328     albertel 1024: 	return '';
                   1025:     }
                   1026:     $Apache::lonxml::redirection--;
                   1027:     if (!$Apache::lonxml::redirection) {
                   1028: 	$Apache::lonxml::metamode=$metamode_was;
                   1029:     }
                   1030:     pop @Apache::lonxml::outputstack;
1.97      albertel 1031: }
1.459     albertel 1032: sub in_redirection {
                   1033:     return ($Apache::lonxml::redirection > 0)
                   1034: }
1.97      albertel 1035: 
                   1036: sub end_tag {
                   1037:   my ($tagstack,$parstack,$token)=@_;
                   1038:   pop(@$tagstack);
                   1039:   pop(@$parstack);
                   1040:   &decreasedepth($token);
1.55      albertel 1041: }
                   1042: 
1.17      albertel 1043: sub initdepth {
                   1044:   @Apache::lonxml::depthcounter=();
1.439     albertel 1045:   undef($Apache::lonxml::last_depth_count);
1.17      albertel 1046: }
                   1047: 
1.438     albertel 1048: 
1.339     albertel 1049: my @timers;
                   1050: my $lasttime;
1.438     albertel 1051: # @Apache::lonxml::depthcounter -> count of tags that exist so
                   1052: #                                  far at each level
1.439     albertel 1053: # $Apache::lonxml::last_depth_count -> when ascending, need to
                   1054: # remember the count for the level below the current level (for
                   1055: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
1.438     albertel 1056: 
1.17      albertel 1057: sub increasedepth {
1.19      albertel 1058:   my ($token) = @_;
1.439     albertel 1059:   push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
                   1060:   undef($Apache::lonxml::last_depth_count);
1.340     albertel 1061:   my $time;
                   1062:   if ($Apache::lonxml::debug eq "1") {
                   1063:       push(@timers,[&gettimeofday()]);
                   1064:       $time=&tv_interval($lasttime);
                   1065:       $lasttime=[&gettimeofday()];
                   1066:   }
1.439     albertel 1067:   my $spacing='  'x($#Apache::lonxml::depthcounter);
1.438     albertel 1068:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
1.439     albertel 1069: #  &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
1.54      albertel 1070: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
1.17      albertel 1071: }
                   1072: 
                   1073: sub decreasedepth {
1.19      albertel 1074:   my ($token) = @_;
1.439     albertel 1075:   if (  $#Apache::lonxml::depthcounter == -1) {
                   1076:       &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
1.43      albertel 1077:   }
1.439     albertel 1078:   $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
                   1079: 
1.340     albertel 1080:   my ($timer,$time);
                   1081:   if ($Apache::lonxml::debug eq "1") {
                   1082:       $timer=pop(@timers);
                   1083:       $time=&tv_interval($lasttime);
                   1084:       $lasttime=[&gettimeofday()];
                   1085:   }
1.439     albertel 1086:   my $spacing='  'x($#Apache::lonxml::depthcounter);
                   1087:   $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
                   1088: #  &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
1.54      albertel 1089: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
1.1       sakharuk 1090: }
1.19      albertel 1091: 
1.399     albertel 1092: sub get_id {
                   1093:     my ($parstack,$safeeval)=@_;
                   1094:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
1.531.2.24  raeburn  1095:     if ($env{'request.state'} eq 'construct' && $id =~ /([._]|[^\w\s\-])/) { 
1.498     bisitz   1096: 	&error(&mt('ID [_1] contains invalid characters. IDs are only allowed to contain letters, numbers, spaces and -','"<tt>'.$id.'</tt>"'));
1.399     albertel 1097:     }
                   1098:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
                   1099:     return $id;
                   1100: }
                   1101: 
1.180     albertel 1102: sub get_all_text_unbalanced {
1.190     albertel 1103: #there is a copy of this in lonpublisher.pm
1.326     albertel 1104:     my($tag,$pars)= @_;
                   1105:     my $token;
                   1106:     my $result='';
                   1107:     $tag='<'.$tag.'>';
                   1108:     while ($token = $$pars[-1]->get_token) {
                   1109: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1.386     albertel 1110: 	    if ($token->[0] eq 'T' && $token->[2]) {
1.382     albertel 1111: 		$result.='<![CDATA['.$token->[1].']]>';
                   1112: 	    } else {
                   1113: 		$result.=$token->[1];
                   1114: 	    }
1.326     albertel 1115: 	} elsif ($token->[0] eq 'PI') {
                   1116: 	    $result.=$token->[2];
                   1117: 	} elsif ($token->[0] eq 'S') {
                   1118: 	    $result.=$token->[4];
                   1119: 	} elsif ($token->[0] eq 'E')  {
                   1120: 	    $result.=$token->[2];
                   1121: 	}
                   1122: 	if ($result =~ /\Q$tag\E/is) {
                   1123: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
                   1124: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
                   1125: 	    #&Apache::lonxml::debug('Result is :'.$1);
                   1126: 	    $redo=$tag.$redo;
                   1127: 	    &Apache::lonxml::newparser($pars,\$redo);
                   1128: 	    last;
                   1129: 	}
                   1130:     }
                   1131:     return $result
1.462     foxr     1132: 
1.204     albertel 1133: }
                   1134: 
1.462     foxr     1135: #########################################################################
                   1136: #                                                                       #
                   1137: #           bubble line counter management                              #
                   1138: #                                                                       #
                   1139: #########################################################################
                   1140: 
1.447     albertel 1141: =pod
                   1142: 
                   1143: For bubble grading mode and exam bubble printing mode, the tracking of
                   1144: the current 'bubble line number' is stored in the %env element
                   1145: 'form.counter', and is modifed and handled by the following routines.
                   1146: 
                   1147: The value of it is stored in $Apache:lonxml::counter when live and
                   1148: stored back to env after done.
                   1149: 
1.522     raeburn  1150: =item &increment_counter($increment, $part_response);
1.447     albertel 1151: 
                   1152: Increments the internal counter environment variable a specified amount
                   1153: 
                   1154: Optional Arguments:
                   1155:   $increment - amount to increment by (defaults to 1)
1.462     foxr     1156:                Also 1 if the value is negative or zero.
1.467     foxr     1157:   $part_response - A concatenation of the part and response id
                   1158:                    identifying exactly what is being 'answered'.
                   1159: 
1.447     albertel 1160: 
                   1161: =cut
                   1162: 
1.204     albertel 1163: sub increment_counter {
1.467     foxr     1164:     my ($increment, $part_response) = @_;
1.481     raeburn  1165:     if ($env{'form.grade_noincrement'}) { return; }
1.462     foxr     1166:     if (!defined($increment) || $increment le 0) {
                   1167: 	$increment = 1;
                   1168:     }
                   1169:     $Apache::lonxml::counter += $increment;
                   1170: 
1.466     foxr     1171:     # If the caller supplied the response_id parameter, 
1.462     foxr     1172:     # Maintain its counter.. creating if necessary.
                   1173: 
1.470     albertel 1174:     if (defined($part_response)) {
1.467     foxr     1175: 	if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
                   1176: 	    $Apache::lonxml::counters_per_part{$part_response} = 0;
1.462     foxr     1177: 	}
1.467     foxr     1178: 	$Apache::lonxml::counters_per_part{$part_response} += $increment;
                   1179: 	my $new_value = $Apache::lonxml::counters_per_part{$part_response};
1.247     albertel 1180:     }
1.462     foxr     1181: 	
1.289     sakharuk 1182:     $Apache::lonxml::counter_changed=1;
1.204     albertel 1183: }
                   1184: 
1.447     albertel 1185: =pod
                   1186: 
1.461     foxr     1187: =item &init_counter($increment);
1.447     albertel 1188: 
                   1189: Initialize the internal counter environment variable
                   1190: 
                   1191: =cut
                   1192: 
1.204     albertel 1193: sub init_counter {
1.391     albertel 1194:     if ($env{'request.state'} eq 'construct') {
                   1195: 	$Apache::lonxml::counter=1;
                   1196: 	$Apache::lonxml::counter_changed=1;
                   1197:     } elsif (defined($env{'form.counter'})) {
1.372     albertel 1198: 	$Apache::lonxml::counter=$env{'form.counter'};
1.247     albertel 1199: 	$Apache::lonxml::counter_changed=0;
1.237     sakharuk 1200:     } else {
1.204     albertel 1201: 	$Apache::lonxml::counter=1;
1.247     albertel 1202: 	$Apache::lonxml::counter_changed=1;
1.204     albertel 1203:     }
                   1204: }
                   1205: 
                   1206: sub store_counter {
1.474     raeburn  1207:     &Apache::lonnet::appenv({'form.counter' => $Apache::lonxml::counter});
1.401     albertel 1208:     $Apache::lonxml::counter_changed=0;
1.204     albertel 1209:     return '';
1.180     albertel 1210: }
                   1211: 
1.398     albertel 1212: {
                   1213:     my $state;
                   1214:     sub clear_problem_counter {
                   1215: 	undef($state);
                   1216: 	&Apache::lonnet::delenv('form.counter');
                   1217: 	&Apache::lonxml::init_counter();
                   1218: 	&Apache::lonxml::store_counter();
                   1219:     }
                   1220: 
                   1221:     sub remember_problem_counter {
1.422     albertel 1222: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1.398     albertel 1223: 	$state = $env{'form.counter'};
                   1224:     }
                   1225: 
                   1226:     sub restore_problem_counter {
                   1227: 	if (defined($state)) {
1.474     raeburn  1228: 	    &Apache::lonnet::appenv({'form.counter' => $state});
1.398     albertel 1229: 	}
                   1230:     }
1.401     albertel 1231:     sub get_problem_counter {
                   1232: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
1.422     albertel 1233: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1.401     albertel 1234: 	return $env{'form.counter'};
                   1235:     }
1.398     albertel 1236: }
                   1237: 
1.462     foxr     1238: =pod
                   1239: 
1.468     albertel 1240: =item  bubble_lines_for_part(part_response)
1.462     foxr     1241: 
                   1242: Returns the number of lines required to get a response for
1.467     foxr     1243: $part_response (this is just $Apache::lonxml::counters_per_part{$part_response}
1.462     foxr     1244: 
                   1245: =cut
                   1246: 
                   1247: sub bubble_lines_for_part {
1.467     foxr     1248:     my ($part_response) = @_;
1.462     foxr     1249: 
1.467     foxr     1250:     if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
1.462     foxr     1251: 	return 0;
                   1252:     } else {
1.467     foxr     1253: 	return $Apache::lonxml::counters_per_part{$part_response};
1.462     foxr     1254:     }
                   1255: }
                   1256: 
                   1257: =pod
                   1258: 
                   1259: =item clear_bubble_lines_for_part
                   1260: 
                   1261: Clears the hash of bubble lines per part.  If a caller
                   1262: needs to analyze several resources this should be called between
                   1263: resources to reset the hash for each problem being analyzed.
                   1264: 
                   1265: =cut
                   1266: 
                   1267: sub clear_bubble_lines_for_part {
                   1268:     undef(%Apache::lonxml::counters_per_part);
                   1269: }
                   1270: 
                   1271: =pod
                   1272: 
1.468     albertel 1273: =item set_bubble_lines(part_response, value)
1.462     foxr     1274: 
                   1275: If there is a problem part, that for whatever reason
                   1276: requires bubble lines that are not
                   1277: the same as the counter increment, it can call this sub during
                   1278: analysis to set its hash value explicitly.
                   1279: 
                   1280: =cut
                   1281: 
                   1282: sub set_bubble_lines {
1.467     foxr     1283:     my ($part_response, $value) = @_;
1.462     foxr     1284: 
1.467     foxr     1285:     $Apache::lonxml::counters_per_part{$part_response} = $value;
1.462     foxr     1286: }
                   1287: 
                   1288: =pod
                   1289: 
                   1290: =item get_bubble_line_hash
                   1291: 
                   1292: Returns the current bubble line hash.  This is assumed to 
                   1293: be small so we return a copy
                   1294: 
                   1295: 
                   1296: =cut
                   1297: 
                   1298: sub get_bubble_line_hash {
                   1299:     return %Apache::lonxml::counters_per_part;
                   1300: }
                   1301: 
                   1302: 
                   1303: #--------------------------------------------------
                   1304: 
1.19      albertel 1305: sub get_all_text {
1.270     albertel 1306:     my($tag,$pars,$style)= @_;
                   1307:     my $gotfullstack=1;
                   1308:     if (ref($pars) ne 'ARRAY') {
                   1309: 	$gotfullstack=0;
                   1310: 	$pars=[$pars];
                   1311:     }
                   1312:     if (ref($style) ne 'HASH') {
                   1313: 	$style={};
                   1314:     }
                   1315:     my $depth=0;
                   1316:     my $token;
                   1317:     my $result='';
                   1318:     if ( $tag =~ m:^/: ) { 
                   1319: 	my $tag=substr($tag,1); 
                   1320: 	#&Apache::lonxml::debug("have:$tag:");
                   1321: 	my $top_empty=0;
                   1322: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
                   1323: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
                   1324: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
                   1325: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1.382     albertel 1326: 		    if ($token->[2]) {
                   1327: 			$result.='<![CDATA['.$token->[1].']]>';
                   1328: 		    } else {
                   1329: 			$result.=$token->[1];
                   1330: 		    }
1.270     albertel 1331: 		} elsif ($token->[0] eq 'PI') {
                   1332: 		    $result.=$token->[2];
                   1333: 		} elsif ($token->[0] eq 'S') {
1.316     albertel 1334: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
                   1335: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
                   1336: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1.270     albertel 1337: 		    $result.=$token->[4];
                   1338: 		} elsif ($token->[0] eq 'E')  {
1.316     albertel 1339: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
1.270     albertel 1340: 		    #skip sending back the last end tag
1.283     albertel 1341: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
1.270     albertel 1342: 			my $string=
                   1343: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
                   1344: 				$$style{'/'.$token->[1]}.
                   1345: 				    $token->[2].
                   1346: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
                   1347: 			&Apache::lonxml::newparser($pars,\$string);
                   1348: 			#&Apache::lonxml::debug("reParsing $string");
                   1349: 			next;
                   1350: 		    }
                   1351: 		    if ($depth > -1) {
                   1352: 			$result.=$token->[2];
                   1353: 		    } else {
                   1354: 			$$pars[-1]->unget_token($token);
                   1355: 		    }
                   1356: 		}
                   1357: 	    }
                   1358: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
                   1359: 	    if (($depth >=0) && ($#$pars > 0) ) {
                   1360: 		pop(@$pars);
                   1361: 		pop(@Apache::lonxml::pwd);
                   1362: 	    }
                   1363: 	}
                   1364: 	if ($top_empty && $depth >= 0) {
                   1365: 	    #never found the end tag ran out of text, throw error send back blank
                   1366: 	    &error('Never found end tag for &lt;'.$tag.
                   1367: 		   '&gt; current string <pre>'.
1.314     albertel 1368: 		   &HTML::Entities::encode($result,'<>&"').
1.270     albertel 1369: 		   '</pre>');
                   1370: 	    if ($gotfullstack) {
                   1371: 		my $newstring='</'.$tag.'>'.$result;
                   1372: 		&Apache::lonxml::newparser($pars,\$newstring);
                   1373: 	    }
                   1374: 	    $result='';
                   1375: 	}
                   1376:     } else {
                   1377: 	while ($#$pars > -1) {
                   1378: 	    while ($token = $$pars[-1]->get_token) {
                   1379: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
                   1380: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
                   1381: 		    ($token->[0] eq 'D')) {
1.382     albertel 1382: 		    if ($token->[2]) {
                   1383: 			$result.='<![CDATA['.$token->[1].']]>';
                   1384: 		    } else {
                   1385: 			$result.=$token->[1];
                   1386: 		    }
1.270     albertel 1387: 		} elsif ($token->[0] eq 'PI') {
                   1388: 		    $result.=$token->[2];
                   1389: 		} elsif ($token->[0] eq 'S') {
1.316     albertel 1390: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
1.270     albertel 1391: 			$$pars[-1]->unget_token($token); last;
                   1392: 		    } else {
                   1393: 			$result.=$token->[4];
                   1394: 		    }
1.316     albertel 1395: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
                   1396: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1.270     albertel 1397: 		} elsif ($token->[0] eq 'E')  {
                   1398: 		    $result.=$token->[2];
                   1399: 		}
                   1400: 	    }
                   1401: 	    if (($#$pars > 0) ) {
                   1402: 		pop(@$pars);
                   1403: 		pop(@Apache::lonxml::pwd);
                   1404: 	    } else { last; }
                   1405: 	}
                   1406:     }
                   1407:     #&Apache::lonxml::debug("Exit:$result:");
                   1408:     return $result
1.19      albertel 1409: }
                   1410: 
1.23      albertel 1411: sub newparser {
                   1412:   my ($parser,$contentref,$dir) = @_;
1.167     albertel 1413:   push (@$parser,HTML::LCParser->new($contentref));
1.365     albertel 1414:   $$parser[-1]->xml_mode(1);
                   1415:   $$parser[-1]->marked_sections(1);
1.23      albertel 1416:   if ( $dir eq '' ) {
                   1417:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
                   1418:   } else {
                   1419:     push (@Apache::lonxml::pwd, $dir);
                   1420:   } 
                   1421: }
1.1       sakharuk 1422: 
1.8       albertel 1423: sub parstring {
1.417     albertel 1424:     my ($token) = @_;
                   1425:     my (@vars,@values);
                   1426:     foreach my $attr (@{$token->[3]}) {
                   1427: 	if ($attr!~/\W/) {
                   1428: 	    my $val=$token->[2]->{$attr};
                   1429: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
                   1430: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
                   1431: 	    $val =~ s/(\$)$/\\$1/;
                   1432: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
                   1433: 	    push(@vars,"\$$attr");
                   1434: 	    push(@values,"\"$val\"");
                   1435: 	}
                   1436:     }
                   1437:     my $var_init = 
                   1438: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
                   1439: 	        : '';
                   1440:     return $var_init;
1.8       albertel 1441: }
1.22      albertel 1442: 
1.384     albertel 1443: sub extlink {
                   1444:     my ($res,$exact)=@_;
                   1445:     if (!$exact) {
                   1446: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
                   1447:     }
1.531.2.18  raeburn  1448:     push(@Apache::lonxml::extlinks,$res);
1.384     albertel 1449: }
                   1450: 
1.34      www      1451: sub writeallows {
1.126     www      1452:     unless ($#extlinks>=0) { return; }
1.377     albertel 1453:     my $thisurl = &Apache::lonnet::clutter(shift);
1.372     albertel 1454:     if ($env{'httpref.'.$thisurl}) {
                   1455: 	$thisurl=$env{'httpref.'.$thisurl};
1.111     www      1456:     }
1.34      www      1457:     my $thisdir=$thisurl;
                   1458:     $thisdir=~s/\/[^\/]+$//;
                   1459:     my %httpref=();
1.142     albertel 1460:     foreach (@extlinks) {
1.34      www      1461:        $httpref{'httpref.'.
1.444     albertel 1462:  	        &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
1.142     albertel 1463:     }
1.126     www      1464:     @extlinks=();
1.474     raeburn  1465:     &Apache::lonnet::appenv(\%httpref);
1.34      www      1466: }
                   1467: 
1.281     albertel 1468: sub register_ssi {
                   1469:     my ($url,%form)=@_;
                   1470:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
                   1471:     return '';
                   1472: }
                   1473: 
                   1474: sub do_registered_ssi {
                   1475:     foreach my $info (@Apache::lonxml::ssi_info) {
                   1476: 	my %form=%{ $info->{'form'}};
                   1477: 	my $url=$info->{'url'};
                   1478: 	&Apache::lonnet::ssi($url,%form);
                   1479:     }
                   1480: }
1.448     albertel 1481: 
                   1482: sub add_script_result {
                   1483:     my ($display) = @_;
1.531.2.14  raeburn  1484:     if ($display ne '') {
                   1485:         push(@script_var_displays, $display);
                   1486:     }
1.448     albertel 1487: }
                   1488: 
1.66      www      1489: #
                   1490: # Afterburner handles anchors, highlights and links
                   1491: #
                   1492: sub afterburn {
                   1493:     my $result=shift;
1.154     albertel 1494:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1495: 					    ['highlight','anchor','link']);
1.372     albertel 1496:     if ($env{'form.highlight'}) {
                   1497:        foreach (split(/\,/,$env{'form.highlight'})) {
1.66      www      1498:            my $anchorname=$_;
                   1499: 	   my $matchthis=$anchorname;
                   1500:            $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1501:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
1.142     albertel 1502:        }
1.66      www      1503:     }
1.372     albertel 1504:     if ($env{'form.link'}) {
                   1505:        foreach (split(/\,/,$env{'form.link'})) {
1.66      www      1506:            my ($anchorname,$linkurl)=split(/\>/,$_);
                   1507: 	   my $matchthis=$anchorname;
                   1508:            $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1509:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1.142     albertel 1510:        }
1.66      www      1511:     }
1.372     albertel 1512:     if ($env{'form.anchor'}) {
                   1513:         my $anchorname=$env{'form.anchor'};
1.66      www      1514: 	my $matchthis=$anchorname;
                   1515:         $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1516:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
1.66      www      1517:         $result.=(<<"ENDSCRIPT");
1.226     albertel 1518: <script type="text/javascript">
1.66      www      1519:     document.location.hash='$anchorname';
                   1520: </script>
                   1521: ENDSCRIPT
                   1522:     }
                   1523:     return $result;
                   1524: }
                   1525: 
1.79      www      1526: sub storefile {
                   1527:     my ($file,$contents)=@_;
1.290     albertel 1528:     &Apache::lonnet::correct_line_ends(\$contents);
1.79      www      1529:     if (my $fh=Apache::File->new('>'.$file)) {
                   1530: 	print $fh $contents;
                   1531:         $fh->close();
1.271     www      1532:         return 1;
1.147     albertel 1533:     } else {
1.482     bisitz   1534: 	&warning(&mt('Unable to save file [_1]','<tt>'.$file.'</tt>'));
1.271     www      1535: 	return 0;
1.79      www      1536:     }
                   1537: }
                   1538: 
1.151     albertel 1539: sub createnewhtml {
1.321     www      1540:     my $title=&mt('Title of document goes here');
                   1541:     my $body=&mt('Body of document goes here');
                   1542:     my $filecontents=(<<SIMPLECONTENT);
1.78      www      1543: <html>
                   1544: <head>
1.321     www      1545: <title>$title</title>
1.78      www      1546: </head>
                   1547: <body bgcolor="#FFFFFF">
1.321     www      1548: $body
1.78      www      1549: </body>
                   1550: </html>
                   1551: SIMPLECONTENT
1.321     www      1552:     return $filecontents;
1.151     albertel 1553: }
                   1554: 
1.274     albertel 1555: sub createnewsty {
                   1556:   my $filecontents=(<<SIMPLECONTENT);
                   1557: <definetag name="">
                   1558:     <render>
                   1559:        <web></web>
                   1560:        <tex></tex>
                   1561:     </render>
                   1562: </definetag>
                   1563: SIMPLECONTENT
                   1564:   return $filecontents;
                   1565: }
                   1566: 
1.493     raeburn  1567: sub createnewjs {
                   1568:     my $filecontents=(<<SIMPLECONTENT);
                   1569: <script type="text/javascript" language="Javascript">
                   1570: 
                   1571: </script>
                   1572: SIMPLECONTENT
                   1573:     return $filecontents;
                   1574: }
                   1575: 
1.472     www      1576: sub verify_html {
                   1577:     my ($filecontents)=@_;
1.531.2.19  raeburn  1578:     my ($is_html,$is_xml,$is_physnet);
1.516     raeburn  1579:     if ($filecontents =~/(?:\<|\&lt\;)\?xml[^\<]*\?(?:\>|\&gt\;)/is) {
                   1580:         $is_xml = 1;
1.518     raeburn  1581:     } elsif ($filecontents =~/(?:\<|\&lt\;)html(?:\s+[^\<]+|\s*)(?:\>|\&gt\;)/is) {
1.516     raeburn  1582:         $is_html = 1;
1.531.2.19  raeburn  1583:     } elsif ($filecontents =~/(?:\<|\&lt\;)physnet[^\<]*(?:\>|\&gt\;)/is) {
                   1584:         $is_physnet = 1;
1.516     raeburn  1585:     }
1.531.2.19  raeburn  1586:     unless ($is_xml || $is_html || $is_physnet) {
1.516     raeburn  1587:         return &mt('File does not have [_1] or [_2] starting tag','&lt;html&gt;','&lt;?xml ?&gt;');
                   1588:     }
                   1589:     if ($is_html) {
                   1590:         if ($filecontents!~/(?:\<|\&lt\;)\/html(?:\>|\&gt\;)/is) {
                   1591:             return &mt('File does not have [_1] ending tag','&lt;html&gt;');
                   1592:         }
                   1593:         if ($filecontents!~/(?:\<|\&lt\;)(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
                   1594:             return &mt('File does not have [_1] or [_2] starting tag','&lt;body&gt;','&lt;frameset&gt;');
                   1595:         }
                   1596:         if ($filecontents!~/(?:\<|\&lt\;)\/(?:body|frameset)[^\<]*(?:\>|\&gt\;)/is) {
                   1597:             return &mt('File does not have [_1] or [_2] ending tag','&lt;body&gt;','&lt;frameset&gt;');
                   1598:         }
1.472     www      1599:     }
                   1600:     return '';
                   1601: }
1.147     albertel 1602: 
1.478     www      1603: sub renderingoptions {
                   1604:     my %langchoices=('' => '');
                   1605:     foreach (&Apache::loncommon::languageids()) {
                   1606:         if (&Apache::loncommon::supportedlanguagecode($_)) {
                   1607:             $langchoices{&Apache::loncommon::supportedlanguagecode($_)}
                   1608:                        = &Apache::loncommon::plainlanguagedescription($_);
                   1609:         }
                   1610:     }
1.500     raeburn  1611:     my $output;
                   1612:     unless ($env{'form.forceedit'}) {
1.504     bisitz   1613:        $output .=
                   1614:            '<span class="LC_nobreak">'.
1.500     raeburn  1615:            &mt('Language:').' '.
1.504     bisitz   1616:            &Apache::loncommon::select_form(
                   1617:                $env{'form.languages'},
                   1618:                'languages',
1.510     raeburn  1619:                {&Apache::lonlocal::texthash(%langchoices)}).
1.504     bisitz   1620:            '</span>';
1.500     raeburn  1621:     }
1.504     bisitz   1622:     $output .=
                   1623:      ' <span class="LC_nobreak">'.
1.479     bisitz   1624:        &mt('Math Rendering:').' '.
1.504     bisitz   1625:        &Apache::loncommon::select_form(
                   1626:            $env{'form.texengine'},
                   1627:            'texengine',
1.510     raeburn  1628:            {&Apache::lonlocal::texthash
1.504     bisitz   1629:                (''        => '',
                   1630:                 'tth'     => 'tth (TeX to HTML)',
1.531.2.3  raeburn  1631:                 'MathJax' => 'MathJax',
1.510     raeburn  1632:                 'mimetex' => 'mimetex (Convert to Images)')}).
1.504     bisitz   1633:      '</span>';
1.500     raeburn  1634:     return $output;
1.478     www      1635: }
                   1636: 
1.531.2.26  raeburn  1637: sub setmode_javascript {
                   1638:     return <<"ENDSCRIPT";
                   1639: <script type="text/javascript">
                   1640: // <![CDATA[
                   1641: function setmode(form,probmode) {
                   1642:     var initial = form.problemmode.value;
                   1643:     form.problemmode.value = probmode;
                   1644:     form.submit();
                   1645:     form.problemmode.value = initial;
                   1646: }
                   1647: // ]]>
                   1648: </script>
                   1649: ENDSCRIPT
                   1650: }
                   1651: 
1.151     albertel 1652: sub inserteditinfo {
1.531.2.11  raeburn  1653:       my ($filecontents,$filetype,$filename,$symb,$itemtitle,$folderpath,$uri,$action) = @_;
1.314     albertel 1654:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
1.274     albertel 1655:       my $xml_help = '';
1.321     www      1656:       my $initialize='';
1.452     albertel 1657:       my $textarea_id = 'filecont';
1.531.2.16  raeburn  1658:       my ($dragmath_button,$deps_button,$context,$cnum,$cdom,$add_to_onload,
                   1659:           $add_to_onresize,$init_dragmath);
1.456     albertel 1660:       $initialize=&Apache::lonhtmlcommon::spellheader();
1.531.2.16  raeburn  1661:       if ($filetype eq 'html') {
                   1662:           if ($env{'request.course.id'}) {
                   1663:               $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1664:               $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   1665:               if ($uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E}) {
                   1666:                   $context = 'syllabus';
                   1667:               }
                   1668:           }
                   1669:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
                   1670: 	      my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
                   1671:               my %textarea_args = (
                   1672:                                     fullpage => 'true',
                   1673:                                     dragmath => 'math',
                   1674:                                   );
                   1675:               $initialize .= &Apache::lonhtmlcommon::htmlareaselectactive(\%textarea_args);
                   1676:               if ($context eq 'syllabus') {
                   1677:                   $init_dragmath = "editmath_visibility('filecont','none')";
                   1678:               }
                   1679:           }
1.514     raeburn  1680:       }
                   1681:       $initialize .= (<<FULLPAGE);
1.321     www      1682: <script type="text/javascript">
1.514     raeburn  1683: // <![CDATA[
1.321     www      1684:     function initDocument() {
1.463     albertel 1685: 	resize_textarea('$textarea_id','LC_aftertextarea');
1.531.2.16  raeburn  1686:         $init_dragmath
1.321     www      1687:     }
1.514     raeburn  1688: // ]]>
1.321     www      1689: </script>
                   1690: FULLPAGE
1.531.2.8  raeburn  1691:       my $textareaclass;
1.514     raeburn  1692:       if ($filetype eq 'html') {
1.531.2.16  raeburn  1693:           if ($context eq 'syllabus') {
                   1694:               $deps_button = &Apache::lonhtmlcommon::dependencies_button()."\n";
                   1695:               $initialize .=
                   1696:                   &Apache::lonhtmlcommon::dependencycheck_js(undef,&mt('Syllabus'),
                   1697:                                                              $uri,undef,
                   1698:                                                              "/public/$cdom/$cnum/syllabus").
                   1699:                   "\n";
                   1700:               if (&Apache::lonhtmlcommon::htmlareabrowser()) {
                   1701:                   $textareaclass = 'class="LC_richDefaultOn"';
1.531.2.7  raeburn  1702:               }
1.531.2.16  raeburn  1703:           } elsif ($symb || $folderpath) {
                   1704:               $deps_button = &Apache::lonhtmlcommon::dependencies_button()."\n";
                   1705:               $initialize .=
                   1706:                   &Apache::lonhtmlcommon::dependencycheck_js($symb,$itemtitle,
                   1707:                                                              undef,$folderpath,$uri)."\n";
1.530     raeburn  1708:           }
1.514     raeburn  1709:           $dragmath_button = '<span id="math_filecont">'.&Apache::lonhtmlcommon::dragmath_button('filecont',1).'</span>';
                   1710:           $initialize .= "\n".&Apache::lonhtmlcommon::dragmath_js('EditMathPopup');
1.512     raeburn  1711:       }
1.456     albertel 1712:       $add_to_onload = 'initDocument();';
                   1713:       $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
                   1714: 
                   1715:       if ($filetype eq 'html') {
1.531.2.15  raeburn  1716:           my $not_author;
                   1717:           if ($uri =~ m{^/uploaded/}) {
                   1718:               $not_author = 1;
                   1719:           }
                   1720: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet(undef,undef,$not_author);
1.274     albertel 1721:       }
1.452     albertel 1722: 
1.254     albertel 1723:       my $titledisplay=&display_title();
1.426     banghart 1724:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
                   1725: 					 'vi' => 'Save and View',
1.427     banghart 1726: 					 'dv' => 'Discard Edits and View',
1.531.2.27  raeburn  1727: 					 'un' => 'Undo',
1.280     www      1728: 					 'ed' => 'Edit');
1.512     raeburn  1729:       my $spelllink = &Apache::lonhtmlcommon::spelllink('xmledit','filecont');
1.451     albertel 1730:       my $textarea_events = &Apache::edit::element_change_detection();
                   1731:       my $form_events     = &Apache::edit::form_change_detection();
1.491     raeburn  1732:       my $htmlerror;
                   1733:       if ($filetype eq 'html') {
                   1734:           $htmlerror=&verify_html($filecontents);
                   1735:           if ($htmlerror) {
1.531.2.25  raeburn  1736:               $htmlerror=('&nbsp;'x3).' <span class="LC_error">'.$htmlerror.'</span>';
1.491     raeburn  1737:           }
1.501     raeburn  1738:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
1.531.2.8  raeburn  1739:               unless ($textareaclass) {
                   1740:                   $textareaclass = 'class="LC_richDefaultOff"';
                   1741:               }
1.501     raeburn  1742:           }
1.472     www      1743:       }
1.531.2.25  raeburn  1744:       my ($undo,%onclick);
                   1745:       foreach my $item ('discard','undo') {
                   1746:           $onclick{$item} = 'onclick="still_ask=true;setmode(this.form,'."'$item'".')"';
                   1747:       }
                   1748:       foreach my $item ('saveedit','saveview') {
                   1749:           $onclick{$item} = 'onclick="is_submit=true;setmode(this.form,'."'$item'".')"';
                   1750:       }
1.531.2.15  raeburn  1751:       unless ($uri =~ m{^/uploaded/}) {
1.531.2.27  raeburn  1752:           $undo = '<input type="button" name="undo" accesskey="u" value="'.$lt{'un'}.'" '.
1.531.2.25  raeburn  1753:                   $onclick{'undo'}.' />'."\n"; 
1.531.2.15  raeburn  1754:       }
1.531.2.25  raeburn  1755:       $initialize .= &setmode_javascript();
1.78      www      1756:       my $editfooter=(<<ENDFOOTER);
1.321     www      1757: $initialize
1.78      www      1758: <a name="editsection" />
1.531.2.11  raeburn  1759: <form $form_events method="post" name="xmledit" action="$action">
1.531.2.25  raeburn  1760:   <input type="hidden" name="problemmode" value="edit" />
1.470     albertel 1761:   <div class="LC_edit_problem_editxml_header">
                   1762:     <table class="LC_edit_problem_header_title"><tr><td>
                   1763:         $filename
                   1764:       </td><td align="right">
                   1765:         $xml_help
                   1766:       </td></tr>
                   1767:     </table>
1.531.2.22  raeburn  1768:     <div style="float:right">
1.531.2.25  raeburn  1769:       <input type="button" name="savethisfile" accesskey="s" value="$lt{'st'}" $onclick{'saveedit'} />
                   1770:       <input type="button" name="viewmode" accesskey="v" value="$lt{'vi'}" $onclick{'saveview'} />
                   1771:     </div>
                   1772:     <div>
                   1773:       <input type="button" name="discardview" accesskey="d" value="$lt{'dv'}" $onclick{'discard'} />
                   1774:       $undo $deps_button $dragmath_button $htmlerror
1.470     albertel 1775:     </div>
                   1776:   </div>
1.513     raeburn  1777:   <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont" $textareaclass>$filecontents</textarea><br />$spelllink
1.470     albertel 1778:   <div id="LC_aftertextarea">
                   1779:     <br />
                   1780:     $titledisplay
                   1781:   </div>
1.78      www      1782: </form>
                   1783: ENDFOOTER
1.531.2.25  raeburn  1784:       return ($editfooter,$add_to_onload,$add_to_onresize);
1.78      www      1785: }
                   1786: 
1.152     albertel 1787: sub get_target {
1.372     albertel 1788:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
                   1789:   if ( $env{'request.state'} eq 'published') {
                   1790:     if ( defined($env{'form.grade_target'})
1.152     albertel 1791: 	 && ($viewgrades == 'F' )) {
1.372     albertel 1792:       return ($env{'form.grade_target'});
                   1793:     } elsif (defined($env{'form.grade_target'})) {
                   1794:       if (($env{'form.grade_target'} eq 'web') ||
                   1795: 	  ($env{'form.grade_target'} eq 'tex') ) {
                   1796: 	return $env{'form.grade_target'}
1.153     albertel 1797:       } else {
                   1798: 	return 'web';
                   1799:       }
1.152     albertel 1800:     } else {
                   1801:       return 'web';
                   1802:     }
1.372     albertel 1803:   } elsif ($env{'request.state'} eq 'construct') {
                   1804:     if ( defined($env{'form.grade_target'})) {
                   1805:       return ($env{'form.grade_target'});
1.152     albertel 1806:     } else {
                   1807:       return 'web';
                   1808:     }
                   1809:   } else {
                   1810:     return 'web';
                   1811:   }
                   1812: }
                   1813: 
1.24      sakharuk 1814: sub handler {
1.255     sakharuk 1815:     my $request=shift;
1.493     raeburn  1816: 
1.255     sakharuk 1817:     my $target=&get_target();
1.372     albertel 1818:     $Apache::lonxml::debug=$env{'user.debug'};
1.255     sakharuk 1819:     
1.364     albertel 1820:     &Apache::loncommon::content_type($request,'text/html');
1.255     sakharuk 1821:     &Apache::loncommon::no_cache($request);
1.372     albertel 1822:     if ($env{'request.state'} eq 'published') {
1.363     albertel 1823: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                   1824: 							      'lastrevisiondate'));
                   1825:     }
1.499     raeburn  1826:     # Embedded Flash movies from Camtasia served from https will not display in IE
                   1827:     #   if XML config file has expired from cache.    
                   1828:     if ($ENV{'SERVER_PORT'} == 443) {
                   1829:         if ($request->uri =~ /\.xml$/) {
                   1830:             my ($httpbrowser,$clientbrowser) =
                   1831:                 &Apache::loncommon::decode_user_agent($request);
                   1832:             if ($clientbrowser =~ /^explorer$/i) {
                   1833:                 delete $request->headers_out->{'Cache-control'};
                   1834:                 delete $request->headers_out->{'Pragma'};
                   1835:                 my $expiration = time + 60;
                   1836:                 my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime($expiration));
                   1837:                 $request->headers_out->set("Expires" => $date);
                   1838:             }
                   1839:         }
                   1840:     }
1.255     sakharuk 1841:     $request->send_http_header;
                   1842:     
                   1843:     return OK if $request->header_only;
1.68      www      1844: 
                   1845: 
1.255     sakharuk 1846:     my $file=&Apache::lonnet::filelocation("",$request->uri);
1.502     raeburn  1847:     my ($filetype,$breadcrumbtext);
                   1848:     if ($file =~ /\.(sty|css|js|txt|tex)$/) {
1.493     raeburn  1849: 	$filetype=$1;
1.274     albertel 1850:     } else {
                   1851: 	$filetype='html';
                   1852:     }
1.531.2.5  raeburn  1853:     unless ($env{'request.uri'}) {
                   1854:         $env{'request.uri'}=$request->uri;
                   1855:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1856:                                                 ['todocs']);
                   1857:     }
1.531.2.8  raeburn  1858:     my ($cdom,$cnum);
                   1859:     if ($env{'request.course.id'}) {
                   1860:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1861:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   1862:         if ($filetype eq 'html') {
                   1863:             if ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E.+$}) {
                   1864:                 if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
                   1865:                     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1866:                                                             ['editmode']);
                   1867:                 }
                   1868:             }
                   1869:         }
                   1870:     }
1.502     raeburn  1871:     if ($filetype eq 'sty') {
                   1872:         $breadcrumbtext = 'Style File Editor';
                   1873:     } elsif ($filetype eq 'js') {
                   1874:         $breadcrumbtext = 'Javascript Editor';
                   1875:     } elsif ($filetype eq 'css') {
                   1876:         $breadcrumbtext = 'CSS Editor';
                   1877:     } elsif ($filetype eq 'txt') {
                   1878:         $breadcrumbtext = 'Text Editor';
                   1879:     } elsif ($filetype eq 'tex') {
                   1880:         $breadcrumbtext = 'TeX Editor';
                   1881:     } else {
                   1882:         $breadcrumbtext = 'HTML Editor';
                   1883:     }
1.493     raeburn  1884: 
1.78      www      1885: #
                   1886: # Edit action? Save file.
                   1887: #
1.428     banghart 1888:     if (!($env{'request.state'} eq 'published')) {
1.531.2.25  raeburn  1889:         if (($env{'form.problemmode'} eq 'saveedit') ||
                   1890:             ($env{'form.problemmode'} eq 'saveview') ||
                   1891:             ($env{'form.problemmode'} eq 'undo')) {
1.429     albertel 1892: 	    my $html_file=&Apache::lonnet::getfile($file);
                   1893: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
1.531.2.25  raeburn  1894:             if ($env{'form.problemmode'} eq 'saveedit') {
                   1895:                 $env{'form.editmode'}='edit'; #force edit mode
1.472     www      1896:             }
1.255     sakharuk 1897: 	}
                   1898:     }
1.531.2.17  raeburn  1899:     my $inhibit_menu;
1.255     sakharuk 1900:     my %mystyle;
                   1901:     my $result = '';
                   1902:     my $filecontents=&Apache::lonnet::getfile($file);
                   1903:     if ($filecontents eq -1) {
1.402     albertel 1904: 	my $start_page=&Apache::loncommon::start_page('File Error');
1.412     albertel 1905: 	my $end_page=&Apache::loncommon::end_page();
1.495     bisitz   1906:         my $errormsg='<p class="LC_error">'
                   1907:                     .&mt('File not found: [_1]'
                   1908:                         ,'<span class="LC_filename">'.$file.'</span>')
                   1909:                     .'</p>';
1.255     sakharuk 1910: 	$result=(<<ENDNOTFOUND);
1.402     albertel 1911: $start_page
1.495     bisitz   1912: $errormsg
1.402     albertel 1913: $end_page
1.78      www      1914: ENDNOTFOUND
1.343     albertel 1915:         $filecontents='';
1.372     albertel 1916: 	if ($env{'request.state'} ne 'published') {
1.274     albertel 1917: 	    if ($filetype eq 'sty') {
                   1918: 		$filecontents=&createnewsty();
1.493     raeburn  1919:             } elsif ($filetype eq 'js') {
                   1920:                 $filecontents=&createnewjs();
1.502     raeburn  1921:             } elsif ($filetype ne 'css' && $filetype ne 'txt' && $filetype ne 'tex') {
1.274     albertel 1922: 		$filecontents=&createnewhtml();
                   1923: 	    }
1.531.2.25  raeburn  1924: 	    $env{'form.editmode'}='edit'; #force edit mode
1.255     sakharuk 1925: 	}
                   1926:     } else {
1.372     albertel 1927: 	unless ($env{'request.state'} eq 'published') {
1.343     albertel 1928: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
1.381     www      1929: 		&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 1930: 	    }
1.264     www      1931: #
                   1932: # we are in construction space, see if edit mode forced
1.385     albertel 1933:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1934: 						    ['editmode']);
1.255     sakharuk 1935: 	}
1.531.2.25  raeburn  1936:         if ((!$env{'form.editmode'}) ||
                   1937:             ($env{'form.problemmode'} eq 'saveview') ||
                   1938:             ($env{'form.problemmode'} eq 'discard')) {
1.493     raeburn  1939:             if ($filetype eq 'html' || $filetype eq 'sty') {
                   1940: 	        &Apache::structuretags::reset_problem_globals();
                   1941: 	        $result = &Apache::lonxml::xmlparse($request,$target,
                   1942:                                                     $filecontents,'',%mystyle);
1.455     albertel 1943: 	    # .html files may contain <problem> or <Task> need to clean
                   1944: 	    # up if it did
1.493     raeburn  1945: 	        &Apache::structuretags::reset_problem_globals();
                   1946: 	        &Apache::lonhomework::finished_parsing();
1.502     raeburn  1947:             } elsif ($filetype eq 'tex') {
1.503     raeburn  1948:                 $result = &Apache::lontexconvert::converted(\$filecontents,
                   1949:                               $env{'form.texengine'});
                   1950:                 if ($env{'form.return_only_error_and_warning_counts'}) {
                   1951:                     $result = "$errorcount:$warningcount";
                   1952:                 }
1.493     raeburn  1953:             } else {
                   1954:                 $result = $filecontents;
                   1955:             }
1.385     albertel 1956: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1957: 						    ['rawmode']);
1.395     albertel 1958: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
1.531.2.17  raeburn  1959:             if (($env{'request.state'} eq 'construct') &&
                   1960:                 (($filetype eq 'css') || ($filetype eq 'js')) && ($ENV{'HTTP_REFERER'})) {
                   1961:                 if ($ENV{'HTTP_REFERER'} =~ m{^https?\://[^\/]+/priv/$LONCAPA::match_domain/$LONCAPA::match_username/[^\?]+\.(x?html?|swf)(|\?)[^\?]*$}) {
                   1962:                     $inhibit_menu = 1;
                   1963:                 }
                   1964:             }
1.503     raeburn  1965:             if (($filetype ne 'html') && 
1.531.2.17  raeburn  1966:                 (!$env{'form.return_only_error_and_warning_counts'}) &&
                   1967:                 (!$inhibit_menu)) {
1.502     raeburn  1968:                 my $nochgview = 1;
1.495     bisitz   1969:                 my $controls = '';
                   1970:                     if ($env{'request.state'} eq 'construct') {
                   1971:                         $controls = &Apache::loncommon::head_subbox(
                   1972:                                         &Apache::loncommon::CSTR_pageheader()
                   1973:                                        .&Apache::londefdef::edit_controls($nochgview));
                   1974:                     }
1.502     raeburn  1975:                 if ($filetype ne 'sty' && $filetype ne 'tex') {
1.493     raeburn  1976:                     $result =~ s/</&lt;/g;
                   1977:                     $result =~ s/>/&gt;/g;
                   1978:                     $result = '<table class="LC_sty_begin">'.
                   1979:                               '<tr><td><b><pre>'.$result.
                   1980:                               '</pre></b></td></tr></table>';
                   1981:                 }
1.506     droeschl 1982:                 my $brcrum;
                   1983:                 if ($env{'request.state'} eq 'construct') {
1.523     raeburn  1984:                     $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.531.2.9  raeburn  1985:                                 'text' => 'Authoring Space'},
1.506     droeschl 1986:                                {'href' => '',
                   1987:                                 'text' => $breadcrumbtext}];
1.493     raeburn  1988:                 } else {
1.506     droeschl 1989:                     $brcrum = ''; # FIXME: Where are we?
1.493     raeburn  1990:                 }
1.506     droeschl 1991:                 my %options = ('bread_crumbs' => $brcrum,
                   1992:                                'bgcolor'      => '#FFFFFF');
                   1993:                 $result =
                   1994:                     &Apache::loncommon::start_page(undef,undef,\%options)
                   1995:                    .$controls
                   1996:                    .$result
                   1997:                    .&Apache::loncommon::end_page();
1.493     raeburn  1998:             }
1.495     bisitz   1999:         }
1.147     albertel 2000:     }
1.456     albertel 2001: 
1.78      www      2002: #
                   2003: # Edit action? Insert editing commands
                   2004: #
1.531.2.17  raeburn  2005:     unless (($env{'request.state'} eq 'published') || ($inhibit_menu)) {
1.531.2.25  raeburn  2006:         if (($env{'form.editmode'}) &&
                   2007:             (!($env{'form.problemmode'} eq 'saveview')) &&
                   2008:             (!($env{'form.problemmode'} eq 'discard'))) {
1.531.2.11  raeburn  2009:             my ($displayfile,$url,$symb,$itemtitle,$action);
1.530     raeburn  2010: 	    $displayfile=$request->uri;
                   2011:             if ($request->uri =~ m{^/uploaded/}) {
1.531.2.5  raeburn  2012:                 if ($env{'request.course.id'}) {
1.531.2.7  raeburn  2013:                     if ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/supplemental/\E}) {
1.531.2.5  raeburn  2014:                         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2015:                                                                 ['folderpath','title']);
1.531.2.7  raeburn  2016:                     } elsif ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E(.+)$}) {
1.531.2.8  raeburn  2017:                         my $filename = $1;
                   2018:                         if ($1 eq 'loncapa.html') {
                   2019:                             $displayfile = &mt('Syllabus (minimal template)');
1.531.2.11  raeburn  2020:                             $action = $request->uri.'?forceedit=1';
1.531.2.8  raeburn  2021:                         } else {
                   2022:                             $displayfile = &mt('Syllabus file: [_1]',$1);
                   2023:                         }
1.531.2.7  raeburn  2024:                         $itemtitle = &mt('Syllabus');
1.531.2.5  raeburn  2025:                     }
                   2026:                 }
1.531.2.7  raeburn  2027:                 unless ($itemtitle) {
                   2028:                     ($symb,$itemtitle,$displayfile) = 
                   2029:                         &get_courseupload_hierarchy($request->uri,
                   2030:                                                     $env{'form.folderpath'},
                   2031:                                                     $env{'form.title'});
                   2032:                 }
1.529     raeburn  2033:             } else {
                   2034: 	        $displayfile=~s/^\/[^\/]*//;
                   2035:             }
1.470     albertel 2036: 
1.452     albertel 2037: 	    my ($edit_info, $add_to_onload, $add_to_onresize)=
1.531.2.5  raeburn  2038: 		&inserteditinfo($filecontents,$filetype,$displayfile,$symb,
1.531.2.11  raeburn  2039:                                 $itemtitle,$env{'form.folderpath'},$request->uri,$action);
1.450     albertel 2040: 
                   2041: 	    my %options = 
                   2042: 		('add_entries' =>
1.495     bisitz   2043:                    {'onresize'     => $add_to_onresize,
                   2044:                     'onload'       => $add_to_onload,   });
1.500     raeburn  2045:             my $header;
                   2046:             if ($env{'request.state'} eq 'construct') {
                   2047:                 $options{'bread_crumbs'} = [{
1.523     raeburn  2048:                             'href' => &Apache::loncommon::authorspace($request->uri),
1.531.2.9  raeburn  2049:                             'text' => 'Authoring Space'},
1.500     raeburn  2050:                            {'href' => '',
1.502     raeburn  2051:                             'text' => $breadcrumbtext}];
1.500     raeburn  2052:                 $header = &Apache::loncommon::head_subbox(
                   2053:                               &Apache::loncommon::CSTR_pageheader());
                   2054:             }
1.452     albertel 2055: 	    my $js =
                   2056: 		&Apache::edit::js_change_detection().
                   2057: 		&Apache::loncommon::resize_textarea_js();
1.451     albertel 2058: 	    my $start_page = &Apache::loncommon::start_page(undef,$js,
1.402     albertel 2059: 							    \%options);
1.495     bisitz   2060:             $result = $start_page
1.500     raeburn  2061:                      .$header
1.495     bisitz   2062:                      .&Apache::lonxml::message_location()
                   2063:                      .$edit_info
                   2064:                      .&Apache::loncommon::end_page();
1.493     raeburn  2065:         }
1.147     albertel 2066:     }
1.402     albertel 2067:     if ($filetype eq 'html') { &writeallows($request->uri); }
1.501     raeburn  2068: 
1.309     albertel 2069:     &Apache::lonxml::add_messages(\$result);
1.255     sakharuk 2070:     $request->print($result);
                   2071:     
                   2072:     return OK;
1.253     albertel 2073: }
                   2074: 
                   2075: sub display_title {
                   2076:     my $result;
1.372     albertel 2077:     if ($env{'request.state'} eq 'construct') {
1.253     albertel 2078: 	my $title=&Apache::lonnet::gettitle();
                   2079: 	if (!defined($title) || $title eq '') {
1.372     albertel 2080: 	    $title = $env{'request.filename'};
1.253     albertel 2081: 	    $title = substr($title, rindex($title, '/') + 1);
                   2082: 	}
1.476     bisitz   2083:         $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
1.531.2.9  raeburn  2084:                   .&mt('Authoring Space')."';</script>";
1.253     albertel 2085:     }
                   2086:     return $result;
1.24      sakharuk 2087: }
1.147     albertel 2088: 
1.530     raeburn  2089: sub get_courseupload_hierarchy {
1.531.2.5  raeburn  2090:     my ($url,$folderpath,$title) = @_;
1.530     raeburn  2091:     my ($symb,$itemtitle,$displaypath);
                   2092:     if ($env{'request.course.id'}) {
1.531.2.5  raeburn  2093:         if ($folderpath =~ /^supplemental/) {
                   2094:             my @folders = split(/\&/,$folderpath);
                   2095:             my @pathitems;
                   2096:             while (@folders) {
                   2097:                 my $folder=shift(@folders);
                   2098:                 my $foldername=shift(@folders);
1.531.2.6  raeburn  2099:                 $foldername =~ s/\:(\d*)\:(\w*)\:(\w*):(\d*)\:?(\d*)$//;
1.531.2.5  raeburn  2100:                 push(@pathitems,&unescape($foldername));
                   2101:             }
                   2102:             if ($title) {
                   2103:                 push(@pathitems,&unescape($title));
                   2104:             }
                   2105:             $displaypath = join(' &raquo; ',@pathitems);
                   2106:         } else {
                   2107:             $symb = &Apache::lonnet::symbread($url);
                   2108:             my ($map,$id,$res)=&Apache::lonnet::decode_symb($symb);
                   2109:             my $navmap=Apache::lonnavmaps::navmap->new;
                   2110:             if (ref($navmap)) {
                   2111:                 my $res = $navmap->getBySymb($symb);
                   2112:                 if (ref($res)) {
                   2113:                     my @pathitems =
                   2114:                         &Apache::loncommon::get_folder_hierarchy($navmap,$map,1);
                   2115:                     $itemtitle = $res->compTitle();
                   2116:                     push(@pathitems,$itemtitle);
                   2117:                     $displaypath = join(' &raquo; ',@pathitems);
                   2118:                 }
1.530     raeburn  2119:             }
                   2120:         }
                   2121:     }
                   2122:     return ($symb,$itemtitle,$displaypath);
                   2123: }
                   2124: 
1.22      albertel 2125: sub debug {
1.298     albertel 2126:     if ($Apache::lonxml::debug eq "1") {
                   2127: 	$|=1;
1.300     albertel 2128: 	my $request=$Apache::lonxml::request;
1.388     albertel 2129: 	if (!$request) {
                   2130: 	    eval { $request=Apache->request; };
                   2131: 	}
                   2132: 	if (!$request) {
                   2133: 	    eval { $request=Apache2::RequestUtil->request; };
                   2134: 	}
1.314     albertel 2135: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
1.346     albertel 2136: 	#&Apache::lonnet::logthis($_[0]);
1.298     albertel 2137:     }
1.22      albertel 2138: }
1.49      albertel 2139: 
1.348     albertel 2140: sub show_error_warn_msg {
1.522     raeburn  2141:     if (($env{'request.filename'} eq 
                   2142:          $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/lib/templates/simpleproblem.problem') &&
                   2143:         (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
1.351     albertel 2144: 	return 1;
                   2145:     }
1.348     albertel 2146:     return (($Apache::lonxml::debug eq 1) ||
1.372     albertel 2147: 	    ($env{'request.state'} eq 'construct') ||
1.348     albertel 2148: 	    ($Apache::lonhomework::browse eq 'F'
                   2149: 	     &&
1.372     albertel 2150: 	     $env{'form.show_errors'} eq 'on'));
1.348     albertel 2151: }
                   2152: 
1.22      albertel 2153: sub error {
1.454     albertel 2154:     my @errors = @_;
                   2155: 
1.336     albertel 2156:     $errorcount++;
1.454     albertel 2157: 
1.490     www      2158:     $Apache::lonxml::internal_error=1;
                   2159: 
1.454     albertel 2160:     if (defined($Apache::inputtags::part)) {
                   2161: 	if ( @Apache::inputtags::response ) {
                   2162: 	    push(@errors,
                   2163: 		 &mt("This error occurred while processing response [_1] in part [_2]",
                   2164: 		     $Apache::inputtags::response[-1],
                   2165: 		     $Apache::inputtags::part));
                   2166: 	} else {
                   2167: 	    push(@errors,
                   2168: 		 &mt("This error occurred while processing part [_1]",
                   2169: 		     $Apache::inputtags::part));
                   2170: 	}
                   2171:     }
                   2172: 
1.348     albertel 2173:     if ( &show_error_warn_msg() ) {
1.336     albertel 2174: 	# If printing in construction space, put the error inside <pre></pre>
                   2175: 	push(@Apache::lonxml::error_messages,
1.484     bisitz   2176: 	     $Apache::lonxml::warnings_error_header
                   2177:              .'<div class="LC_error">'
                   2178:              .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
                   2179:              ."</div>\n");
1.336     albertel 2180: 	$Apache::lonxml::warnings_error_header='';
                   2181:     } else {
                   2182: 	my $errormsg;
                   2183: 	my ($symb)=&Apache::lonnet::symbread();
                   2184: 	if ( !$symb ) {
                   2185: 	    #public or browsers
1.486     bisitz   2186: 	    $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
1.403     albertel 2187: 	}
1.413     albertel 2188: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
1.476     bisitz   2189: 	push(@errors,
                   2190:         &mt("The error occurred on host [_1]",
                   2191:              "<tt>$host</tt>"));
1.454     albertel 2192: 
                   2193: 	my $msg = join('<br />', @errors);
                   2194: 
1.336     albertel 2195: 	#notify author
1.403     albertel 2196: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
1.336     albertel 2197: 	#notify course
1.372     albertel 2198: 	if ( $symb && $env{'request.course.id'} ) {
1.380     www      2199: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2200: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.440     albertel 2201: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
1.372     albertel 2202: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
1.435     raeburn  2203:             my $baseurl = &Apache::lonnet::clutter($declutter);
1.336     albertel 2204: 	    my @userlist;
1.531.2.18  raeburn  2205: 	    foreach (keys(%users)) {
1.336     albertel 2206: 		my ($user,$domain) = split(/:/, $_);
1.531     bisitz   2207: 		push(@userlist,"$user:$domain");
1.380     www      2208: 		my $key=$declutter.'_'.$user.'_'.$domain;
                   2209: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
                   2210: 						      [$key],
                   2211: 						      $cdom,$cnum);
                   2212: 		my $now=time;
                   2213: 		if ($now-$lastnotified{$key}>86400) {
1.434     raeburn  2214:                     my $title = &Apache::lonnet::gettitle($symb);
                   2215:                     my $sentmessage;
1.380     www      2216: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
1.435     raeburn  2217: 		        "Error [$title]",$msg,'',$baseurl,'','',
1.434     raeburn  2218:                         \$sentmessage,$symb,$title,1);
1.380     www      2219: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
                   2220: 					 {$key => $now},
                   2221: 					 $cdom,$cnum);		
                   2222: 		}
1.336     albertel 2223: 	    }
1.372     albertel 2224: 	    if ($env{'request.role.adv'}) {
1.486     bisitz   2225: 		$errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
1.336     albertel 2226: 	    } else {
1.486     bisitz   2227: 		$errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
1.336     albertel 2228: 	    }
                   2229: 	}
1.531     bisitz   2230: 	push(@Apache::lonxml::error_messages,"<span class=\"LC_warning\">$errormsg</span><br />");
1.52      albertel 2231:     }
1.22      albertel 2232: }
1.49      albertel 2233: 
1.22      albertel 2234: sub warning {
1.295     albertel 2235:     $warningcount++;
1.261     albertel 2236:   
1.372     albertel 2237:     if ($env{'form.grade_target'} ne 'tex') {
1.348     albertel 2238: 	if ( &show_error_warn_msg() ) {
1.309     albertel 2239: 	    push(@Apache::lonxml::warning_messages,
1.484     bisitz   2240: 		 $Apache::lonxml::warnings_error_header
                   2241:                 .'<div class="LC_warning">'
                   2242:                 .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
                   2243:                 ."</div>\n"
1.482     bisitz   2244:                 );
1.295     albertel 2245: 	    $Apache::lonxml::warnings_error_header='';
                   2246: 	}
                   2247:     }
1.309     albertel 2248: }
                   2249: 
                   2250: sub info {
1.372     albertel 2251:     if ($env{'form.grade_target'} ne 'tex' 
                   2252: 	&& $env{'request.state'} eq 'construct') {
1.309     albertel 2253: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
                   2254:     }
                   2255: }
                   2256: 
                   2257: sub message_location {
                   2258:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
                   2259: }
                   2260: 
                   2261: sub add_messages {
                   2262:     my ($msg)=@_;
                   2263:     my $result=join(' ',
                   2264: 		    @Apache::lonxml::info_messages,
                   2265: 		    @Apache::lonxml::error_messages,
                   2266: 		    @Apache::lonxml::warning_messages);
                   2267:     undef(@Apache::lonxml::info_messages);
                   2268:     undef(@Apache::lonxml::error_messages);
                   2269:     undef(@Apache::lonxml::warning_messages);
                   2270:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
                   2271:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
1.83      albertel 2272: }
                   2273: 
                   2274: sub get_param {
1.531.2.5  raeburn  2275:     my ($param,$parstack,$safeeval,$context,$case_insensitive, $noelide) = @_;
1.213     albertel 2276:     if ( ! $context ) { $context = -1; }
                   2277:     my $args ='';
                   2278:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 2279:     if ( ! $Apache::lonxml::usestyle ) {
                   2280: 	$args=$Apache::lonxml::style_values.$args;
                   2281:     }
1.531.2.5  raeburn  2282: 
                   2283:     if ($noelide) {
                   2284:         $args =~ s/'\$/'\\\$/g;
                   2285:     }
                   2286: 
1.213     albertel 2287:     if ( ! $args ) { return undef; }
                   2288:     if ( $case_insensitive ) {
1.417     albertel 2289: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
1.213     albertel 2290: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   2291:                                      $safeeval); #'
                   2292: 	} else {
                   2293: 	    return undef;
                   2294: 	}
                   2295:     } else {
1.417     albertel 2296: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
1.213     albertel 2297: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   2298:                                      $safeeval); #'
                   2299: 	} else {
                   2300: 	    return undef;
                   2301: 	}
                   2302:     }
1.22      albertel 2303: }
                   2304: 
1.132     albertel 2305: sub get_param_var {
1.213     albertel 2306:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1.132     albertel 2307:   if ( ! $context ) { $context = -1; }
                   2308:   my $args ='';
                   2309:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 2310:   if ( ! $Apache::lonxml::usestyle ) {
                   2311:       $args=$Apache::lonxml::style_values.$args;
                   2312:   }
1.230     albertel 2313:   &Apache::lonxml::debug("Args are $args param is $param");
1.213     albertel 2314:   if ($case_insensitive) {
1.419     albertel 2315:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
1.213     albertel 2316: 	  return undef;
                   2317:       }
1.419     albertel 2318:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
1.132     albertel 2319:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
1.230     albertel 2320:   &Apache::lonxml::debug("first run is $value");
1.341     albertel 2321:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
1.230     albertel 2322:       &Apache::lonxml::debug("doing second");
                   2323:       my @result=&Apache::run::run("return $value",$safeeval,1);
                   2324:       if (!defined($result[0])) {
                   2325: 	  return $value
                   2326:       } else {
                   2327: 	  if (wantarray) { return @result; } else { return $result[0]; }
                   2328:       }
1.132     albertel 2329:   } else {
                   2330:     return $value;
                   2331:   }
                   2332: }
                   2333: 
1.438     albertel 2334: sub register_insert_xml {
                   2335:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
                   2336: 				     .'/insertlist.xml');
                   2337:     my ($tagnum,$in_help)=(0,0);
1.442     albertel 2338:     my @alltags;
1.438     albertel 2339:     my $tag;
                   2340:     while (my $token = $parser->get_token()) {
                   2341: 	if ($token->[0] eq 'S') {
                   2342: 	    my $key;
1.525     raeburn  2343: 	    if ($token->[1] eq 'tag') {
1.438     albertel 2344: 		$tag = $token->[2]{'name'};
1.525     raeburn  2345:                 if (defined($tag)) {
                   2346: 		    $insertlist{$tagnum.'.tag'} = $tag;
                   2347: 		    $insertlist{$tag.'.num'}   = $tagnum;
                   2348: 		    push(@alltags,$tag);
                   2349:                 }
1.438     albertel 2350: 	    } elsif ($in_help && $token->[1] eq 'file') {
                   2351: 		$key = $tag.'.helpfile';
                   2352: 	    } elsif ($in_help && $token->[1] eq 'description') {
                   2353: 		$key = $tag.'.helpdesc';
                   2354: 	    } elsif ($token->[1] eq 'description' ||
                   2355: 		     $token->[1] eq 'color'       ||
                   2356: 		     $token->[1] eq 'show'          ) {
                   2357: 		$key = $tag.'.'.$token->[1];
                   2358: 	    } elsif ($token->[1] eq 'insert_sub') {
                   2359: 		$key = $tag.'.function';
                   2360: 	    } elsif ($token->[1] eq 'help') {
                   2361: 		$in_help=1;
                   2362: 	    } elsif ($token->[1] eq 'allow') {
1.442     albertel 2363: 		$key = $tag.'.allow';
1.438     albertel 2364: 	    }
                   2365: 	    if (defined($key)) {
                   2366: 		$insertlist{$key} = $parser->get_text();
                   2367: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
                   2368: 	    }
                   2369: 	} elsif ($token->[0] eq 'E') {
                   2370: 	    if      ($token->[1] eq 'tag') {
                   2371: 		undef($tag);
                   2372: 		$tagnum++;
                   2373: 	    } elsif ($token->[1] eq 'help') {
                   2374: 		undef($in_help);
                   2375: 	    }
                   2376: 	}
                   2377:     }
1.442     albertel 2378:     
                   2379:     # parse the allows and ignore tags set to <show>no</show>
                   2380:     foreach my $tag (@alltags) {	
1.519     raeburn  2381:         next if (!exists($insertlist{$tag.'.allow'}));
                   2382: 	my $allow =  $insertlist{$tag.'.allow'};
1.442     albertel 2383:        	foreach my $element (split(',',$allow)) {
                   2384: 	    $element =~ s/(^\s*|\s*$ )//gx;
1.519     raeburn  2385: 	    if (!exists($insertlist{$element.'.show'})
                   2386:                 || $insertlist{$element.'.show'} ne 'no') {
1.442     albertel 2387: 		push(@{ $insertlist{$tag.'.which'} },$element);
                   2388: 	    }
                   2389: 	}
                   2390:     }
1.438     albertel 2391: }
                   2392: 
                   2393: sub register_insert {
                   2394:     return &register_insert_xml(@_);
                   2395: #    &dump_insertlist('2');
                   2396: }
                   2397: 
                   2398: sub dump_insertlist {
                   2399:     my ($ext) = @_;
1.531.2.24  raeburn  2400:     open(XML,">","/tmp/insertlist.xml.$ext");
1.438     albertel 2401:     print XML ("<insertlist>");
                   2402:     my $i=0;
                   2403: 
                   2404:     while (exists($insertlist{"$i.tag"})) {
                   2405: 	my $tag = $insertlist{"$i.tag"};
                   2406: 	print XML ("
                   2407: \t<tag name=\"$tag\">");
                   2408: 	if (defined($insertlist{"$tag.description"})) {
                   2409: 	    print XML ("
                   2410: \t\t<description>".$insertlist{"$tag.description"}."</description>");
                   2411: 	}
                   2412: 	if (defined($insertlist{"$tag.color"})) {
                   2413: 	    print XML ("
                   2414: \t\t<color>".$insertlist{"$tag.color"}."</color>");
                   2415: 	}
                   2416: 	if (defined($insertlist{"$tag.function"})) {
                   2417: 	    print XML ("
                   2418: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
                   2419: 	}
                   2420: 	if (defined($insertlist{"$tag.show"})
                   2421: 	    && $insertlist{"$tag.show"} ne 'yes') {
                   2422: 	    print XML ("
                   2423: \t\t<show>".$insertlist{"$tag.show"}."</show>");
                   2424: 	}
                   2425: 	if (defined($insertlist{"$tag.helpfile"})) {
                   2426: 	    print XML ("
                   2427: \t\t<help>
                   2428: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
                   2429: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
                   2430: 		print XML ("
                   2431: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
                   2432: 	    }
                   2433: 	    print XML ("
                   2434: \t\t</help>");
                   2435: 	}
                   2436: 	if (defined($insertlist{"$tag.which"})) {
                   2437: 	    print XML ("
                   2438: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
                   2439: 	}
                   2440: 	print XML ("
                   2441: \t</tag>");
                   2442: 	$i++;
                   2443:     }
                   2444:     print XML ("\n</insertlist>\n");
                   2445:     close(XML);
                   2446: }
                   2447: 
1.98      albertel 2448: sub description {
1.437     albertel 2449:     my ($token)=@_;
                   2450:     my $tag = &get_tag($token);
                   2451:     return $insertlist{$tag.'.description'};
1.268     bowersj2 2452: }
                   2453: 
                   2454: # Returns a list containing the help file, and the description
                   2455: sub helpinfo {
1.437     albertel 2456:     my ($token)=@_;
                   2457:     my $tag = &get_tag($token);
1.531.2.13  raeburn  2458:     return ($insertlist{$tag.'.helpfile'}, &mt($insertlist{$tag.'.helpdesc'}));
1.437     albertel 2459: }
                   2460: 
                   2461: sub get_tag {
                   2462:     my ($token)=@_;
                   2463:     my $tagnum;
                   2464:     my $tag=$token->[1];
                   2465:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
                   2466: 	my $testtag = $namespace.'::'.$tag;
                   2467: 	$tagnum = $insertlist{"$testtag.num"};
                   2468: 	last if (defined($tagnum));
                   2469:     }
                   2470:     if (!defined($tagnum)) {
                   2471: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
                   2472:     }
                   2473:     return $insertlist{"$tagnum.tag"};
1.98      albertel 2474: }
1.123     albertel 2475: 
1.485     onken    2476: ############################################################
                   2477: #                                           PDF-FORM-METHODS
                   2478: 
                   2479: =pod
                   2480: 
1.508     onken    2481: =item &print_pdf_radiobutton(fieldname, value)
1.485     onken    2482: 
1.508     onken    2483: Returns a latexline to generate a PDF-Form-Radiobutton.
                   2484: Note: Radiobuttons with equal names are automaticly grouped 
                   2485:       in a selection-group.
1.485     onken    2486: 
1.508     onken    2487: $fieldname: PDF internalname of the radiobutton(group)
                   2488: $value:     Value of radiobutton
1.485     onken    2489: 
                   2490: =cut
                   2491: sub print_pdf_radiobutton {
1.508     onken    2492:     my ($fieldname, $value) = @_;
                   2493:     return '\radioButton[\symbolchoice{circle}]{'
                   2494:            .$fieldname.'}{10bp}{10bp}{'.$value.'}';
1.485     onken    2495: }
                   2496: 
                   2497: 
                   2498: =pod
                   2499: 
                   2500: =item &print_pdf_start_combobox(fieldname)
                   2501: 
                   2502: Starts a latexline to generate a PDF-Form-Combobox with text.
                   2503: 
                   2504: $fieldname: PDF internal name of the Combobox
                   2505: 
                   2506: =cut
                   2507: sub print_pdf_start_combobox {
                   2508:     my $result;
                   2509:     my ($fieldName) = @_;
                   2510:     $result .= '\begin{tabularx}{\textwidth}{p{2.5cm}X}'."\n";
                   2511:     $result .= '\comboBox[]{'.$fieldName.'}{2.3cm}{14bp}{'; # 
                   2512: 
                   2513:     return $result;
                   2514: }
                   2515: 
                   2516: 
                   2517: =pod
                   2518: 
                   2519: =item &print_pdf_add_combobox_option(options)
                   2520: 
                   2521: Generates a latexline to add Options to a PDF-Form-ComboBox.
                   2522: 
                   2523: $option: PDF internal name of the Combobox-Option
                   2524: 
                   2525: =cut
                   2526: sub print_pdf_add_combobox_option {
                   2527: 
                   2528:     my $result;
                   2529:     my ($option) = @_;  
                   2530: 
                   2531:     $result .= '('.$option.')';
                   2532:     
                   2533:     return $result;
                   2534: }
                   2535: 
                   2536: 
                   2537: =pod
                   2538: 
                   2539: =item &print_pdf_end_combobox(text) {
                   2540: 
                   2541: Returns latexcode to end a PDF-Form-Combobox with text.
                   2542: 
                   2543: =cut
                   2544: sub print_pdf_end_combobox {
                   2545:     my $result;
                   2546:     my ($text) = @_;
                   2547: 
                   2548:     $result .= '}&'.$text."\\\\\n";
                   2549:     $result .= '\end{tabularx}' . "\n";
                   2550:     $result .= '\hspace{2mm}' . "\n";
                   2551:     return $result;
                   2552: }
                   2553: 
                   2554: 
                   2555: =pod
                   2556: 
                   2557: =item &print_pdf_hiddenField(fieldname, user, domain)
                   2558: 
                   2559: Returns a latexline to generate a PDF-Form-hiddenField with userdata.
                   2560: 
                   2561: $fieldname label for hiddentextfield
                   2562: $user:    name of user
                   2563: $domain:  domain of user
                   2564: 
                   2565: =cut
                   2566: sub print_pdf_hiddenfield {
                   2567:     my $result;
                   2568:     my ($fieldname, $user, $domain) = @_;
                   2569: 
                   2570:     $result .= '\textField [\F{\FHidden}\F{-\FPrint}\V{'.$domain.'&'.$user.'}]{'.$fieldname.'}{0in}{0in}'."\n";
                   2571: 
                   2572:     return $result;
                   2573: }
                   2574: 
1.1       sakharuk 2575: 1;
                   2576: __END__
1.68      www      2577: 

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