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

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

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