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

1.2       sakharuk    1: # The LearningOnline Network with CAPA
1.3       sakharuk    2: # XML Parser Module 
1.2       sakharuk    3: #
1.531.2.26! raeburn     4: # $Id: lonxml.pm,v 1.531.2.25 2024/07/04 15:50:20 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.531.2.26! raeburn  1636: sub setmode_javascript {
        !          1637:     return <<"ENDSCRIPT";
        !          1638: <script type="text/javascript">
        !          1639: // <![CDATA[
        !          1640: function setmode(form,probmode) {
        !          1641:     var initial = form.problemmode.value;
        !          1642:     form.problemmode.value = probmode;
        !          1643:     form.submit();
        !          1644:     form.problemmode.value = initial;
        !          1645: }
        !          1646: // ]]>
        !          1647: </script>
        !          1648: ENDSCRIPT
        !          1649: }
        !          1650: 
1.151     albertel 1651: sub inserteditinfo {
1.531.2.11  raeburn  1652:       my ($filecontents,$filetype,$filename,$symb,$itemtitle,$folderpath,$uri,$action) = @_;
1.314     albertel 1653:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
1.274     albertel 1654:       my $xml_help = '';
1.321     www      1655:       my $initialize='';
1.452     albertel 1656:       my $textarea_id = 'filecont';
1.531.2.16  raeburn  1657:       my ($dragmath_button,$deps_button,$context,$cnum,$cdom,$add_to_onload,
                   1658:           $add_to_onresize,$init_dragmath);
1.456     albertel 1659:       $initialize=&Apache::lonhtmlcommon::spellheader();
1.531.2.16  raeburn  1660:       if ($filetype eq 'html') {
                   1661:           if ($env{'request.course.id'}) {
                   1662:               $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1663:               $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   1664:               if ($uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E}) {
                   1665:                   $context = 'syllabus';
                   1666:               }
                   1667:           }
                   1668:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
                   1669: 	      my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
                   1670:               my %textarea_args = (
                   1671:                                     fullpage => 'true',
                   1672:                                     dragmath => 'math',
                   1673:                                   );
                   1674:               $initialize .= &Apache::lonhtmlcommon::htmlareaselectactive(\%textarea_args);
                   1675:               if ($context eq 'syllabus') {
                   1676:                   $init_dragmath = "editmath_visibility('filecont','none')";
                   1677:               }
                   1678:           }
1.514     raeburn  1679:       }
                   1680:       $initialize .= (<<FULLPAGE);
1.321     www      1681: <script type="text/javascript">
1.514     raeburn  1682: // <![CDATA[
1.321     www      1683:     function initDocument() {
1.463     albertel 1684: 	resize_textarea('$textarea_id','LC_aftertextarea');
1.531.2.16  raeburn  1685:         $init_dragmath
1.321     www      1686:     }
1.514     raeburn  1687: // ]]>
1.321     www      1688: </script>
                   1689: FULLPAGE
1.531.2.8  raeburn  1690:       my $textareaclass;
1.514     raeburn  1691:       if ($filetype eq 'html') {
1.531.2.16  raeburn  1692:           if ($context eq 'syllabus') {
                   1693:               $deps_button = &Apache::lonhtmlcommon::dependencies_button()."\n";
                   1694:               $initialize .=
                   1695:                   &Apache::lonhtmlcommon::dependencycheck_js(undef,&mt('Syllabus'),
                   1696:                                                              $uri,undef,
                   1697:                                                              "/public/$cdom/$cnum/syllabus").
                   1698:                   "\n";
                   1699:               if (&Apache::lonhtmlcommon::htmlareabrowser()) {
                   1700:                   $textareaclass = 'class="LC_richDefaultOn"';
1.531.2.7  raeburn  1701:               }
1.531.2.16  raeburn  1702:           } elsif ($symb || $folderpath) {
                   1703:               $deps_button = &Apache::lonhtmlcommon::dependencies_button()."\n";
                   1704:               $initialize .=
                   1705:                   &Apache::lonhtmlcommon::dependencycheck_js($symb,$itemtitle,
                   1706:                                                              undef,$folderpath,$uri)."\n";
1.530     raeburn  1707:           }
1.514     raeburn  1708:           $dragmath_button = '<span id="math_filecont">'.&Apache::lonhtmlcommon::dragmath_button('filecont',1).'</span>';
                   1709:           $initialize .= "\n".&Apache::lonhtmlcommon::dragmath_js('EditMathPopup');
1.512     raeburn  1710:       }
1.456     albertel 1711:       $add_to_onload = 'initDocument();';
                   1712:       $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
                   1713: 
                   1714:       if ($filetype eq 'html') {
1.531.2.15  raeburn  1715:           my $not_author;
                   1716:           if ($uri =~ m{^/uploaded/}) {
                   1717:               $not_author = 1;
                   1718:           }
                   1719: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet(undef,undef,$not_author);
1.274     albertel 1720:       }
1.452     albertel 1721: 
1.254     albertel 1722:       my $titledisplay=&display_title();
1.426     banghart 1723:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
                   1724: 					 'vi' => 'Save and View',
1.427     banghart 1725: 					 'dv' => 'Discard Edits and View',
1.428     banghart 1726: 					 'un' => 'undo',
1.280     www      1727: 					 'ed' => 'Edit');
1.512     raeburn  1728:       my $spelllink = &Apache::lonhtmlcommon::spelllink('xmledit','filecont');
1.451     albertel 1729:       my $textarea_events = &Apache::edit::element_change_detection();
                   1730:       my $form_events     = &Apache::edit::form_change_detection();
