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

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

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