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

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

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