1.491     raeburn  1731:       my $htmlerror;
                   1732:       if ($filetype eq 'html') {
                   1733:           $htmlerror=&verify_html($filecontents);
                   1734:           if ($htmlerror) {
1.531.2.25  raeburn  1735:               $htmlerror=('&nbsp;'x3).' <span class="LC_error">'.$htmlerror.'</span>';
1.491     raeburn  1736:           }
1.501     raeburn  1737:           if (&Apache::lonhtmlcommon::htmlareabrowser()) {
1.531.2.8  raeburn  1738:               unless ($textareaclass) {
                   1739:                   $textareaclass = 'class="LC_richDefaultOff"';
                   1740:               }
1.501     raeburn  1741:           }
1.472     www      1742:       }
1.531.2.25  raeburn  1743:       my ($undo,%onclick);
                   1744:       foreach my $item ('discard','undo') {
                   1745:           $onclick{$item} = 'onclick="still_ask=true;setmode(this.form,'."'$item'".')"';
                   1746:       }
                   1747:       foreach my $item ('saveedit','saveview') {
                   1748:           $onclick{$item} = 'onclick="is_submit=true;setmode(this.form,'."'$item'".')"';
                   1749:       }
1.531.2.15  raeburn  1750:       unless ($uri =~ m{^/uploaded/}) {
1.531.2.25  raeburn  1751:           $undo = '<input type="submit" name="Undo" accesskey="u" value="'.$lt{'un'}.'" '.
                   1752:                   $onclick{'undo'}.' />'."\n"; 
1.531.2.15  raeburn  1753:       }
1.531.2.25  raeburn  1754:       $initialize .= &setmode_javascript();
1.78      www      1755:       my $editfooter=(<<ENDFOOTER);
1.321     www      1756: $initialize
1.78      www      1757: <a name="editsection" />
1.531.2.11  raeburn  1758: <form $form_events method="post" name="xmledit" action="$action">
1.531.2.25  raeburn  1759:   <input type="hidden" name="problemmode" value="edit" />
1.470     albertel 1760:   <div class="LC_edit_problem_editxml_header">
                   1761:     <table class="LC_edit_problem_header_title"><tr><td>
                   1762:         $filename
                   1763:       </td><td align="right">
                   1764:         $xml_help
                   1765:       </td></tr>
                   1766:     </table>
1.531.2.22  raeburn  1767:     <div style="float:right">
1.531.2.25  raeburn  1768:       <input type="button" name="savethisfile" accesskey="s" value="$lt{'st'}" $onclick{'saveedit'} />
                   1769:       <input type="button" name="viewmode" accesskey="v" value="$lt{'vi'}" $onclick{'saveview'} />
                   1770:     </div>
                   1771:     <div>
                   1772:       <input type="button" name="discardview" accesskey="d" value="$lt{'dv'}" $onclick{'discard'} />
                   1773:       $undo $deps_button $dragmath_button $htmlerror
1.470     albertel 1774:     </div>
                   1775:   </div>
1.513     raeburn  1776:   <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont" $textareaclass>$filecontents</textarea><br />$spelllink
1.470     albertel 1777:   <div id="LC_aftertextarea">
                   1778:     <br />
                   1779:     $titledisplay
                   1780:   </div>
1.78      www      1781: </form>
                   1782: ENDFOOTER
1.531.2.25  raeburn  1783:       return ($editfooter,$add_to_onload,$add_to_onresize);
1.78      www      1784: }
                   1785: 
1.152     albertel 1786: sub get_target {
1.372     albertel 1787:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
                   1788:   if ( $env{'request.state'} eq 'published') {
                   1789:     if ( defined($env{'form.grade_target'})
1.152     albertel 1790: 	 && ($viewgrades == 'F' )) {
1.372     albertel 1791:       return ($env{'form.grade_target'});
                   1792:     } elsif (defined($env{'form.grade_target'})) {
                   1793:       if (($env{'form.grade_target'} eq 'web') ||
                   1794: 	  ($env{'form.grade_target'} eq 'tex') ) {
                   1795: 	return $env{'form.grade_target'}
1.153     albertel 1796:       } else {
                   1797: 	return 'web';
                   1798:       }
1.152     albertel 1799:     } else {
                   1800:       return 'web';
                   1801:     }
1.372     albertel 1802:   } elsif ($env{'request.state'} eq 'construct') {
                   1803:     if ( defined($env{'form.grade_target'})) {
                   1804:       return ($env{'form.grade_target'});
1.152     albertel 1805:     } else {
                   1806:       return 'web';
                   1807:     }
                   1808:   } else {
                   1809:     return 'web';
                   1810:   }
                   1811: }
                   1812: 
1.24      sakharuk 1813: sub handler {
1.255     sakharuk 1814:     my $request=shift;
1.493     raeburn  1815: 
1.255     sakharuk 1816:     my $target=&get_target();
1.372     albertel 1817:     $Apache::lonxml::debug=$env{'user.debug'};
1.255     sakharuk 1818:     
1.364     albertel 1819:     &Apache::loncommon::content_type($request,'text/html');
1.255     sakharuk 1820:     &Apache::loncommon::no_cache($request);
1.372     albertel 1821:     if ($env{'request.state'} eq 'published') {
1.363     albertel 1822: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                   1823: 							      'lastrevisiondate'));
                   1824:     }
1.499     raeburn  1825:     # Embedded Flash movies from Camtasia served from https will not display in IE
                   1826:     #   if XML config file has expired from cache.    
                   1827:     if ($ENV{'SERVER_PORT'} == 443) {
                   1828:         if ($request->uri =~ /\.xml$/) {
                   1829:             my ($httpbrowser,$clientbrowser) =
                   1830:                 &Apache::loncommon::decode_user_agent($request);
                   1831:             if ($clientbrowser =~ /^explorer$/i) {
                   1832:                 delete $request->headers_out->{'Cache-control'};
                   1833:                 delete $request->headers_out->{'Pragma'};
                   1834:                 my $expiration = time + 60;
                   1835:                 my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime($expiration));
                   1836:                 $request->headers_out->set("Expires" => $date);
                   1837:             }
                   1838:         }
                   1839:     }
1.255     sakharuk 1840:     $request->send_http_header;
                   1841:     
                   1842:     return OK if $request->header_only;
1.68      www      1843: 
                   1844: 
1.255     sakharuk 1845:     my $file=&Apache::lonnet::filelocation("",$request->uri);
1.502     raeburn  1846:     my ($filetype,$breadcrumbtext);
                   1847:     if ($file =~ /\.(sty|css|js|txt|tex)$/) {
1.493     raeburn  1848: 	$filetype=$1;
1.274     albertel 1849:     } else {
                   1850: 	$filetype='html';
                   1851:     }
1.531.2.5  raeburn  1852:     unless ($env{'request.uri'}) {
                   1853:         $env{'request.uri'}=$request->uri;
                   1854:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1855:                                                 ['todocs']);
                   1856:     }
1.531.2.8  raeburn  1857:     my ($cdom,$cnum);
                   1858:     if ($env{'request.course.id'}) {
                   1859:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1860:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   1861:         if ($filetype eq 'html') {
                   1862:             if ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E.+$}) {
                   1863:                 if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
                   1864:                     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1865:                                                             ['editmode']);
                   1866:                 }
                   1867:             }
                   1868:         }
                   1869:     }
1.502     raeburn  1870:     if ($filetype eq 'sty') {
                   1871:         $breadcrumbtext = 'Style File Editor';
                   1872:     } elsif ($filetype eq 'js') {
                   1873:         $breadcrumbtext = 'Javascript Editor';
                   1874:     } elsif ($filetype eq 'css') {
                   1875:         $breadcrumbtext = 'CSS Editor';
                   1876:     } elsif ($filetype eq 'txt') {
                   1877:         $breadcrumbtext = 'Text Editor';
                   1878:     } elsif ($filetype eq 'tex') {
                   1879:         $breadcrumbtext = 'TeX Editor';
                   1880:     } else {
                   1881:         $breadcrumbtext = 'HTML Editor';
                   1882:     }
1.493     raeburn  1883: 
1.78      www      1884: #
                   1885: # Edit action? Save file.
                   1886: #
1.428     banghart 1887:     if (!($env{'request.state'} eq 'published')) {
1.531.2.25  raeburn  1888:         if (($env{'form.problemmode'} eq 'saveedit') ||
                   1889:             ($env{'form.problemmode'} eq 'saveview') ||
                   1890:             ($env{'form.problemmode'} eq 'undo')) {
1.429     albertel 1891: 	    my $html_file=&Apache::lonnet::getfile($file);
                   1892: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
1.531.2.25  raeburn  1893:             if ($env{'form.problemmode'} eq 'saveedit') {
                   1894:                 $env{'form.editmode'}='edit'; #force edit mode
1.472     www      1895:             }
1.255     sakharuk 1896: 	}
                   1897:     }
1.531.2.17  raeburn  1898:     my $inhibit_menu;
1.255     sakharuk 1899:     my %mystyle;
                   1900:     my $result = '';
                   1901:     my $filecontents=&Apache::lonnet::getfile($file);
                   1902:     if ($filecontents eq -1) {
1.402     albertel 1903: 	my $start_page=&Apache::loncommon::start_page('File Error');
1.412     albertel 1904: 	my $end_page=&Apache::loncommon::end_page();
1.495     bisitz   1905:         my $errormsg='<p class="LC_error">'
                   1906:                     .&mt('File not found: [_1]'
                   1907:                         ,'<span class="LC_filename">'.$file.'</span>')
                   1908:                     .'</p>';
1.255     sakharuk 1909: 	$result=(<<ENDNOTFOUND);
1.402     albertel 1910: $start_page
1.495     bisitz   1911: $errormsg
1.402     albertel 1912: $end_page
1.78      www      1913: ENDNOTFOUND
1.343     albertel 1914:         $filecontents='';
1.372     albertel 1915: 	if ($env{'request.state'} ne 'published') {
1.274     albertel 1916: 	    if ($filetype eq 'sty') {
                   1917: 		$filecontents=&createnewsty();
1.493     raeburn  1918:             } elsif ($filetype eq 'js') {
                   1919:                 $filecontents=&createnewjs();
1.502     raeburn  1920:             } elsif ($filetype ne 'css' && $filetype ne 'txt' && $filetype ne 'tex') {
1.274     albertel 1921: 		$filecontents=&createnewhtml();
                   1922: 	    }
1.531.2.25  raeburn  1923: 	    $env{'form.editmode'}='edit'; #force edit mode
1.255     sakharuk 1924: 	}
                   1925:     } else {
1.372     albertel 1926: 	unless ($env{'request.state'} eq 'published') {
1.343     albertel 1927: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
1.381     www      1928: 		&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 1929: 	    }
1.264     www      1930: #
                   1931: # we are in construction space, see if edit mode forced
1.385     albertel 1932:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1933: 						    ['editmode']);
1.255     sakharuk 1934: 	}
1.531.2.25  raeburn  1935:         if ((!$env{'form.editmode'}) ||
                   1936:             ($env{'form.problemmode'} eq 'saveview') ||
                   1937:             ($env{'form.problemmode'} eq 'discard')) {
1.493     raeburn  1938:             if ($filetype eq 'html' || $filetype eq 'sty') {
                   1939: 	        &Apache::structuretags::reset_problem_globals();
                   1940: 	        $result = &Apache::lonxml::xmlparse($request,$target,
                   1941:                                                     $filecontents,'',%mystyle);
1.455     albertel 1942: 	    # .html files may contain <problem> or <Task> need to clean
                   1943: 	    # up if it did
1.493     raeburn  1944: 	        &Apache::structuretags::reset_problem_globals();
                   1945: 	        &Apache::lonhomework::finished_parsing();
1.502     raeburn  1946:             } elsif ($filetype eq 'tex') {
1.503     raeburn  1947:                 $result = &Apache::lontexconvert::converted(\$filecontents,
                   1948:                               $env{'form.texengine'});
                   1949:                 if ($env{'form.return_only_error_and_warning_counts'}) {
                   1950:                     $result = "$errorcount:$warningcount";
                   1951:                 }
1.493     raeburn  1952:             } else {
                   1953:                 $result = $filecontents;
                   1954:             }
1.385     albertel 1955: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1956: 						    ['rawmode']);
1.395     albertel 1957: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
1.531.2.17  raeburn  1958:             if (($env{'request.state'} eq 'construct') &&
                   1959:                 (($filetype eq 'css') || ($filetype eq 'js')) && ($ENV{'HTTP_REFERER'})) {
                   1960:                 if ($ENV{'HTTP_REFERER'} =~ m{^https?\://[^\/]+/priv/$LONCAPA::match_domain/$LONCAPA::match_username/[^\?]+\.(x?html?|swf)(|\?)[^\?]*$}) {
                   1961:                     $inhibit_menu = 1;
                   1962:                 }
                   1963:             }
1.503     raeburn  1964:             if (($filetype ne 'html') && 
1.531.2.17  raeburn  1965:                 (!$env{'form.return_only_error_and_warning_counts'}) &&
                   1966:                 (!$inhibit_menu)) {
1.502     raeburn  1967:                 my $nochgview = 1;
1.495     bisitz   1968:                 my $controls = '';
                   1969:                     if ($env{'request.state'} eq 'construct') {
                   1970:                         $controls = &Apache::loncommon::head_subbox(
                   1971:                                         &Apache::loncommon::CSTR_pageheader()
                   1972:                                        .&Apache::londefdef::edit_controls($nochgview));
                   1973:                     }
1.502     raeburn  1974:                 if ($filetype ne 'sty' && $filetype ne 'tex') {
1.493     raeburn  1975:                     $result =~ s/</&lt;/g;
                   1976:                     $result =~ s/>/&gt;/g;
                   1977:                     $result = '<table class="LC_sty_begin">'.
                   1978:                               '<tr><td><b><pre>'.$result.
                   1979:                               '</pre></b></td></tr></table>';
                   1980:                 }
1.506     droeschl 1981:                 my $brcrum;
                   1982:                 if ($env{'request.state'} eq 'construct') {
1.523     raeburn  1983:                     $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.531.2.9  raeburn  1984:                                 'text' => 'Authoring Space'},
1.506     droeschl 1985:                                {'href' => '',
                   1986:                                 'text' => $breadcrumbtext}];
1.493     raeburn  1987:                 } else {
1.506     droeschl 1988:                     $brcrum = ''; # FIXME: Where are we?
1.493     raeburn  1989:                 }
1.506     droeschl 1990:                 my %options = ('bread_crumbs' => $brcrum,
                   1991:                                'bgcolor'      => '#FFFFFF');
                   1992:                 $result =
                   1993:                     &Apache::loncommon::start_page(undef,undef,\%options)
                   1994:                    .$controls
                   1995:                    .$result
                   1996:                    .&Apache::loncommon::end_page();
1.493     raeburn  1997:             }
1.495     bisitz   1998:         }
1.147     albertel 1999:     }
1.456     albertel 2000: 
1.78      www      2001: #
                   2002: # Edit action? Insert editing commands
                   2003: #
1.531.2.17  raeburn  2004:     unless (($env{'request.state'} eq 'published') || ($inhibit_menu)) {
1.531.2.25  raeburn  2005:         if (($env{'form.editmode'}) &&
                   2006:             (!($env{'form.problemmode'} eq 'saveview')) &&
                   2007:             (!($env{'form.problemmode'} eq 'discard'))) {
1.531.2.11  raeburn  2008:             my ($displayfile,$url,$symb,$itemtitle,$action);
1.530     raeburn  2009: 	    $displayfile=$request->uri;
                   2010:             if ($request->uri =~ m{^/uploaded/}) {
1.531.2.5  raeburn  2011:                 if ($env{'request.course.id'}) {
1.531.2.7  raeburn  2012:                     if ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/supplemental/\E}) {
1.531.2.5  raeburn  2013:                         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2014:                                                                 ['folderpath','title']);
1.531.2.7  raeburn  2015:                     } elsif ($request->uri =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus/\E(.+)$}) {
1.531.2.8  raeburn  2016:                         my $filename = $1;
                   2017:                         if ($1 eq 'loncapa.html') {
                   2018:                             $displayfile = &mt('Syllabus (minimal template)');
1.531.2.11  raeburn  2019:                             $action = $request->uri.'?forceedit=1';
1.531.2.8  raeburn  2020:                         } else {
                   2021:                             $displayfile = &mt('Syllabus file: [_1]',$1);
                   2022:                         }
1.531.2.7  raeburn  2023:                         $itemtitle = &mt('Syllabus');
1.531.2.5  raeburn  2024:                     }
                   2025:                 }
1.531.2.7  raeburn  2026:                 unless ($itemtitle) {
                   2027:                     ($symb,$itemtitle,$displayfile) = 
                   2028:                         &get_courseupload_hierarchy($request->uri,
                   2029:                                                     $env{'form.folderpath'},
                   2030:                                                     $env{'form.title'});
                   2031:                 }
1.529     raeburn  2032:             } else {
                   2033: 	        $displayfile=~s/^\/[^\/]*//;
                   2034:             }
1.470     albertel 2035: 
1.452     albertel 2036: 	    my ($edit_info, $add_to_onload, $add_to_onresize)=
1.531.2.5  raeburn  2037: 		&inserteditinfo($filecontents,$filetype,$displayfile,$symb,
1.531.2.11  raeburn  2038:                                 $itemtitle,$env{'form.folderpath'},$request->uri,$action);
1.450     albertel 2039: 
                   2040: 	    my %options = 
                   2041: 		('add_entries' =>
1.495     bisitz   2042:                    {'onresize'     => $add_to_onresize,
                   2043:                     'onload'       => $add_to_onload,   });
1.500     raeburn  2044:             my $header;
                   2045:             if ($env{'request.state'} eq 'construct') {
                   2046:                 $options{'bread_crumbs'} = [{
1.523     raeburn  2047:                             'href' => &Apache::loncommon::authorspace($request->uri),
1.531.2.9  raeburn  2048:                             'text' => 'Authoring Space'},
1.500     raeburn  2049:                            {'href' => '',
1.502     raeburn  2050:                             'text' => $breadcrumbtext}];
1.500     raeburn  2051:                 $header = &Apache::loncommon::head_subbox(
                   2052:                               &Apache::loncommon::CSTR_pageheader());
                   2053:             }
1.452     albertel 2054: 	    my $js =
                   2055: 		&Apache::edit::js_change_detection().
                   2056: 		&Apache::loncommon::resize_textarea_js();
1.451     albertel 2057: 	    my $start_page = &Apache::loncommon::start_page(undef,$js,
1.402     albertel 2058: 							    \%options);
1.495     bisitz   2059:             $result = $start_page
1.500     raeburn  2060:                      .$header
1.495     bisitz   2061:                      .&Apache::lonxml::message_location()
                   2062:                      .$edit_info
                   2063:                      .&Apache::loncommon::end_page();
1.493     raeburn  2064:         }
1.147     albertel 2065:     }
1.402     albertel 2066:     if ($filetype eq 'html') { &writeallows($request->uri); }
1.501     raeburn  2067: 
1.309     albertel 2068:     &Apache::lonxml::add_messages(\$result);
1.255     sakharuk 2069:     $request->print($result);
                   2070:     
                   2071:     return OK;
1.253     albertel 2072: }
                   2073: 
                   2074: sub display_title {
                   2075:     my $result;
1.372     albertel 2076:     if ($env{'request.state'} eq 'construct') {
1.253     albertel 2077: 	my $title=&Apache::lonnet::gettitle();
                   2078: 	if (!defined($title) || $title eq '') {
1.372     albertel 2079: 	    $title = $env{'request.filename'};
1.253     albertel 2080: 	    $title = substr($title, rindex($title, '/') + 1);
                   2081: 	}
1.476     bisitz   2082:         $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
1.531.2.9  raeburn  2083:                   .&mt('Authoring Space')."';</script>";
1.253     albertel 2084:     }
                   2085:     return $result;
1.24      sakharuk 2086: }
1.147     albertel 2087: 
1.530     raeburn  2088: sub get_courseupload_hierarchy {
1.531.2.5  raeburn  2089:     my ($url,$folderpath,$title) = @_;
1.530     raeburn  2090:     my ($symb,$itemtitle,$displaypath);
                   2091:     if ($env{'request.course.id'}) {
1.531.2.5  raeburn  2092:         if ($folderpath =~ /^supplemental/) {
                   2093:             my @folders = split(/\&/,$folderpath);
                   2094:             my @pathitems;
                   2095:             while (@folders) {
                   2096:                 my $folder=shift(@folders);
                   2097:                 my $foldername=shift(@folders);
1.531.2.6  raeburn  2098:                 $foldername =~ s/\:(\d*)\:(\w*)\:(\w*):(\d*)\:?(\d*)$//;
1.531.2.5  raeburn  2099:                 push(@pathitems,&unescape($foldername));
                   2100:             }
                   2101:             if ($title) {
                   2102:                 push(@pathitems,&unescape($title));
                   2103:             }
                   2104:             $displaypath = join(' &raquo; ',@pathitems);
                   2105:         } else {
                   2106:             $symb = &Apache::lonnet::symbread($url);
                   2107:             my ($map,$id,$res)=&Apache::lonnet::decode_symb($symb);
                   2108:             my $navmap=Apache::lonnavmaps::navmap->new;
                   2109:             if (ref($navmap)) {
                   2110:                 my $res = $navmap->getBySymb($symb);
                   2111:                 if (ref($res)) {
                   2112:                     my @pathitems =
                   2113:                         &Apache::loncommon::get_folder_hierarchy($navmap,$map,1);
                   2114:                     $itemtitle = $res->compTitle();
                   2115:                     push(@pathitems,$itemtitle);
                   2116:                     $displaypath = join(' &raquo; ',@pathitems);
                   2117:                 }
1.530     raeburn  2118:             }
                   2119:         }
                   2120:     }
                   2121:     return ($symb,$itemtitle,$displaypath);
                   2122: }
                   2123: 
1.22      albertel 2124: sub debug {
1.298     albertel 2125:     if ($Apache::lonxml::debug eq "1") {
                   2126: 	$|=1;
1.300     albertel 2127: 	my $request=$Apache::lonxml::request;
1.388     albertel 2128: 	if (!$request) {
                   2129: 	    eval { $request=Apache->request; };
                   2130: 	}
                   2131: 	if (!$request) {
                   2132: 	    eval { $request=Apache2::RequestUtil->request; };
                   2133: 	}
1.314     albertel 2134: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
1.346     albertel 2135: 	#&Apache::lonnet::logthis($_[0]);
1.298     albertel 2136:     }
1.22      albertel 2137: }
1.49      albertel 2138: 
1.348     albertel 2139: sub show_error_warn_msg {
1.522     raeburn  2140:     if (($env{'request.filename'} eq 
                   2141:          $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/lib/templates/simpleproblem.problem') &&
                   2142:         (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
1.351     albertel 2143: 	return 1;
                   2144:     }
1.348     albertel 2145:     return (($Apache::lonxml::debug eq 1) ||
1.372     albertel 2146: 	    ($env{'request.state'} eq 'construct') ||
1.348     albertel 2147: 	    ($Apache::lonhomework::browse eq 'F'
                   2148: 	     &&
1.372     albertel 2149: 	     $env{'form.show_errors'} eq 'on'));
1.348     albertel 2150: }
                   2151: 
1.22      albertel 2152: sub error {
1.454     albertel 2153:     my @errors = @_;
                   2154: 
1.336     albertel 2155:     $errorcount++;
1.454     albertel 2156: 
1.490     www      2157:     $Apache::lonxml::internal_error=1;
                   2158: 
1.454     albertel 2159:     if (defined($Apache::inputtags::part)) {
                   2160: 	if ( @Apache::inputtags::response ) {
                   2161: 	    push(@errors,
                   2162: 		 &mt("This error occurred while processing response [_1] in part [_2]",
                   2163: 		     $Apache::inputtags::response[-1],
                   2164: 		     $Apache::inputtags::part));
                   2165: 	} else {
                   2166: 	    push(@errors,
                   2167: 		 &mt("This error occurred while processing part [_1]",
                   2168: 		     $Apache::inputtags::part));
                   2169: 	}
                   2170:     }
                   2171: 
1.348     albertel 2172:     if ( &show_error_warn_msg() ) {
1.336     albertel 2173: 	# If printing in construction space, put the error inside <pre></pre>
                   2174: 	push(@Apache::lonxml::error_messages,
1.484     bisitz   2175: 	     $Apache::lonxml::warnings_error_header
                   2176:              .'<div class="LC_error">'
                   2177:              .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
                   2178:              ."</div>\n");
1.336     albertel 2179: 	$Apache::lonxml::warnings_error_header='';
                   2180:     } else {
                   2181: 	my $errormsg;
                   2182: 	my ($symb)=&Apache::lonnet::symbread();
                   2183: 	if ( !$symb ) {
                   2184: 	    #public or browsers
1.486     bisitz   2185: 	    $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
1.403     albertel 2186: 	}
1.413     albertel 2187: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
1.476     bisitz   2188: 	push(@errors,
                   2189:         &mt("The error occurred on host [_1]",
                   2190:              "<tt>$host</tt>"));
1.454     albertel 2191: 
                   2192: 	my $msg = join('<br />', @errors);
                   2193: 
1.336     albertel 2194: 	#notify author
1.403     albertel 2195: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
1.336     albertel 2196: 	#notify course
1.372     albertel 2197: 	if ( $symb && $env{'request.course.id'} ) {
1.380     www      2198: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2199: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.440     albertel 2200: 	    my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
1.372     albertel 2201: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
1.435     raeburn  2202:             my $baseurl = &Apache::lonnet::clutter($declutter);
1.336     albertel 2203: 	    my @userlist;
1.531.2.18  raeburn  2204: 	    foreach (keys(%users)) {
1.336     albertel 2205: 		my ($user,$domain) = split(/:/, $_);
1.531     bisitz   2206: 		push(@userlist,"$user:$domain");
1.380     www      2207: 		my $key=$declutter.'_'.$user.'_'.$domain;
                   2208: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
                   2209: 						      [$key],
                   2210: 						      $cdom,$cnum);
                   2211: 		my $now=time;
                   2212: 		if ($now-$lastnotified{$key}>86400) {
1.434     raeburn  2213:                     my $title = &Apache::lonnet::gettitle($symb);
                   2214:                     my $sentmessage;
1.380     www      2215: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
1.435     raeburn  2216: 		        "Error [$title]",$msg,'',$baseurl,'','',
1.434     raeburn  2217:                         \$sentmessage,$symb,$title,1);
1.380     www      2218: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
                   2219: 					 {$key => $now},
                   2220: 					 $cdom,$cnum);		
                   2221: 		}
1.336     albertel 2222: 	    }
1.372     albertel 2223: 	    if ($env{'request.role.adv'}) {
1.486     bisitz   2224: 		$errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
1.336     albertel 2225: 	    } else {
1.486     bisitz   2226: 		$errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
1.336     albertel 2227: 	    }
                   2228: 	}
1.531     bisitz   2229: 	push(@Apache::lonxml::error_messages,"<span class=\"LC_warning\">$errormsg</span><br />");
1.52      albertel 2230:     }
1.22      albertel 2231: }
1.49      albertel 2232: 
1.22      albertel 2233: sub warning {
1.295     albertel 2234:     $warningcount++;
1.261     albertel 2235:   
1.372     albertel 2236:     if ($env{'form.grade_target'} ne 'tex') {
1.348     albertel 2237: 	if ( &show_error_warn_msg() ) {
1.309     albertel 2238: 	    push(@Apache::lonxml::warning_messages,
1.484     bisitz   2239: 		 $Apache::lonxml::warnings_error_header
                   2240:                 .'<div class="LC_warning">'
                   2241:                 .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
                   2242:                 ."</div>\n"
1.482     bisitz   2243:                 );
1.295     albertel 2244: 	    $Apache::lonxml::warnings_error_header='';
                   2245: 	}
                   2246:     }
1.309     albertel 2247: }
                   2248: 
                   2249: sub info {
1.372     albertel 2250:     if ($env{'form.grade_target'} ne 'tex' 
                   2251: 	&& $env{'request.state'} eq 'construct') {
1.309     albertel 2252: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
                   2253:     }
                   2254: }
                   2255: 
                   2256: sub message_location {
                   2257:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
                   2258: }
                   2259: 
                   2260: sub add_messages {
                   2261:     my ($msg)=@_;
                   2262:     my $result=join(' ',
                   2263: 		    @Apache::lonxml::info_messages,
                   2264: 		    @Apache::lonxml::error_messages,
                   2265: 		    @Apache::lonxml::warning_messages);
                   2266:     undef(@Apache::lonxml::info_messages);
                   2267:     undef(@Apache::lonxml::error_messages);
                   2268:     undef(@Apache::lonxml::warning_messages);
                   2269:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
                   2270:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
1.83      albertel 2271: }
                   2272: 
                   2273: sub get_param {
1.531.2.5  raeburn  2274:     my ($param,$parstack,$safeeval,$context,$case_insensitive, $noelide) = @_;
1.213     albertel 2275:     if ( ! $context ) { $context = -1; }
                   2276:     my $args ='';
                   2277:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 2278:     if ( ! $Apache::lonxml::usestyle ) {
                   2279: 	$args=$Apache::lonxml::style_values.$args;
                   2280:     }
1.531.2.5  raeburn  2281: 
                   2282:     if ($noelide) {
                   2283:         $args =~ s/'\$/'\\\$/g;
                   2284:     }
                   2285: 
1.213     albertel 2286:     if ( ! $args ) { return undef; }
                   2287:     if ( $case_insensitive ) {
1.417     albertel 2288: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
1.213     albertel 2289: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   2290:                                      $safeeval); #'
                   2291: 	} else {
                   2292: 	    return undef;
                   2293: 	}
                   2294:     } else {
1.417     albertel 2295: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
1.213     albertel 2296: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   2297:                                      $safeeval); #'
                   2298: 	} else {
                   2299: 	    return undef;
                   2300: 	}
                   2301:     }
1.22      albertel 2302: }
                   2303: 
1.132     albertel 2304: sub get_param_var {
1.213     albertel 2305:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1.132     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.230     albertel 2312:   &Apache::lonxml::debug("Args are $args param is $param");
1.213     albertel 2313:   if ($case_insensitive) {
1.419     albertel 2314:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
1.213     albertel 2315: 	  return undef;
                   2316:       }
1.419     albertel 2317:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
1.132     albertel 2318:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
1.230     albertel 2319:   &Apache::lonxml::debug("first run is $value");
1.341     albertel 2320:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
1.230     albertel 2321:       &Apache::lonxml::debug("doing second");
                   2322:       my @result=&Apache::run::run("return $value",$safeeval,1);
                   2323:       if (!defined($result[0])) {
                   2324: 	  return $value
                   2325:       } else {
                   2326: 	  if (wantarray) { return @result; } else { return $result[0]; }
                   2327:       }
1.132     albertel 2328:   } else {
                   2329:     return $value;
                   2330:   }
                   2331: }
                   2332: 
1.438     albertel 2333: sub register_insert_xml {
                   2334:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
                   2335: 				     .'/insertlist.xml');
                   2336:     my ($tagnum,$in_help)=(0,0);
1.442     albertel 2337:     my @alltags;
1.438     albertel 2338:     my $tag;
                   2339:     while (my $token = $parser->get_token()) {
                   2340: 	if ($token->[0] eq 'S') {
                   2341: 	    my $key;
1.525     raeburn  2342: 	    if ($token->[1] eq 'tag') {
1.438     albertel 2343: 		$tag = $token->[2]{'name'};
1.525     raeburn  2344:                 if (defined($tag)) {
                   2345: 		    $insertlist{$tagnum.'.tag'} = $tag;
                   2346: 		    $insertlist{$tag.'.num'}   = $tagnum;
                   2347: 		    push(@alltags,$tag);
                   2348:                 }
1.438     albertel 2349: 	    } elsif ($in_help && $token->[1] eq 'file') {
                   2350: 		$key = $tag.'.helpfile';
                   2351: 	    } elsif ($in_help && $token->[1] eq 'description') {
                   2352: 		$key = $tag.'.helpdesc';
                   2353: 	    } elsif ($token->[1] eq 'description' ||
                   2354: 		     $token->[1] eq 'color'       ||
                   2355: 		     $token->[1] eq 'show'          ) {
                   2356: 		$key = $tag.'.'.$token->[1];
                   2357: 	    } elsif ($token->[1] eq 'insert_sub') {
                   2358: 		$key = $tag.'.function';
                   2359: 	    } elsif ($token->[1] eq 'help') {
                   2360: 		$in_help=1;
                   2361: 	    } elsif ($token->[1] eq 'allow') {
1.442     albertel 2362: 		$key = $tag.'.allow';
1.438     albertel 2363: 	    }
                   2364: 	    if (defined($key)) {
                   2365: 		$insertlist{$key} = $parser->get_text();
                   2366: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
                   2367: 	    }
                   2368: 	} elsif ($token->[0] eq 'E') {
                   2369: 	    if      ($token->[1] eq 'tag') {
                   2370: 		undef($tag);
                   2371: 		$tagnum++;
                   2372: 	    } elsif ($token->[1] eq 'help') {
                   2373: 		undef($in_help);
                   2374: 	    }
                   2375: 	}
                   2376:     }
1.442     albertel 2377:     
                   2378:     # parse the allows and ignore tags set to <show>no</show>
                   2379:     foreach my $tag (@alltags) {	
1.519     raeburn  2380:         next if (!exists($insertlist{$tag.'.allow'}));
                   2381: 	my $allow =  $insertlist{$tag.'.allow'};
1.442     albertel 2382:        	foreach my $element (split(',',$allow)) {
                   2383: 	    $element =~ s/(^\s*|\s*$ )//gx;
1.519     raeburn  2384: 	    if (!exists($insertlist{$element.'.show'})
                   2385:                 || $insertlist{$element.'.show'} ne 'no') {
1.442     albertel 2386: 		push(@{ $insertlist{$tag.'.which'} },$element);
                   2387: 	    }
                   2388: 	}
                   2389:     }
1.438     albertel 2390: }
                   2391: 
                   2392: sub register_insert {
                   2393:     return &register_insert_xml(@_);
                   2394: #    &dump_insertlist('2');
                   2395: }
                   2396: 
                   2397: sub dump_insertlist {
                   2398:     my ($ext) = @_;
1.531.2.24  raeburn  2399:     open(XML,">","/tmp/insertlist.xml.$ext");
1.438     albertel 2400:     print XML ("<insertlist>");
                   2401:     my $i=0;
                   2402: 
                   2403:     while (exists($insertlist{"$i.tag"})) {
                   2404: 	my $tag = $insertlist{"$i.tag"};
                   2405: 	print XML ("
                   2406: \t<tag name=\"$tag\">");
                   2407: 	if (defined($insertlist{"$tag.description"})) {
                   2408: 	    print XML ("
                   2409: \t\t<description>".$insertlist{"$tag.description"}."</description>");
                   2410: 	}
                   2411: 	if (defined($insertlist{"$tag.color"})) {
                   2412: 	    print XML ("
                   2413: \t\t<color>".$insertlist{"$tag.color"}."</color>");
                   2414: 	}
                   2415: 	if (defined($insertlist{"$tag.function"})) {
                   2416: 	    print XML ("
                   2417: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
                   2418: 	}
                   2419: 	if (defined($insertlist{"$tag.show"})
                   2420: 	    && $insertlist{"$tag.show"} ne 'yes') {
                   2421: 	    print XML ("
                   2422: \t\t<show>".$insertlist{"$tag.show"}."</show>");
                   2423: 	}
                   2424: 	if (defined($insertlist{"$tag.helpfile"})) {
                   2425: 	    print XML ("
                   2426: \t\t<help>
                   2427: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
                   2428: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
                   2429: 		print XML ("
                   2430: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
                   2431: 	    }
                   2432: 	    print XML ("
                   2433: \t\t</help>");
                   2434: 	}
                   2435: 	if (defined($insertlist{"$tag.which"})) {
                   2436: 	    print XML ("
                   2437: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
                   2438: 	}
                   2439: 	print XML ("
                   2440: \t</tag>");
                   2441: 	$i++;
                   2442:     }
                   2443:     print XML ("\n</insertlist>\n");
                   2444:     close(XML);
                   2445: }
                   2446: 
1.98      albertel 2447: sub description {
1.437     albertel 2448:     my ($token)=@_;
                   2449:     my $tag = &get_tag($token);
                   2450:     return $insertlist{$tag.'.description'};
1.268     bowersj2 2451: }
                   2452: 
                   2453: # Returns a list containing the help file, and the description
                   2454: sub helpinfo {
1.437     albertel 2455:     my ($token)=@_;
                   2456:     my $tag = &get_tag($token);
1.531.2.13  raeburn  2457:     return ($insertlist{$tag.'.helpfile'}, &mt($insertlist{$tag.'.helpdesc'}));
1.437     albertel 2458: }
                   2459: 
                   2460: sub get_tag {
                   2461:     my ($token)=@_;
                   2462:     my $tagnum;
                   2463:     my $tag=$token->[1];
                   2464:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
                   2465: 	my $testtag = $namespace.'::'.$tag;
                   2466: 	$tagnum = $insertlist{"$testtag.num"};
                   2467: 	last if (defined($tagnum));
                   2468:     }
                   2469:     if (!defined($tagnum)) {
                   2470: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
                   2471:     }
                   2472:     return $insertlist{"$tagnum.tag"};
1.98      albertel 2473: }
1.123     albertel 2474: 
1.485     onken    2475: ############################################################
                   2476: #                                           PDF-FORM-METHODS
                   2477: 
                   2478: =pod
                   2479: 
1.508     onken    2480: =item &print_pdf_radiobutton(fieldname, value)
1.485     onken    2481: 
1.508     onken    2482: Returns a latexline to generate a PDF-Form-Radiobutton.
                   2483: Note: Radiobuttons with equal names are automaticly grouped 
                   2484:       in a selection-group.
1.485     onken    2485: 
1.508     onken    2486: $fieldname: PDF internalname of the radiobutton(group)
                   2487: $value:     Value of radiobutton
1.485     onken    2488: 
                   2489: =cut
                   2490: sub print_pdf_radiobutton {
1.508     onken    2491:     my ($fieldname, $value) = @_;
                   2492:     return '\radioButton[\symbolchoice{circle}]{'
                   2493:            .$fieldname.'}{10bp}{10bp}{'.$value.'}';
1.485     onken    2494: }
                   2495: 
                   2496: 
                   2497: =pod
                   2498: 
                   2499: =item &print_pdf_start_combobox(fieldname)
                   2500: 
                   2501: Starts a latexline to generate a PDF-Form-Combobox with text.
                   2502: 
                   2503: $fieldname: PDF internal name of the Combobox
                   2504: 
                   2505: =cut
                   2506: sub print_pdf_start_combobox {
                   2507:     my $result;
                   2508:     my ($fieldName) = @_;
                   2509:     $result .= '\begin{tabularx}{\textwidth}{p{2.5cm}X}'."\n";
                   2510:     $result .= '\comboBox[]{'.$fieldName.'}{2.3cm}{14bp}{'; # 
                   2511: 
                   2512:     return $result;
                   2513: }
                   2514: 
                   2515: 
                   2516: =pod
                   2517: 
                   2518: =item &print_pdf_add_combobox_option(options)
                   2519: 
                   2520: Generates a latexline to add Options to a PDF-Form-ComboBox.
                   2521: 
                   2522: $option: PDF internal name of the Combobox-Option
                   2523: 
                   2524: =cut
                   2525: sub print_pdf_add_combobox_option {
                   2526: 
                   2527:     my $result;
                   2528:     my ($option) = @_;  
                   2529: 
                   2530:     $result .= '('.$option.')';
                   2531:     
                   2532:     return $result;
                   2533: }
                   2534: 
                   2535: 
                   2536: =pod
                   2537: 
                   2538: =item &print_pdf_end_combobox(text) {
                   2539: 
                   2540: Returns latexcode to end a PDF-Form-Combobox with text.
                   2541: 
                   2542: =cut
                   2543: sub print_pdf_end_combobox {
                   2544:     my $result;
                   2545:     my ($text) = @_;
                   2546: 
                   2547:     $result .= '}&'.$text."\\\\\n";
                   2548:     $result .= '\end{tabularx}' . "\n";
                   2549:     $result .= '\hspace{2mm}' . "\n";
                   2550:     return $result;
                   2551: }
                   2552: 
                   2553: 
                   2554: =pod
                   2555: 
                   2556: =item &print_pdf_hiddenField(fieldname, user, domain)
                   2557: 
                   2558: Returns a latexline to generate a PDF-Form-hiddenField with userdata.
                   2559: 
                   2560: $fieldname label for hiddentextfield
                   2561: $user:    name of user
                   2562: $domain:  domain of user
                   2563: 
                   2564: =cut
                   2565: sub print_pdf_hiddenfield {
                   2566:     my $result;
                   2567:     my ($fieldname, $user, $domain) = @_;
                   2568: 
                   2569:     $result .= '\textField [\F{\FHidden}\F{-\FPrint}\V{'.$domain.'&'.$user.'}]{'.$fieldname.'}{0in}{0in}'."\n";
                   2570: 
                   2571:     return $result;
                   2572: }
                   2573: 
1.1       sakharuk 2574: 1;
                   2575: __END__
1.68      www      2576: 

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