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

1.2       sakharuk    1: # The LearningOnline Network with CAPA
1.3       sakharuk    2: # XML Parser Module 
1.2       sakharuk    3: #
1.438   ! albertel    4: # $Id: lonxml.pm,v 1.437 2007/01/29 23:51:04 albertel 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.2       sakharuk   40: 
1.4       albertel   41: package Apache::lonxml; 
1.33      www        42: use vars 
1.410     albertel   43: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount);
1.1       sakharuk   44: use strict;
1.167     albertel   45: use HTML::LCParser();
1.161     albertel   46: use HTML::TreeBuilder();
                     47: use HTML::Entities();
                     48: use Safe();
                     49: use Safe::Hole();
                     50: use Math::Cephes();
                     51: use Math::Random();
                     52: use Opcode();
1.271     www        53: use POSIX qw(strftime);
1.339     albertel   54: use Time::HiRes qw( gettimeofday tv_interval );
1.393     albertel   55: use Symbol();
1.266     bowersj2   56: 
1.72      albertel   57: sub register {
1.141     albertel   58:   my ($space,@taglist) = @_;
                     59:   foreach my $temptag (@taglist) {
                     60:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
1.72      albertel   61:   }
                     62: }
                     63: 
1.141     albertel   64: sub deregister {
                     65:   my ($space,@taglist) = @_;
                     66:   foreach my $temptag (@taglist) {
                     67:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
                     68:     if ($tempspace eq $space) {
                     69:       pop(@{ $Apache::lonxml::alltags{$temptag} });
                     70:     }
                     71:   }
1.142     albertel   72:   #&printalltags();
1.141     albertel   73: }
                     74: 
1.46      www        75: use Apache::Constants qw(:common);
1.161     albertel   76: use Apache::lontexconvert();
                     77: use Apache::style();
                     78: use Apache::run();
                     79: use Apache::londefdef();
                     80: use Apache::scripttag();
1.285     www        81: use Apache::languagetags();
1.161     albertel   82: use Apache::edit();
1.266     bowersj2   83: use Apache::inputtags();
                     84: use Apache::outputtags();
1.372     albertel   85: use Apache::lonnet;
1.161     albertel   86: use Apache::File();
                     87: use Apache::loncommon();
1.198     www        88: use Apache::lonfeedback();
1.200     www        89: use Apache::lonmsg();
1.217     matthew    90: use Apache::loncacc();
1.431     www        91: use Apache::lonmaxima();
1.280     www        92: use Apache::lonlocal;
1.79      www        93: 
1.72      albertel   94: #==================================================   Main subroutine: xmlparse  
                     95: #debugging control, to turn on debugging modify the correct handler
                     96: $Apache::lonxml::debug=0;
1.206     albertel   97: 
                     98: # keeps count of the number of warnings and errors generated in a parse
                     99: $warningcount=0;
                    100: $errorcount=0;
1.72      albertel  101: 
                    102: #path to the directory containing the file currently being processed
                    103: @pwd=();
                    104: 
                    105: #these two are used for capturing a subset of the output for later processing,
                    106: #don't touch them directly use &startredirection and &endredirection
                    107: @outputstack = ();
                    108: $redirection = 0;
                    109: 
                    110: #controls wheter the <import> tag actually does
                    111: $import = 1;
                    112: @extlinks=();
                    113: 
                    114: # meta mode is a bit weird only some output is to be turned off
                    115: #<output> tag turns metamode off (defined in londefdef.pm)
                    116: $metamode = 0;
                    117: 
                    118: # turns on and of run::evaluate actually derefencing var refs
                    119: $evaluate = 1;
1.7       albertel  120: 
1.74      albertel  121: # data structure for eidt mode, determines what tags can go into what other tags
                    122: %insertlist=();
1.68      www       123: 
1.99      albertel  124: # stores the list of active tag namespaces
1.76      albertel  125: @namespace=();
                    126: 
1.172     albertel  127: # a pointer the the Apache request object
                    128: $Apache::lonxml::request='';
                    129: 
1.216     sakharuk  130: # a problem number counter, and check on ether it is used
1.237     sakharuk  131: $Apache::lonxml::counter=1;
1.204     albertel  132: $Apache::lonxml::counter_changed=0;
                    133: 
1.212     albertel  134: #internal check on whether to look at style defs
                    135: $Apache::lonxml::usestyle=1;
1.260     albertel  136: 
                    137: #locations used to store the parameter string for style substitutions
                    138: $Apache::lonxml::style_values='';
                    139: $Apache::lonxml::style_end_values='';
1.212     albertel  140: 
1.281     albertel  141: #array of ssi calls that need to occur after we are done parsing
                    142: @Apache::lonxml::ssi_info=();
                    143: 
1.282     albertel  144: #should we do the postag variable interpolation
                    145: $Apache::lonxml::post_evaluate=1;
                    146: 
1.295     albertel  147: #a header message to emit in the case of any generated warning or errors
                    148: $Apache::lonxml::warnings_error_header='';
                    149: 
1.396     foxr      150: #  Control whether or not LaTeX symbols should be substituted for their
                    151: #  \ style equivalents...this may be turned off e.g. in an verbatim
                    152: #  environment.
                    153: 
                    154: $Apache::lonxml::substitute_LaTeX_symbols = 1; # Starts out on.
                    155: 
                    156: sub enable_LaTeX_substitutions {
                    157:     $Apache::lonxml::substitute_LaTeX_symbols = 1;
                    158: }
                    159: sub disable_LaTeX_substitutions {
                    160:     $Apache::lonxml::substitute_LaTeX_symbols = 0;
                    161: }
                    162: 
1.68      www       163: sub xmlend {
1.335     sakharuk  164:     my ($target,$parser)=@_;
1.278     www       165:     my $mode='xml';
                    166:     my $status='OPEN';
1.368     albertel  167:     if ($Apache::lonhomework::parsing_a_problem ||
                    168: 	$Apache::lonhomework::parsing_a_task ) {
1.278     www       169: 	$mode='problem';
                    170: 	$status=$Apache::inputtags::status[-1]; 
                    171:     }
1.362     matthew   172:     my $discussion;
1.379     albertel  173:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                    174: 					   ['LONCAPA_INTERNAL_no_discussion']);
1.372     albertel  175:     if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
                    176:         $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
1.362     matthew   177:         $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
                    178:     }
1.334     sakharuk  179:     if ($target eq 'tex') {
1.335     sakharuk  180: 	$discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
1.334     sakharuk  181: 	&Apache::lonxml::newparser($parser,\$discussion,'');
                    182: 	return '';
                    183:     }
1.405     albertel  184: 
1.407     albertel  185:     return $discussion;
1.119     www       186: }
                    187: 
                    188: sub tokeninputfield {
1.120     www       189:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
                    190:     $defhost=~tr/a-z/A-Z/;
1.119     www       191:     return (<<ENDINPUTFIELD)
1.226     albertel  192: <script type="text/javascript">
1.120     www       193:     function updatetoken() {
                    194: 	var comp=new Array;
                    195:         var barcode=unescape(document.tokeninput.barcode.value);
                    196:         comp=barcode.split('*');
                    197:         if (typeof(comp[0])!="undefined") {
                    198: 	    document.tokeninput.codeone.value=comp[0];
                    199: 	}
                    200:         if (typeof(comp[1])!="undefined") {
                    201: 	    document.tokeninput.codetwo.value=comp[1];
                    202: 	}
                    203:         if (typeof(comp[2])!="undefined") {
                    204:             comp[2]=comp[2].toUpperCase();
                    205: 	    document.tokeninput.codethree.value=comp[2];
                    206: 	}
                    207:         document.tokeninput.barcode.value='';
                    208:     }  
                    209: </script>
                    210: <form method="post" name="tokeninput">
1.119     www       211: <table border="2" bgcolor="#FFFFBB">
                    212: <tr><th>DocID Checkin</th></tr>
                    213: <tr><td>
                    214: <table>
                    215: <tr>
                    216: <td>Scan in Barcode</td>
1.120     www       217: <td><input type="text" size="22" name="barcode" 
                    218: onChange="updatetoken()"/></td>
1.119     www       219: </tr>
                    220: <tr><td><i>or</i> Type in DocID</td>
                    221: <td>
                    222: <input type="text" size="5" name="codeone" />
1.120     www       223: <b><font size="+2">*</font></b>
1.119     www       224: <input type="text" size="5" name="codetwo" />
1.120     www       225: <b><font size="+2">*</font></b>
                    226: <input type="text" size="10" name="codethree" value="$defhost" 
                    227: onChange="this.value=this.value.toUpperCase()" />
1.119     www       228: </td></tr>
                    229: </table>
                    230: </td></tr>
                    231: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
                    232: </table>
                    233: </form>
                    234: ENDINPUTFIELD
1.112     www       235: }
                    236: 
1.116     www       237: sub maketoken {
1.118     www       238:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
1.112     www       239:     unless ($symb) {
                    240: 	$symb=&Apache::lonnet::symbread();
                    241:     }
                    242:     unless ($tuname) {
1.372     albertel  243: 	$tuname=$env{'user.name'};
                    244:         $tudom=$env{'user.domain'};
                    245:         $tcrsid=$env{'request.course.id'};
1.112     www       246:     }
1.116     www       247: 
1.118     www       248:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
                    249: }
                    250: 
                    251: sub printtokenheader {
1.133     albertel  252:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
1.116     www       253:     unless ($token) { return ''; }
1.118     www       254: 
1.423     albertel  255:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
1.133     albertel  256:     unless ($tsymb) {
                    257: 	$tsymb=$symb;
1.118     www       258:     }
                    259:     unless ($tuname) {
1.133     albertel  260: 	$tuname=$name;
                    261:         $tudom=$domain;
                    262:         $tcrsid=$courseid;
1.118     www       263:     }
1.114     www       264: 
1.390     albertel  265:     my $plainname=&Apache::loncommon::plainname($tuname,$tudom);
1.114     www       266: 
1.112     www       267:     if ($target eq 'web') {
1.145     www       268:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
1.115     www       269: 	return 
1.221     albertel  270:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
1.284     www       271:                &mt('Checked out for').' '.$plainname.
                    272:                '<br />'.&mt('User').': '.$tuname.' at '.$tudom.
                    273: 	       '<br />'.&mt('ID').': '.$idhash{$tuname}.
                    274: 	       '<br />'.&mt('CourseID').': '.$tcrsid.
1.372     albertel  275: 	       '<br />'.&mt('Course').': '.$env{'course.'.$tcrsid.'.description'}.
1.284     www       276:                '<br />'.&mt('DocID').': '.$token.
                    277:                '<br />'.&mt('Time').': '.&Apache::lonlocal::locallocaltime().'<hr />';
1.112     www       278:     } else {
1.121     albertel  279:         return $token;
1.112     www       280:     }
1.68      www       281: }
                    282: 
1.48      albertel  283: sub printalltags {
                    284:   my $temp;
                    285:   foreach $temp (sort keys %Apache::lonxml::alltags) {
1.141     albertel  286:     &Apache::lonxml::debug("$temp -- ".
                    287: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
1.48      albertel  288:   }
                    289: }
1.31      sakharuk  290: 
1.3       sakharuk  291: sub xmlparse {
1.172     albertel  292:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
1.96      albertel  293: 
1.172     albertel  294:  &setup_globals($request,$target);
1.232     albertel  295:  &Apache::inputtags::initialize_inputtags();
1.370     albertel  296:  &Apache::bridgetask::initialize_bridgetask();
1.232     albertel  297:  &Apache::outputtags::initialize_outputtags();
                    298:  &Apache::edit::initialize_edit();
1.287     albertel  299:  &Apache::londefdef::initialize_londefdef();
1.244     albertel  300: 
1.178     www       301: #
                    302: # do we have a course style file?
                    303: #
                    304: 
1.372     albertel  305:  if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
1.178     www       306:      my $bodytext=
1.372     albertel  307: 	 $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
1.178     www       308:      if ($bodytext) {
1.337     albertel  309: 	 foreach my $file (split(',',$bodytext)) {
                    310: 	     my $location=&Apache::lonnet::filelocation('',$file);
                    311: 	     my $styletext=&Apache::lonnet::getfile($location);
                    312: 	     if ($styletext ne '-1') {
                    313: 		 %style_for_target = (%style_for_target,
                    314: 				      &Apache::style::styleparser($target,$styletext));
                    315: 	     }
                    316: 	 }
                    317:      }
1.372     albertel  318:  } elsif ($env{'construct.style'} && ($env{'request.state'} eq 'construct')) {
                    319:      my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
1.291     sakharuk  320:      my $styletext=&Apache::lonnet::getfile($location);
                    321:        if ($styletext ne '-1') {
                    322:           %style_for_target = (%style_for_target,
                    323:                           &Apache::style::styleparser($target,$styletext));
                    324:       }
1.178     www       325:  }
1.255     sakharuk  326: #&printalltags();
1.16      albertel  327:  my @pars = ();
1.372     albertel  328:  my $pwd=$env{'request.filename'};
1.23      albertel  329:  $pwd =~ s:/[^/]*$::;
                    330:  &newparser(\@pars,\$content_file_string,$pwd);
1.24      sakharuk  331: 
1.3       sakharuk  332:  my $safeeval = new Safe;
1.40      albertel  333:  my $safehole = new Safe::Hole;
1.82      ng        334:  &init_safespace($target,$safeeval,$safehole,$safeinit);
1.3       sakharuk  335: #-------------------- Redefinition of the target in the case of compound target
                    336: 
                    337:  ($target, my @tenta) = split('&&',$target);
                    338: 
1.150     albertel  339:  my @stack = ();
1.3       sakharuk  340:  my @parstack = ();
1.358     albertel  341:  &initdepth();
                    342:  &init_alarm();
1.101     albertel  343:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
1.394     albertel  344: 				   $safeeval,\%style_for_target,1);
1.255     sakharuk  345: 
1.425     albertel  346:  if (@stack) {
                    347:      &warning("At end of file some tags were still left unclosed, ".
                    348: 	      '<tt>&lt;'.join('&gt;</tt>, <tt>&lt;',reverse(@stack)).
                    349: 	      '&gt;</tt>');
                    350:  }
1.372     albertel  351:  if ($env{'request.uri'}) {
                    352:     &writeallows($env{'request.uri'});
1.125     www       353:  }
1.281     albertel  354:  &do_registered_ssi();
1.204     albertel  355:  if ($Apache::lonxml::counter_changed) { &store_counter() }
1.393     albertel  356: 
                    357:  &clean_safespace($safeeval);
                    358: 
1.372     albertel  359:  if ($env{'form.return_only_error_and_warning_counts'}) {
1.361     www       360:      return "$errorcount:$warningcount";
                    361:  }
1.3       sakharuk  362:  return $finaloutput;
1.106     www       363: }
                    364: 
1.191     albertel  365: sub latex_special_symbols {
1.272     albertel  366:     my ($string,$where)=@_;
1.396     foxr      367:     #
                    368:     #  If e.g. in verbatim mode, then don't substitute.
                    369:     #  but return original string.
                    370:     #
                    371:     if (!($Apache::lonxml::substitute_LaTeX_symbols)) {
                    372: 	return $string;
                    373:     }
1.235     sakharuk  374:     if ($where eq 'header') {
1.414     foxr      375: 	$string =~ s/\\/\$\\backslash\$/g; # \  -> $\backslash$ per LaTex line by line pg  10.
1.311     albertel  376: 	$string =~ s/(\$|%|\{|\})/\\$1/g;
                    377: 	$string=&Apache::lonprintout::character_chart($string);
                    378: 	# any & or # leftover should be safe to just escape
                    379:         $string=~s/([^\\])\&/$1\\\&/g;
                    380:         $string=~s/([^\\])\#/$1\\\#/g;
1.415     foxr      381: 	$string =~ s/_/\\_/g;              # _ -> \_
                    382: 	$string =~ s/\^/\\\^{}/g;          # ^ -> \^{} 
1.229     sakharuk  383:     } else {
1.312     albertel  384: 	$string=~s/\\/\\ensuremath{\\backslash}/g;
1.367     albertel  385: 	$string=~s/\\\%|\%/\\\%/g;
                    386: 	$string=~s/\\{|{/\\{/g;
                    387: 	$string=~s/\\}|}/\\}/g;
1.378     albertel  388: 	$string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
1.367     albertel  389: 	$string=~s/\\\$|\$/\\\$/g;
                    390: 	$string=~s/\\\_|\_/\\\_/g;
1.313     albertel  391:         $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
1.310     sakharuk  392: 	$string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
1.311     albertel  393: 	$string=&Apache::lonprintout::character_chart($string);
                    394: 	# any & or # leftover should be safe to just escape
1.367     albertel  395: 	$string=~s/\\\&|\&/\\\&/g;
                    396: 	$string=~s/\\\#|\#/\\\#/g;
1.332     sakharuk  397:         $string=~s/\|/\$\\mid\$/g;
1.310     sakharuk  398: #single { or } How to escape?
1.229     sakharuk  399:     }
1.272     albertel  400:     return $string;
1.188     sakharuk  401: }
                    402: 
1.101     albertel  403: sub inner_xmlparse {
1.394     albertel  404:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target,$start)=@_;
1.101     albertel  405:   my $finaloutput = '';
                    406:   my $result;
                    407:   my $token;
1.258     albertel  408:   my $dontpop=0;
1.389     albertel  409:   my $startredirection = $Apache::lonxml::redirection;
1.101     albertel  410:   while ( $#$pars > -1 ) {
                    411:     while ($token = $$pars['-1']->get_token) {
1.261     albertel  412:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
1.101     albertel  413: 	if ($metamode<1) {
1.190     albertel  414: 	    my $text=$token->[1];
1.193     albertel  415: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
1.239     sakharuk  416: 		$text = '';
                    417: #		$text = '%'.$text."\n";
1.182     sakharuk  418: 	    }
1.190     albertel  419: 	    $result.=$text;
1.101     albertel  420: 	}
1.261     albertel  421:       } elsif (($token->[0] eq 'D')) {
                    422: 	if ($metamode<1 && $target eq 'web') {
                    423: 	    my $text=$token->[1];
                    424: 	    $result.=$text;
                    425: 	}
1.101     albertel  426:       } elsif ($token->[0] eq 'PI') {
1.261     albertel  427: 	if ($metamode<1 && $target eq 'web') {
1.101     albertel  428: 	  $result=$token->[2];
                    429: 	}
                    430:       } elsif ($token->[0] eq 'S') {
1.140     albertel  431: 	# add tag to stack
1.101     albertel  432: 	push (@$stack,$token->[1]);
                    433: 	# add parameters list to another stack
                    434: 	push (@$parstack,&parstring($token));
1.140     albertel  435: 	&increasedepth($token);
1.212     albertel  436: 	if ($Apache::lonxml::usestyle &&
                    437: 	    exists($$style_for_target{$token->[1]})) {
                    438: 	    $Apache::lonxml::usestyle=0;
                    439: 	    my $string=$$style_for_target{$token->[1]}.
                    440: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
                    441: 	    &Apache::lonxml::newparser($pars,\$string);
1.257     albertel  442: 	    $Apache::lonxml::style_values=$$parstack[-1];
1.259     albertel  443: 	    $Apache::lonxml::style_end_values=$$parstack[-1];
1.101     albertel  444: 	} else {
                    445: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
                    446: 			     $parstack, $pars, $safeeval, $style_for_target);
1.140     albertel  447: 	}
1.101     albertel  448:       } elsif ($token->[0] eq 'E') {
1.212     albertel  449: 	if ($Apache::lonxml::usestyle &&
                    450: 	    exists($$style_for_target{'/'."$token->[1]"})) {
                    451: 	    $Apache::lonxml::usestyle=0;
                    452: 	    my $string=$$style_for_target{'/'.$token->[1]}.
1.258     albertel  453: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
1.212     albertel  454: 	    &Apache::lonxml::newparser($pars,\$string);
1.259     albertel  455: 	    $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
                    456: 	    $Apache::lonxml::style_end_values='';
1.258     albertel  457: 	    $dontpop=1;
1.101     albertel  458: 	} else {
1.258     albertel  459: 	    #clear out any tags that didn't end
                    460: 	    while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
                    461: 		my $lasttag=$$stack[-1];
1.317     albertel  462: 		if ($token->[1] =~ /^\Q$lasttag\E$/i) {
1.258     albertel  463: 		    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' as end tag to &lt;'.$$stack[-1].'&gt;');
                    464: 		    last;
                    465: 		} else {
                    466: 		    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; on line '.$token->[3].' when looking for &lt;/'.$$stack[-1].'&gt; in file');
                    467: 		    &end_tag($stack,$parstack,$token);
                    468: 		}
                    469: 	    }
                    470: 	    $result = &callsub("end_$token->[1]", $target, $token, $stack,
                    471: 			       $parstack, $pars,$safeeval, $style_for_target);
1.101     albertel  472: 	}
                    473:       } else {
                    474: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
                    475:       }
                    476:       #evaluate variable refs in result
1.282     albertel  477:       if ($Apache::lonxml::post_evaluate &&$result ne "") {
1.257     albertel  478: 	  my $extras;
                    479: 	  if (!$Apache::lonxml::usestyle) {
                    480: 	      $extras=$Apache::lonxml::style_values;
                    481: 	  }
1.101     albertel  482: 	if ( $#$parstack > -1 ) {
1.257     albertel  483: 	  $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
1.101     albertel  484: 	} else {
1.257     albertel  485: 	  $result= &Apache::run::evaluate($result,$safeeval,$extras);
1.101     albertel  486: 	}
1.163     albertel  487:       }
1.282     albertel  488:       $Apache::lonxml::post_evaluate=1;
                    489: 
1.190     albertel  490:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
1.249     albertel  491: 	  #Style file definitions should be correct
1.250     albertel  492: 	  if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
1.311     albertel  493: 	      $result=&latex_special_symbols($result);
1.249     albertel  494: 	  }
1.190     albertel  495:       }
                    496: 
1.169     albertel  497:       if ($Apache::lonxml::redirection) {
                    498: 	$Apache::lonxml::outputstack['-1'] .= $result;
                    499:       } else {
                    500: 	$finaloutput.=$result;
                    501:       }
                    502:       $result = '';
                    503: 
1.258     albertel  504:       if ($token->[0] eq 'E' && !$dontpop) {
1.101     albertel  505: 	&end_tag($stack,$parstack,$token);
                    506:       }
1.258     albertel  507:       $dontpop=0;
1.224     albertel  508:     }	
1.212     albertel  509:     if ($#$pars > -1) {
                    510: 	pop @$pars;
                    511: 	pop @Apache::lonxml::pwd;
                    512:     }
1.101     albertel  513:   }
                    514: 
                    515:   # if ($target eq 'meta') {
                    516:   #   $finaloutput.=&endredirection;
                    517:   # }
                    518: 
1.394     albertel  519:   if ( $start && $target eq 'grade') { &endredirection(); }
1.389     albertel  520:   if ( $Apache::lonxml::redirection > $startredirection) {
                    521:       while ($Apache::lonxml::redirection > $startredirection) {
                    522: 	  $finaloutput .= &endredirection();
1.387     albertel  523:       }
                    524:   }
1.101     albertel  525:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
                    526:     $finaloutput=&afterburn($finaloutput);
1.216     sakharuk  527:   }	    
1.101     albertel  528:   return $finaloutput;
                    529: }
1.67      www       530: 
1.318     matthew   531: ## 
                    532: ## Looks to see if there is a subroutine defined for this tag.  If so, call it,
                    533: ## otherwise do not call it as we do not know what it is.
                    534: ##
1.7       albertel  535: sub callsub {
1.84      albertel  536:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.7       albertel  537:   my $currentstring='';
1.72      albertel  538:   my $nodefault;
1.7       albertel  539:   {
1.59      albertel  540:     my $sub1;
1.7       albertel  541:     no strict 'refs';
1.68      www       542:     my $tag=$token->[1];
1.236     www       543: # get utterly rid of extended html tags
                    544:     if ($tag=~/^x\-/i) { return ''; }
1.141     albertel  545:     my $space=$Apache::lonxml::alltags{$tag}[-1];
1.68      www       546:     if (!$space) {
1.141     albertel  547:      	$tag=~tr/A-Z/a-z/;
1.68      www       548: 	$sub=~tr/A-Z/a-z/;
1.141     albertel  549: 	$space=$Apache::lonxml::alltags{$tag}[-1]
1.68      www       550:     }
1.97      albertel  551: 
                    552:     my $deleted=0;
                    553:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
                    554:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
                    555: 					     $parstack,$parser,$safeeval,
                    556: 					     $style);
                    557:     }
                    558:     if (!$deleted) {
                    559:       if ($space) {
1.220     albertel  560: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
1.97      albertel  561: 	$sub1="$space\:\:$sub";
                    562: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
                    563: 					     $parstack,$parser,$safeeval,
                    564: 					     $style);
                    565:       } else {
1.318     matthew   566:           if ($target eq 'tex') {
                    567:               # throw away tag name
                    568:               return '';
                    569:           }
1.220     albertel  570: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
1.97      albertel  571: 	if ($metamode <1) {
                    572: 	  if (defined($token->[4]) && ($metamode < 1)) {
                    573: 	    $currentstring = $token->[4];
                    574: 	  } else {
                    575: 	    $currentstring = $token->[2];
                    576: 	  }
1.62      sakharuk  577: 	}
1.7       albertel  578:       }
1.97      albertel  579:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
                    580:       if ($currentstring eq '' && $nodefault eq '') {
                    581: 	if ($target eq 'edit') {
1.220     albertel  582: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
1.97      albertel  583: 	  if ($token->[0] eq 'S') {
                    584: 	    $currentstring = &Apache::edit::tag_start($target,$token);
                    585: 	  } elsif ($token->[0] eq 'E') {
                    586: 	    $currentstring = &Apache::edit::tag_end($target,$token);
                    587: 	  }
                    588: 	} elsif ($target eq 'modified') {
                    589: 	  if ($token->[0] eq 'S') {
                    590: 	    $currentstring = $token->[4];
                    591: 	    $currentstring.=&Apache::edit::handle_insert();
1.210     www       592: 	  } elsif ($token->[0] eq 'E') {
                    593: 	    $currentstring = $token->[2];
                    594:             $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
1.97      albertel  595: 	  } else {
                    596: 	    $currentstring = $token->[2];
                    597: 	  }
1.72      albertel  598: 	}
                    599:       }
1.7       albertel  600:     }
                    601:     use strict 'refs';
                    602:   }
                    603:   return $currentstring;
1.82      ng        604: }
                    605: 
1.96      albertel  606: sub setup_globals {
1.172     albertel  607:   my ($request,$target)=@_;
                    608:   $Apache::lonxml::request=$request;
1.205     www       609:   $errorcount=0;
                    610:   $warningcount=0;
1.207     albertel  611:   $Apache::lonxml::default_homework_loaded=0;
1.212     albertel  612:   $Apache::lonxml::usestyle=1;
1.204     albertel  613:   &init_counter();
1.101     albertel  614:   @Apache::lonxml::pwd=();
1.124     albertel  615:   @Apache::lonxml::extlinks=();
1.281     albertel  616:   @Apache::lonxml::ssi_info=();
1.282     albertel  617:   $Apache::lonxml::post_evaluate=1;
1.295     albertel  618:   $Apache::lonxml::warnings_error_header='';
1.397     albertel  619:   $Apache::lonxml::substitute_LaTeX_symbols = 1;
1.96      albertel  620:   if ($target eq 'meta') {
                    621:     $Apache::lonxml::redirection = 0;
                    622:     $Apache::lonxml::metamode = 1;
                    623:     $Apache::lonxml::evaluate = 1;
                    624:     $Apache::lonxml::import = 0;
1.129     albertel  625:   } elsif ($target eq 'answer') {
                    626:     $Apache::lonxml::redirection = 0;
                    627:     $Apache::lonxml::metamode = 1;
                    628:     $Apache::lonxml::evaluate = 1;
                    629:     $Apache::lonxml::import = 1;
1.96      albertel  630:   } elsif ($target eq 'grade') {
1.387     albertel  631:     &startredirection(); #ended in inner_xmlparse on exit
1.96      albertel  632:     $Apache::lonxml::metamode = 0;
                    633:     $Apache::lonxml::evaluate = 1;
                    634:     $Apache::lonxml::import = 1;
                    635:   } elsif ($target eq 'modified') {
                    636:     $Apache::lonxml::redirection = 0;
                    637:     $Apache::lonxml::metamode = 0;
                    638:     $Apache::lonxml::evaluate = 0;
                    639:     $Apache::lonxml::import = 0;
                    640:   } elsif ($target eq 'edit') {
                    641:     $Apache::lonxml::redirection = 0;
                    642:     $Apache::lonxml::metamode = 0;
                    643:     $Apache::lonxml::evaluate = 0;
                    644:     $Apache::lonxml::import = 0;
1.163     albertel  645:   } elsif ($target eq 'analyze') {
                    646:     $Apache::lonxml::redirection = 0;
                    647:     $Apache::lonxml::metamode = 0;
                    648:     $Apache::lonxml::evaluate = 1;
                    649:     $Apache::lonxml::import = 1;
1.96      albertel  650:   } else {
                    651:     $Apache::lonxml::redirection = 0;
                    652:     $Apache::lonxml::metamode = 0;
                    653:     $Apache::lonxml::evaluate = 1;
                    654:     $Apache::lonxml::import = 1;
                    655:   }
                    656: }
                    657: 
1.82      ng        658: sub init_safespace {
                    659:   my ($target,$safeeval,$safehole,$safeinit) = @_;
1.393     albertel  660:   $safeeval->deny_only(':dangerous');
                    661:   $safeeval->reval('use Math::Complex;');
1.383     albertel  662:   $safeeval->permit_only(":default");
1.82      ng        663:   $safeeval->permit("entereval");
                    664:   $safeeval->permit(":base_math");
                    665:   $safeeval->permit("sort");
1.286     albertel  666:   $safeeval->permit("time");
1.371     albertel  667:   $safeeval->deny("rand");
                    668:   $safeeval->deny("srand");
1.82      ng        669:   $safeeval->deny(":base_io");
1.102     albertel  670:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
1.251     albertel  671:   $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
1.82      ng        672:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
1.324     albertel  673:   $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
                    674: 		  '&chem_standard_order');
1.369     albertel  675:   $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
1.324     albertel  676: 
1.431     www       677:   $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
1.432     www       678:   $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
1.433     albertel  679:   $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
                    680: 		  '&maxima_cas_formula_fix');
                    681: 
                    682:   $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
                    683: 		  '&capa_formula_fix');
1.431     www       684: 
1.82      ng        685:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
                    686:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
                    687:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
                    688:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
                    689:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
                    690:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
                    691:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
                    692:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
                    693:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
                    694:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
                    695:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
                    696:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
                    697:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
                    698:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
                    699:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
                    700:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
                    701:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
                    702:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
                    703:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
1.215     albertel  704:   
                    705:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
                    706:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
                    707:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
                    708:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
                    709:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
                    710:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
                    711:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
                    712:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
                    713:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
                    714:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
                    715:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
                    716:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
                    717:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
                    718:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
                    719:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
                    720:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
                    721:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
                    722:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
                    723:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
                    724:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
                    725:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
                    726:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
                    727: 
1.383     albertel  728:   $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
                    729:   $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
                    730: 		  '&Math::Cephes::Matrix::new');
                    731:   $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
                    732: 		  '&Math::Cephes::Matrix::coef');
                    733:   $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
                    734: 		  '&Math::Cephes::Matrix::clr');
                    735:   $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
                    736: 		  '&Math::Cephes::Matrix::add');
                    737:   $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
                    738: 		  '&Math::Cephes::Matrix::sub');
                    739:   $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
                    740: 		  '&Math::Cephes::Matrix::mul');
                    741:   $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
                    742: 		  '&Math::Cephes::Matrix::div');
                    743:   $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
                    744: 		  '&Math::Cephes::Matrix::inv');
                    745:   $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
                    746: 		  '&Math::Cephes::Matrix::transp');
                    747:   $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
                    748: 		  '&Math::Cephes::Matrix::simq');
                    749:   $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
                    750: 		  '&Math::Cephes::Matrix::mat_to_vec');
                    751:   $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
                    752: 		  '&Math::Cephes::Matrix::vec_to_mat');
                    753:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
                    754: 		  '&Math::Cephes::Matrix::check');
                    755:   $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
                    756: 		  '&Math::Cephes::Matrix::check');
                    757: 
1.215     albertel  758: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
                    759: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
                    760: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
                    761: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
                    762: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
                    763: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
                    764: 
1.91      ng        765:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
                    766:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
                    767:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
                    768:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
                    769:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
                    770:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
                    771:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
                    772:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
                    773:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
                    774:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
                    775:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
1.93      ng        776:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
1.91      ng        777:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
                    778:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
                    779:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
                    780:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
                    781:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
                    782:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
                    783:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
                    784:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
                    785:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
1.305     albertel  786:   $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
1.311     albertel  787:   $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
1.420     albertel  788:   $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
                    789:   $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
1.322     albertel  790:   $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
1.430     albertel  791: #  use Data::Dumper;
                    792: #  $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
1.82      ng        793: #need to inspect this class of ops
                    794: # $safeeval->deny(":base_orig");
1.331     albertel  795:   $safeeval->permit("require");
1.91      ng        796:   $safeinit .= ';$external::target="'.$target.'";';
1.82      ng        797:   &Apache::run::run($safeinit,$safeeval);
1.373     albertel  798:   &initialize_rndseed($safeeval);
                    799: }
1.303     albertel  800: 
1.393     albertel  801: sub clean_safespace {
                    802:     my ($safeeval) = @_;
                    803:     delete_package_recurse($safeeval->{Root});
                    804: }
                    805: 
                    806: sub delete_package_recurse {
                    807:      my ($package) = @_;
                    808:      my @subp;
                    809:      {
                    810: 	 no strict 'refs';
                    811: 	 while (my ($key,$val) = each(%{*{"$package\::"}})) {
                    812: 	     if (!defined($val)) { next; }
                    813: 	     local (*ENTRY) = $val;
                    814: 	     if (defined *ENTRY{HASH} && $key =~ /::$/ &&
                    815: 		 $key ne "main::" && $key ne "<none>::")
                    816: 	     {
                    817: 		 my ($p) = $package ne "main" ? "$package\::" : "";
                    818: 		 ($p .= $key) =~ s/::$//;
                    819: 		 push(@subp,$p);
                    820: 	     }
                    821: 	 }
                    822:      }
                    823:      foreach my $p (@subp) {
                    824: 	 delete_package_recurse($p);
                    825:      }
                    826:      Symbol::delete_package($package);
                    827: }
                    828: 
1.373     albertel  829: sub initialize_rndseed {
                    830:     my ($safeeval)=@_;
                    831:     my $rndseed;
1.423     albertel  832:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
1.373     albertel  833:     $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
                    834:     my $safeinit = '$external::randomseed="'.$rndseed.'";';
                    835:     &Apache::lonxml::debug("Setting rndseed to $rndseed");
                    836:     &Apache::run::run($safeinit,$safeeval);
1.207     albertel  837: }
                    838: 
                    839: sub default_homework_load {
                    840:     my ($safeeval)=@_;
                    841:     &Apache::lonxml::debug('Loading default_homework');
                    842:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
1.241     albertel  843:     if ($default eq -1) {
1.207     albertel  844: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
                    845:     } else {
                    846: 	&Apache::run::run($default,$safeeval);
                    847: 	$Apache::lonxml::default_homework_loaded=1;
                    848:     }
1.17      albertel  849: }
                    850: 
1.358     albertel  851: {
                    852:     my $alarm_depth;
                    853:     sub init_alarm {
                    854: 	alarm(0);
                    855: 	$alarm_depth=0;
                    856:     }
                    857: 
                    858:     sub start_alarm {
                    859: 	if ($alarm_depth<1) {
                    860: 	    my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
                    861: 	    if ($old) {
                    862: 		&Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
                    863: 	    }
                    864: 	}
                    865: 	$alarm_depth++;
                    866:     }
                    867: 
                    868:     sub end_alarm {
                    869: 	$alarm_depth--;
                    870: 	if ($alarm_depth<1) { alarm(0); }
                    871:     }
                    872: }
1.328     albertel  873: my $metamode_was;
1.55      albertel  874: sub startredirection {
1.328     albertel  875:     if (!$Apache::lonxml::redirection) {
                    876: 	$metamode_was=$Apache::lonxml::metamode;
                    877:     }
                    878:     $Apache::lonxml::metamode=0;
                    879:     $Apache::lonxml::redirection++;
                    880:     push (@Apache::lonxml::outputstack, '');
1.55      albertel  881: }
                    882: 
                    883: sub endredirection {
1.328     albertel  884:     if (!$Apache::lonxml::redirection) {
1.380     www       885: 	&Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
1.328     albertel  886: 	return '';
                    887:     }
                    888:     $Apache::lonxml::redirection--;
                    889:     if (!$Apache::lonxml::redirection) {
                    890: 	$Apache::lonxml::metamode=$metamode_was;
                    891:     }
                    892:     pop @Apache::lonxml::outputstack;
1.97      albertel  893: }
                    894: 
                    895: sub end_tag {
                    896:   my ($tagstack,$parstack,$token)=@_;
                    897:   pop(@$tagstack);
                    898:   pop(@$parstack);
                    899:   &decreasedepth($token);
1.55      albertel  900: }
                    901: 
1.17      albertel  902: sub initdepth {
                    903:   @Apache::lonxml::depthcounter=();
                    904:   $Apache::lonxml::depth=-1;
                    905:   $Apache::lonxml::olddepth=-1;
                    906: }
                    907: 
1.438   ! albertel  908: 
1.339     albertel  909: my @timers;
                    910: my $lasttime;
1.438   ! albertel  911: # $Apache::lonxml::depth -> current stack depth
        !           912: # @Apache::lonxml::depthcounter -> count of tags that exist so
        !           913: #                                  far at each level
        !           914: # $Apache::lonxml::olddepth -> when ascending, need to remember the count for the level below the current level (for example going from 1_2 -> 1 -> 1_3 need to rember that ) 
        !           915: 
1.17      albertel  916: sub increasedepth {
1.19      albertel  917:   my ($token) = @_;
1.17      albertel  918:   $Apache::lonxml::depth++;
                    919:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
                    920:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
                    921:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
                    922:   }
1.340     albertel  923:   my $time;
                    924:   if ($Apache::lonxml::debug eq "1") {
                    925:       push(@timers,[&gettimeofday()]);
                    926:       $time=&tv_interval($lasttime);
                    927:       $lasttime=[&gettimeofday()];
                    928:   }
1.339     albertel  929:   my $spacing='  'x($Apache::lonxml::depth-1);
1.438   ! albertel  930:   $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
        !           931:   &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
1.54      albertel  932: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
1.17      albertel  933: }
                    934: 
                    935: sub decreasedepth {
1.19      albertel  936:   my ($token) = @_;
1.17      albertel  937:   $Apache::lonxml::depth--;
1.36      albertel  938:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
                    939:     $#Apache::lonxml::depthcounter--;
                    940:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
                    941:   }
1.43      albertel  942:   if (  $Apache::lonxml::depth < -1) {
1.280     www       943:     &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
1.43      albertel  944:     $Apache::lonxml::depth='-1';
                    945:   }
1.340     albertel  946:   my ($timer,$time);
                    947:   if ($Apache::lonxml::debug eq "1") {
                    948:       $timer=pop(@timers);
                    949:       $time=&tv_interval($lasttime);
                    950:       $lasttime=[&gettimeofday()];
                    951:   }
1.339     albertel  952:   my $spacing='  'x$Apache::lonxml::depth;
1.438   ! albertel  953:   $Apache::lonxml::curdepth=
        !           954:       join('_',@Apache::lonxml::depthcounter[0..$Apache::lonxml::depth]);
        !           955:   &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
1.54      albertel  956: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
1.1       sakharuk  957: }
1.19      albertel  958: 
1.399     albertel  959: sub get_id {
                    960:     my ($parstack,$safeeval)=@_;
                    961:     my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
                    962:     if ($env{'request.state'} eq 'construct' && $id =~ /(\.|_)/) {
                    963: 	&error(&mt("IDs are not allowed to contain &quot;<tt>_</tt>&quot; or &quot;<tt>.</tt>&quot;"));
                    964:     }
                    965:     if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
                    966:     return $id;
                    967: }
                    968: 
1.180     albertel  969: sub get_all_text_unbalanced {
1.190     albertel  970: #there is a copy of this in lonpublisher.pm
1.326     albertel  971:     my($tag,$pars)= @_;
                    972:     my $token;
                    973:     my $result='';
                    974:     $tag='<'.$tag.'>';
                    975:     while ($token = $$pars[-1]->get_token) {
                    976: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1.386     albertel  977: 	    if ($token->[0] eq 'T' && $token->[2]) {
1.382     albertel  978: 		$result.='<![CDATA['.$token->[1].']]>';
                    979: 	    } else {
                    980: 		$result.=$token->[1];
                    981: 	    }
1.326     albertel  982: 	} elsif ($token->[0] eq 'PI') {
                    983: 	    $result.=$token->[2];
                    984: 	} elsif ($token->[0] eq 'S') {
                    985: 	    $result.=$token->[4];
                    986: 	} elsif ($token->[0] eq 'E')  {
                    987: 	    $result.=$token->[2];
                    988: 	}
                    989: 	if ($result =~ /\Q$tag\E/is) {
                    990: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
                    991: 	    #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
                    992: 	    #&Apache::lonxml::debug('Result is :'.$1);
                    993: 	    $redo=$tag.$redo;
                    994: 	    &Apache::lonxml::newparser($pars,\$redo);
                    995: 	    last;
                    996: 	}
                    997:     }
                    998:     return $result
1.204     albertel  999: }
                   1000: 
                   1001: sub increment_counter {
1.247     albertel 1002:     my ($increment) = @_;
1.289     sakharuk 1003:     if (defined($increment) && $increment gt 0) {
                   1004: 	$Apache::lonxml::counter+=$increment;
                   1005:     } else {
                   1006: 	$Apache::lonxml::counter++;
1.247     albertel 1007:     }
1.289     sakharuk 1008:     $Apache::lonxml::counter_changed=1;
1.204     albertel 1009: }
                   1010: 
                   1011: sub init_counter {
1.391     albertel 1012:     if ($env{'request.state'} eq 'construct') {
                   1013: 	$Apache::lonxml::counter=1;
                   1014: 	$Apache::lonxml::counter_changed=1;
                   1015:     } elsif (defined($env{'form.counter'})) {
1.372     albertel 1016: 	$Apache::lonxml::counter=$env{'form.counter'};
1.247     albertel 1017: 	$Apache::lonxml::counter_changed=0;
1.237     sakharuk 1018:     } else {
1.204     albertel 1019: 	$Apache::lonxml::counter=1;
1.247     albertel 1020: 	$Apache::lonxml::counter_changed=1;
1.204     albertel 1021:     }
                   1022: }
                   1023: 
                   1024: sub store_counter {
                   1025:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
1.401     albertel 1026:     $Apache::lonxml::counter_changed=0;
1.204     albertel 1027:     return '';
1.180     albertel 1028: }
                   1029: 
1.398     albertel 1030: {
                   1031:     my $state;
                   1032:     sub clear_problem_counter {
                   1033: 	undef($state);
                   1034: 	&Apache::lonnet::delenv('form.counter');
                   1035: 	&Apache::lonxml::init_counter();
                   1036: 	&Apache::lonxml::store_counter();
                   1037:     }
                   1038: 
                   1039:     sub remember_problem_counter {
1.422     albertel 1040: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1.398     albertel 1041: 	$state = $env{'form.counter'};
                   1042:     }
                   1043: 
                   1044:     sub restore_problem_counter {
                   1045: 	if (defined($state)) {
                   1046: 	    &Apache::lonnet::appenv(('form.counter' => $state));
                   1047: 	}
                   1048:     }
1.401     albertel 1049:     sub get_problem_counter {
                   1050: 	if ($Apache::lonxml::counter_changed) { &store_counter() }
1.422     albertel 1051: 	&Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1.401     albertel 1052: 	return $env{'form.counter'};
                   1053:     }
1.398     albertel 1054: }
                   1055: 
1.19      albertel 1056: sub get_all_text {
1.270     albertel 1057:     my($tag,$pars,$style)= @_;
                   1058:     my $gotfullstack=1;
                   1059:     if (ref($pars) ne 'ARRAY') {
                   1060: 	$gotfullstack=0;
                   1061: 	$pars=[$pars];
                   1062:     }
                   1063:     if (ref($style) ne 'HASH') {
                   1064: 	$style={};
                   1065:     }
                   1066:     my $depth=0;
                   1067:     my $token;
                   1068:     my $result='';
                   1069:     if ( $tag =~ m:^/: ) { 
                   1070: 	my $tag=substr($tag,1); 
                   1071: 	#&Apache::lonxml::debug("have:$tag:");
                   1072: 	my $top_empty=0;
                   1073: 	while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
                   1074: 	    while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
                   1075: 		#&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
                   1076: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1.382     albertel 1077: 		    if ($token->[2]) {
                   1078: 			$result.='<![CDATA['.$token->[1].']]>';
                   1079: 		    } else {
                   1080: 			$result.=$token->[1];
                   1081: 		    }
1.270     albertel 1082: 		} elsif ($token->[0] eq 'PI') {
                   1083: 		    $result.=$token->[2];
                   1084: 		} elsif ($token->[0] eq 'S') {
1.316     albertel 1085: 		    if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
                   1086: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
                   1087: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1.270     albertel 1088: 		    $result.=$token->[4];
                   1089: 		} elsif ($token->[0] eq 'E')  {
1.316     albertel 1090: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
1.270     albertel 1091: 		    #skip sending back the last end tag
1.283     albertel 1092: 		    if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
1.270     albertel 1093: 			my $string=
                   1094: 			    '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
                   1095: 				$$style{'/'.$token->[1]}.
                   1096: 				    $token->[2].
                   1097: 					'<LONCAPA_INTERNAL_TURN_STYLE_ON />';
                   1098: 			&Apache::lonxml::newparser($pars,\$string);
                   1099: 			#&Apache::lonxml::debug("reParsing $string");
                   1100: 			next;
                   1101: 		    }
                   1102: 		    if ($depth > -1) {
                   1103: 			$result.=$token->[2];
                   1104: 		    } else {
                   1105: 			$$pars[-1]->unget_token($token);
                   1106: 		    }
                   1107: 		}
                   1108: 	    }
                   1109: 	    if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
                   1110: 	    if (($depth >=0) && ($#$pars > 0) ) {
                   1111: 		pop(@$pars);
                   1112: 		pop(@Apache::lonxml::pwd);
                   1113: 	    }
                   1114: 	}
                   1115: 	if ($top_empty && $depth >= 0) {
                   1116: 	    #never found the end tag ran out of text, throw error send back blank
                   1117: 	    &error('Never found end tag for &lt;'.$tag.
                   1118: 		   '&gt; current string <pre>'.
1.314     albertel 1119: 		   &HTML::Entities::encode($result,'<>&"').
1.270     albertel 1120: 		   '</pre>');
                   1121: 	    if ($gotfullstack) {
                   1122: 		my $newstring='</'.$tag.'>'.$result;
                   1123: 		&Apache::lonxml::newparser($pars,\$newstring);
                   1124: 	    }
                   1125: 	    $result='';
                   1126: 	}
                   1127:     } else {
                   1128: 	while ($#$pars > -1) {
                   1129: 	    while ($token = $$pars[-1]->get_token) {
                   1130: 		#&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
                   1131: 		if (($token->[0] eq 'T')||($token->[0] eq 'C')||
                   1132: 		    ($token->[0] eq 'D')) {
1.382     albertel 1133: 		    if ($token->[2]) {
                   1134: 			$result.='<![CDATA['.$token->[1].']]>';
                   1135: 		    } else {
                   1136: 			$result.=$token->[1];
                   1137: 		    }
1.270     albertel 1138: 		} elsif ($token->[0] eq 'PI') {
                   1139: 		    $result.=$token->[2];
                   1140: 		} elsif ($token->[0] eq 'S') {
1.316     albertel 1141: 		    if ( $token->[1] =~ /^\Q$tag\E$/i) {
1.270     albertel 1142: 			$$pars[-1]->unget_token($token); last;
                   1143: 		    } else {
                   1144: 			$result.=$token->[4];
                   1145: 		    }
1.316     albertel 1146: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
                   1147: 		    if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1.270     albertel 1148: 		} elsif ($token->[0] eq 'E')  {
                   1149: 		    $result.=$token->[2];
                   1150: 		}
                   1151: 	    }
                   1152: 	    if (($#$pars > 0) ) {
                   1153: 		pop(@$pars);
                   1154: 		pop(@Apache::lonxml::pwd);
                   1155: 	    } else { last; }
                   1156: 	}
                   1157:     }
                   1158:     #&Apache::lonxml::debug("Exit:$result:");
                   1159:     return $result
1.19      albertel 1160: }
                   1161: 
1.23      albertel 1162: sub newparser {
                   1163:   my ($parser,$contentref,$dir) = @_;
1.167     albertel 1164:   push (@$parser,HTML::LCParser->new($contentref));
1.365     albertel 1165:   $$parser[-1]->xml_mode(1);
                   1166:   $$parser[-1]->marked_sections(1);
1.23      albertel 1167:   if ( $dir eq '' ) {
                   1168:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
                   1169:   } else {
                   1170:     push (@Apache::lonxml::pwd, $dir);
                   1171:   } 
                   1172: }
1.1       sakharuk 1173: 
1.8       albertel 1174: sub parstring {
1.417     albertel 1175:     my ($token) = @_;
                   1176:     my (@vars,@values);
                   1177:     foreach my $attr (@{$token->[3]}) {
                   1178: 	if ($attr!~/\W/) {
                   1179: 	    my $val=$token->[2]->{$attr};
                   1180: 	    $val =~ s/([\%\@\\\"\'])/\\$1/g;
                   1181: 	    $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
                   1182: 	    $val =~ s/(\$)$/\\$1/;
                   1183: 	    #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
                   1184: 	    push(@vars,"\$$attr");
                   1185: 	    push(@values,"\"$val\"");
                   1186: 	}
                   1187:     }
                   1188:     my $var_init = 
                   1189: 	(@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
                   1190: 	        : '';
                   1191:     return $var_init;
1.8       albertel 1192: }
1.22      albertel 1193: 
1.384     albertel 1194: sub extlink {
                   1195:     my ($res,$exact)=@_;
                   1196:     if (!$exact) {
                   1197: 	$res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
                   1198:     }
                   1199:     push(@Apache::lonxml::extlinks,$res)	 
                   1200: }
                   1201: 
1.34      www      1202: sub writeallows {
1.126     www      1203:     unless ($#extlinks>=0) { return; }
1.377     albertel 1204:     my $thisurl = &Apache::lonnet::clutter(shift);
1.372     albertel 1205:     if ($env{'httpref.'.$thisurl}) {
                   1206: 	$thisurl=$env{'httpref.'.$thisurl};
1.111     www      1207:     }
1.34      www      1208:     my $thisdir=$thisurl;
                   1209:     $thisdir=~s/\/[^\/]+$//;
                   1210:     my %httpref=();
1.142     albertel 1211:     foreach (@extlinks) {
1.34      www      1212:        $httpref{'httpref.'.
1.125     www      1213:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
1.142     albertel 1214:     }
1.126     www      1215:     @extlinks=();
1.34      www      1216:     &Apache::lonnet::appenv(%httpref);
                   1217: }
                   1218: 
1.281     albertel 1219: sub register_ssi {
                   1220:     my ($url,%form)=@_;
                   1221:     push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
                   1222:     return '';
                   1223: }
                   1224: 
                   1225: sub do_registered_ssi {
                   1226:     foreach my $info (@Apache::lonxml::ssi_info) {
                   1227: 	my %form=%{ $info->{'form'}};
                   1228: 	my $url=$info->{'url'};
                   1229: 	&Apache::lonnet::ssi($url,%form);
                   1230:     }
                   1231: }
1.66      www      1232: #
                   1233: # Afterburner handles anchors, highlights and links
                   1234: #
                   1235: sub afterburn {
                   1236:     my $result=shift;
1.154     albertel 1237:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1238: 					    ['highlight','anchor','link']);
1.372     albertel 1239:     if ($env{'form.highlight'}) {
                   1240:        foreach (split(/\,/,$env{'form.highlight'})) {
1.66      www      1241:            my $anchorname=$_;
                   1242: 	   my $matchthis=$anchorname;
                   1243:            $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1244:            $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
1.142     albertel 1245:        }
1.66      www      1246:     }
1.372     albertel 1247:     if ($env{'form.link'}) {
                   1248:        foreach (split(/\,/,$env{'form.link'})) {
1.66      www      1249:            my ($anchorname,$linkurl)=split(/\>/,$_);
                   1250: 	   my $matchthis=$anchorname;
                   1251:            $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1252:            $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1.142     albertel 1253:        }
1.66      www      1254:     }
1.372     albertel 1255:     if ($env{'form.anchor'}) {
                   1256:         my $anchorname=$env{'form.anchor'};
1.66      www      1257: 	my $matchthis=$anchorname;
                   1258:         $matchthis=~s/\_+/\\s\+/g;
1.317     albertel 1259:         $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
1.66      www      1260:         $result.=(<<"ENDSCRIPT");
1.226     albertel 1261: <script type="text/javascript">
1.66      www      1262:     document.location.hash='$anchorname';
                   1263: </script>
                   1264: ENDSCRIPT
                   1265:     }
                   1266:     return $result;
                   1267: }
                   1268: 
1.79      www      1269: sub storefile {
                   1270:     my ($file,$contents)=@_;
1.290     albertel 1271:     &Apache::lonnet::correct_line_ends(\$contents);
1.79      www      1272:     if (my $fh=Apache::File->new('>'.$file)) {
                   1273: 	print $fh $contents;
                   1274:         $fh->close();
1.271     www      1275:         return 1;
1.147     albertel 1276:     } else {
1.271     www      1277: 	&warning("Unable to save file $file");
                   1278: 	return 0;
1.79      www      1279:     }
                   1280: }
                   1281: 
1.151     albertel 1282: sub createnewhtml {
1.321     www      1283:     my $title=&mt('Title of document goes here');
                   1284:     my $body=&mt('Body of document goes here');
                   1285:     my $filecontents=(<<SIMPLECONTENT);
1.78      www      1286: <html>
                   1287: <head>
1.321     www      1288: <title>$title</title>
1.78      www      1289: </head>
                   1290: <body bgcolor="#FFFFFF">
1.321     www      1291: $body
1.78      www      1292: </body>
                   1293: </html>
                   1294: SIMPLECONTENT
1.321     www      1295:     return $filecontents;
1.151     albertel 1296: }
                   1297: 
1.274     albertel 1298: sub createnewsty {
                   1299:   my $filecontents=(<<SIMPLECONTENT);
                   1300: <definetag name="">
                   1301:     <render>
                   1302:        <web></web>
                   1303:        <tex></tex>
                   1304:     </render>
                   1305: </definetag>
                   1306: SIMPLECONTENT
                   1307:   return $filecontents;
                   1308: }
                   1309: 
1.147     albertel 1310: 
1.151     albertel 1311: sub inserteditinfo {
1.274     albertel 1312:       my ($result,$filecontents,$filetype)=@_;
1.314     albertel 1313:       $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
1.147     albertel 1314: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
1.274     albertel 1315:       my $xml_help = '';
1.321     www      1316:       my $initialize='';
1.274     albertel 1317:       if ($filetype eq 'html') {
1.323     www      1318: 	  my $addbuttons=&Apache::lonhtmlcommon::htmlareaaddbuttons();
1.410     albertel 1319: 	  $initialize=&Apache::lonhtmlcommon::spellheader();
1.347     albertel 1320: 	  if (!&Apache::lonhtmlcommon::htmlareablocked() &&
                   1321: 	      &Apache::lonhtmlcommon::htmlareabrowser()) {
                   1322: 	      $initialize.=(<<FULLPAGE);
1.321     www      1323: <script type="text/javascript">
1.323     www      1324: $addbuttons
                   1325: 
1.321     www      1326:     HTMLArea.loadPlugin("FullPage");
                   1327: 
                   1328:     function initDocument() {
1.323     www      1329: 	var editor=new HTMLArea("filecont",config);
1.321     www      1330: 	editor.registerPlugin(FullPage);
                   1331: 	editor.generate();
                   1332:     }
                   1333: </script>
                   1334: FULLPAGE
1.347     albertel 1335:           } else {
                   1336: 	      $initialize.=(<<FULLPAGE);
                   1337: <script type="text/javascript">
                   1338: $addbuttons
                   1339:     function initDocument() {
                   1340:     }
                   1341: </script>
                   1342: FULLPAGE
                   1343: 	  }
1.321     www      1344:           $result=~s/\<body([^\>]*)\>/\<body onload="initDocument()" $1\>/i;
                   1345: 	  $xml_help=&Apache::loncommon::helpLatexCheatsheet();
1.274     albertel 1346:       }
                   1347:       my $cleanbut = '';
1.374     www      1348: 
1.254     albertel 1349:       my $titledisplay=&display_title();
1.426     banghart 1350:       my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
                   1351: 					 'vi' => 'Save and View',
1.427     banghart 1352: 					 'dv' => 'Discard Edits and View',
1.428     banghart 1353: 					 'un' => 'undo',
1.280     www      1354: 					 'ed' => 'Edit');
1.161     albertel 1355:       my $buttons=(<<BUTTONS);
1.274     albertel 1356: $cleanbut
1.428     banghart 1357: <input type="submit" name="discardview" accesskey="d"  value="$lt{'dv'}" />
                   1358: <input type="submit" name="Undo" accesskey="u"  value="$lt{'un'}" /><hr>
1.304     matthew  1359: <input type="submit" name="savethisfile" accesskey="s"  value="$lt{'st'}" />
                   1360: <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
1.161     albertel 1361: BUTTONS
1.333     www      1362:       $buttons.=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
1.78      www      1363:       my $editfooter=(<<ENDFOOTER);
1.321     www      1364: $initialize
1.78      www      1365: <hr />
                   1366: <a name="editsection" />
1.333     www      1367: <form method="post" name="xmledit">
1.240     albertel 1368: $xml_help
1.280     www      1369: <input type="hidden" name="editmode" value="$lt{'ed'}" />
1.170     www      1370: $buttons<br />
1.366     albertel 1371: <textarea style="width:100%" cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
1.170     www      1372: <br />$buttons
1.78      www      1373: <br />
                   1374: </form>
1.254     albertel 1375: $titledisplay
1.321     www      1376: </body>
1.78      www      1377: ENDFOOTER
1.147     albertel 1378: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
1.78      www      1379:       $result=~s/(\<\/body\>)/$editfooter/is;
                   1380:       return $result;
                   1381: }
                   1382: 
1.152     albertel 1383: sub get_target {
1.372     albertel 1384:   my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
                   1385:   if ( $env{'request.state'} eq 'published') {
                   1386:     if ( defined($env{'form.grade_target'})
1.152     albertel 1387: 	 && ($viewgrades == 'F' )) {
1.372     albertel 1388:       return ($env{'form.grade_target'});
                   1389:     } elsif (defined($env{'form.grade_target'})) {
                   1390:       if (($env{'form.grade_target'} eq 'web') ||
                   1391: 	  ($env{'form.grade_target'} eq 'tex') ) {
                   1392: 	return $env{'form.grade_target'}
1.153     albertel 1393:       } else {
                   1394: 	return 'web';
                   1395:       }
1.152     albertel 1396:     } else {
                   1397:       return 'web';
                   1398:     }
1.372     albertel 1399:   } elsif ($env{'request.state'} eq 'construct') {
                   1400:     if ( defined($env{'form.grade_target'})) {
                   1401:       return ($env{'form.grade_target'});
1.152     albertel 1402:     } else {
                   1403:       return 'web';
                   1404:     }
                   1405:   } else {
                   1406:     return 'web';
                   1407:   }
                   1408: }
                   1409: 
1.24      sakharuk 1410: sub handler {
1.255     sakharuk 1411:     my $request=shift;
                   1412:     
                   1413:     my $target=&get_target();
                   1414:     
1.372     albertel 1415:     $Apache::lonxml::debug=$env{'user.debug'};
1.255     sakharuk 1416:     
1.364     albertel 1417:     &Apache::loncommon::content_type($request,'text/html');
1.255     sakharuk 1418:     &Apache::loncommon::no_cache($request);
1.372     albertel 1419:     if ($env{'request.state'} eq 'published') {
1.363     albertel 1420: 	$request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                   1421: 							      'lastrevisiondate'));
                   1422:     }
1.255     sakharuk 1423:     $request->send_http_header;
                   1424:     
                   1425:     return OK if $request->header_only;
1.68      www      1426: 
                   1427: 
1.255     sakharuk 1428:     my $file=&Apache::lonnet::filelocation("",$request->uri);
1.274     albertel 1429:     my $filetype;
                   1430:     if ($file =~ /\.sty$/) {
                   1431: 	$filetype='sty';
                   1432:     } else {
                   1433: 	$filetype='html';
                   1434:     }
1.78      www      1435: #
                   1436: # Edit action? Save file.
                   1437: #
1.428     banghart 1438:     if (!($env{'request.state'} eq 'published')) {
                   1439: 	if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
1.429     albertel 1440: 	    my $html_file=&Apache::lonnet::getfile($file);
                   1441: 	    my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
1.255     sakharuk 1442: 	}
                   1443:     }
                   1444:     my %mystyle;
                   1445:     my $result = '';
                   1446:     my $filecontents=&Apache::lonnet::getfile($file);
                   1447:     if ($filecontents eq -1) {
1.402     albertel 1448: 	my $start_page=&Apache::loncommon::start_page('File Error');
1.412     albertel 1449: 	my $end_page=&Apache::loncommon::end_page();
1.284     www      1450: 	my $fnf=&mt('File not found');
1.255     sakharuk 1451: 	$result=(<<ENDNOTFOUND);
1.402     albertel 1452: $start_page
1.284     www      1453: <b>$fnf: $file</b>
1.402     albertel 1454: $end_page
1.78      www      1455: ENDNOTFOUND
1.343     albertel 1456:         $filecontents='';
1.372     albertel 1457: 	if ($env{'request.state'} ne 'published') {
1.274     albertel 1458: 	    if ($filetype eq 'sty') {
                   1459: 		$filecontents=&createnewsty();
                   1460: 	    } else {
                   1461: 		$filecontents=&createnewhtml();
                   1462: 	    }
1.372     albertel 1463: 	    $env{'form.editmode'}='Edit'; #force edit mode
1.255     sakharuk 1464: 	}
                   1465:     } else {
1.372     albertel 1466: 	unless ($env{'request.state'} eq 'published') {
1.343     albertel 1467: 	    if ($filecontents=~/BEGIN LON-CAPA Internal/) {
1.381     www      1468: 		&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 1469: 	    }
1.264     www      1470: #
                   1471: # we are in construction space, see if edit mode forced
1.385     albertel 1472:             &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1473: 						    ['editmode']);
1.255     sakharuk 1474: 	}
1.427     banghart 1475: 	if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
1.255     sakharuk 1476: 	    $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
                   1477: 						'',%mystyle);
1.368     albertel 1478: 	    undef($Apache::lonhomework::parsing_a_task);
1.385     albertel 1479: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1480: 						    ['rawmode']);
1.395     albertel 1481: 	    if ($env{'form.rawmode'}) { $result = $filecontents; }
1.255     sakharuk 1482: 	}
1.147     albertel 1483:     }
1.255     sakharuk 1484:     
1.78      www      1485: #
                   1486: # Edit action? Insert editing commands
                   1487: #
1.372     albertel 1488:     unless ($env{'request.state'} eq 'published') {
1.427     banghart 1489: 	if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
                   1490: 	    {
1.255     sakharuk 1491: 	    my $displayfile=$request->uri;
                   1492: 	    $displayfile=~s/^\/[^\/]*//;
1.402     albertel 1493: 	    my %options = ();
                   1494: 	    if ($env{'environment.remote'} ne 'off') {
                   1495: 		$options{'bgcolor'}   = '#FFFFFF';
1.349     albertel 1496: 	    }
1.402     albertel 1497: 	    my $start_page = &Apache::loncommon::start_page(undef,undef,
                   1498: 							    \%options);
                   1499: 	    $result=$start_page.
1.309     albertel 1500: 		&Apache::lonxml::message_location().'<h3>'.
                   1501: 		$displayfile.
1.402     albertel 1502: 		'</h3>'.&Apache::loncommon::end_page();
1.274     albertel 1503: 	    $result=&inserteditinfo($result,$filecontents,$filetype);
1.255     sakharuk 1504: 	}
1.147     albertel 1505:     }
1.402     albertel 1506:     if ($filetype eq 'html') { &writeallows($request->uri); }
1.274     albertel 1507: 	
1.255     sakharuk 1508:     
1.309     albertel 1509:     &Apache::lonxml::add_messages(\$result);
1.255     sakharuk 1510:     $request->print($result);
                   1511:     
                   1512:     return OK;
1.253     albertel 1513: }
                   1514: 
                   1515: sub display_title {
                   1516:     my $result;
1.372     albertel 1517:     if ($env{'request.state'} eq 'construct') {
1.253     albertel 1518: 	my $title=&Apache::lonnet::gettitle();
                   1519: 	if (!defined($title) || $title eq '') {
1.372     albertel 1520: 	    $title = $env{'request.filename'};
1.253     albertel 1521: 	    $title = substr($title, rindex($title, '/') + 1);
                   1522: 	}
                   1523: 	$result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
                   1524:     }
                   1525:     return $result;
1.24      sakharuk 1526: }
1.147     albertel 1527: 
1.22      albertel 1528: sub debug {
1.298     albertel 1529:     if ($Apache::lonxml::debug eq "1") {
                   1530: 	$|=1;
1.300     albertel 1531: 	my $request=$Apache::lonxml::request;
1.388     albertel 1532: 	if (!$request) {
                   1533: 	    eval { $request=Apache->request; };
                   1534: 	}
                   1535: 	if (!$request) {
                   1536: 	    eval { $request=Apache2::RequestUtil->request; };
                   1537: 	}
1.314     albertel 1538: 	$request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
1.346     albertel 1539: 	#&Apache::lonnet::logthis($_[0]);
1.298     albertel 1540:     }
1.22      albertel 1541: }
1.49      albertel 1542: 
1.348     albertel 1543: sub show_error_warn_msg {
1.372     albertel 1544:     if ($env{'request.filename'} eq '/home/httpd/html/res/lib/templates/simpleproblem.problem' &&
                   1545: 	&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
1.351     albertel 1546: 	return 1;
                   1547:     }
1.348     albertel 1548:     return (($Apache::lonxml::debug eq 1) ||
1.372     albertel 1549: 	    ($env{'request.state'} eq 'construct') ||
1.348     albertel 1550: 	    ($Apache::lonhomework::browse eq 'F'
                   1551: 	     &&
1.372     albertel 1552: 	     $env{'form.show_errors'} eq 'on'));
1.348     albertel 1553: }
                   1554: 
1.22      albertel 1555: sub error {
1.336     albertel 1556:     $errorcount++;
1.348     albertel 1557:     if ( &show_error_warn_msg() ) {
1.336     albertel 1558: 	# If printing in construction space, put the error inside <pre></pre>
                   1559: 	push(@Apache::lonxml::error_messages,
                   1560: 	     $Apache::lonxml::warnings_error_header.
                   1561: 	     "<b>ERROR:</b>".join("<br />\n",@_)."<br />\n");
                   1562: 	$Apache::lonxml::warnings_error_header='';
                   1563:     } else {
                   1564: 	my $errormsg;
                   1565: 	my ($symb)=&Apache::lonnet::symbread();
                   1566: 	if ( !$symb ) {
                   1567: 	    #public or browsers
                   1568: 	    $errormsg=&mt("An error occured while processing this resource. The author has been notified.");
1.403     albertel 1569: 	}
1.413     albertel 1570: 	my $host=$Apache::lonnet::perlvar{'lonHostID'};
1.416     albertel 1571: 	my $msg = join('<br />',(@_,"The error occurred on host <tt>$host</tt>"));
1.336     albertel 1572: 	#notify author
1.403     albertel 1573: 	&Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
1.336     albertel 1574: 	#notify course
1.372     albertel 1575: 	if ( $symb && $env{'request.course.id'} ) {
1.380     www      1576: 	    my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1577: 	    my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.336     albertel 1578: 	    my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
1.372     albertel 1579: 	    my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
1.435     raeburn  1580:             my $baseurl = &Apache::lonnet::clutter($declutter);
1.336     albertel 1581: 	    my @userlist;
                   1582: 	    foreach (keys %users) {
                   1583: 		my ($user,$domain) = split(/:/, $_);
                   1584: 		push(@userlist,"$user\@$domain");
1.380     www      1585: 		my $key=$declutter.'_'.$user.'_'.$domain;
                   1586: 		my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
                   1587: 						      [$key],
                   1588: 						      $cdom,$cnum);
                   1589: 		my $now=time;
                   1590: 		if ($now-$lastnotified{$key}>86400) {
1.434     raeburn  1591:                     my $title = &Apache::lonnet::gettitle($symb);
                   1592:                     my $sentmessage;
1.380     www      1593: 		    &Apache::lonmsg::user_normal_msg($user,$domain,
1.435     raeburn  1594: 		        "Error [$title]",$msg,'',$baseurl,'','',
1.434     raeburn  1595:                         \$sentmessage,$symb,$title,1);
1.380     www      1596: 		    &Apache::lonnet::put('nohist_xmlerrornotifications',
                   1597: 					 {$key => $now},
                   1598: 					 $cdom,$cnum);		
                   1599: 		}
1.336     albertel 1600: 	    }
1.372     albertel 1601: 	    if ($env{'request.role.adv'}) {
1.336     albertel 1602: 		$errormsg=&mt("An error occured while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
                   1603: 	    } else {
                   1604: 		$errormsg=&mt("An error occured while processing this resource. The instructor has been notified.");
                   1605: 	    }
                   1606: 	}
                   1607: 	push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
1.52      albertel 1608:     }
1.22      albertel 1609: }
1.49      albertel 1610: 
1.22      albertel 1611: sub warning {
1.295     albertel 1612:     $warningcount++;
1.261     albertel 1613:   
1.372     albertel 1614:     if ($env{'form.grade_target'} ne 'tex') {
1.348     albertel 1615: 	if ( &show_error_warn_msg() ) {
1.309     albertel 1616: 	    push(@Apache::lonxml::warning_messages,
                   1617: 		 $Apache::lonxml::warnings_error_header.
                   1618: 		 "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n");
1.295     albertel 1619: 	    $Apache::lonxml::warnings_error_header='';
                   1620: 	}
                   1621:     }
1.309     albertel 1622: }
                   1623: 
                   1624: sub info {
1.372     albertel 1625:     if ($env{'form.grade_target'} ne 'tex' 
                   1626: 	&& $env{'request.state'} eq 'construct') {
1.309     albertel 1627: 	push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
                   1628:     }
                   1629: }
                   1630: 
                   1631: sub message_location {
                   1632:     return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
                   1633: }
                   1634: 
                   1635: sub add_messages {
                   1636:     my ($msg)=@_;
                   1637:     my $result=join(' ',
                   1638: 		    @Apache::lonxml::info_messages,
                   1639: 		    @Apache::lonxml::error_messages,
                   1640: 		    @Apache::lonxml::warning_messages);
                   1641:     undef(@Apache::lonxml::info_messages);
                   1642:     undef(@Apache::lonxml::error_messages);
                   1643:     undef(@Apache::lonxml::warning_messages);
                   1644:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
                   1645:     $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
1.83      albertel 1646: }
                   1647: 
                   1648: sub get_param {
1.213     albertel 1649:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
                   1650:     if ( ! $context ) { $context = -1; }
                   1651:     my $args ='';
                   1652:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 1653:     if ( ! $Apache::lonxml::usestyle ) {
                   1654: 	$args=$Apache::lonxml::style_values.$args;
                   1655:     }
1.213     albertel 1656:     if ( ! $args ) { return undef; }
                   1657:     if ( $case_insensitive ) {
1.417     albertel 1658: 	if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
1.213     albertel 1659: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   1660:                                      $safeeval); #'
                   1661: 	} else {
                   1662: 	    return undef;
                   1663: 	}
                   1664:     } else {
1.417     albertel 1665: 	if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
1.213     albertel 1666: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
                   1667:                                      $safeeval); #'
                   1668: 	} else {
                   1669: 	    return undef;
                   1670: 	}
                   1671:     }
1.22      albertel 1672: }
                   1673: 
1.132     albertel 1674: sub get_param_var {
1.213     albertel 1675:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1.132     albertel 1676:   if ( ! $context ) { $context = -1; }
                   1677:   my $args ='';
                   1678:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.297     sakharuk 1679:   if ( ! $Apache::lonxml::usestyle ) {
                   1680:       $args=$Apache::lonxml::style_values.$args;
                   1681:   }
1.230     albertel 1682:   &Apache::lonxml::debug("Args are $args param is $param");
1.213     albertel 1683:   if ($case_insensitive) {
1.419     albertel 1684:       if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
1.213     albertel 1685: 	  return undef;
                   1686:       }
1.419     albertel 1687:   } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
1.132     albertel 1688:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
1.230     albertel 1689:   &Apache::lonxml::debug("first run is $value");
1.341     albertel 1690:   if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
1.230     albertel 1691:       &Apache::lonxml::debug("doing second");
                   1692:       my @result=&Apache::run::run("return $value",$safeeval,1);
                   1693:       if (!defined($result[0])) {
                   1694: 	  return $value
                   1695:       } else {
                   1696: 	  if (wantarray) { return @result; } else { return $result[0]; }
                   1697:       }
1.132     albertel 1698:   } else {
                   1699:     return $value;
                   1700:   }
                   1701: }
                   1702: 
1.438   ! albertel 1703: sub register_insert_tab {
1.75      albertel 1704:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
1.74      albertel 1705:   my $i;
1.76      albertel 1706:   my $tagnum=0;
1.74      albertel 1707:   my @order;
                   1708:   for ($i=0;$i < $#data; $i++) {
                   1709:     my $line = $data[$i];
                   1710:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
                   1711:     if ( $line =~ /TABLE/ ) { last; }
1.268     bowersj2 1712:     my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
1.135     albertel 1713:     if ($tag) {
                   1714:       $insertlist{"$tagnum.tag"} = $tag;
1.437     albertel 1715:       $insertlist{"$tag.description"} = $descrip;
                   1716:       $insertlist{"$tag.color"} = $color;
                   1717:       $insertlist{"$tag.function"} = $function;
1.135     albertel 1718:       if (!defined($show)) { $show='yes'; }
1.437     albertel 1719:       $insertlist{"$tag.show"}= $show;
                   1720:       $insertlist{"$tag.helpfile"} = $helpfile;
                   1721:       $insertlist{"$tag.helpdesc"} = $helpdesc;
1.135     albertel 1722:       $insertlist{"$tag.num"}=$tagnum;
                   1723:       $tagnum++;
                   1724:     }
1.74      albertel 1725:   }
1.76      albertel 1726:   $i++; #skipping TABLE line
                   1727:   $tagnum = 0;
1.74      albertel 1728:   for (;$i < $#data;$i++) {
                   1729:     my $line = $data[$i];
1.76      albertel 1730:     my ($mnemonic,@which) = split(/ +/,$line);
                   1731:     my $tag = $insertlist{"$tagnum.tag"};
1.144     matthew  1732:     for (my $j=0;$j <=$#which;$j++) {
1.74      albertel 1733:       if ( $which[$j] eq 'Y' ) {
1.76      albertel 1734: 	if ($insertlist{"$j.show"} ne 'no') {
1.437     albertel 1735: 	  push(@{ $insertlist{"$tag.which"} },$insertlist{"$j.tag"});
1.76      albertel 1736: 	}
1.74      albertel 1737:       }
                   1738:     }
1.76      albertel 1739:     $tagnum++;
1.74      albertel 1740:   }
                   1741: }
1.98      albertel 1742: 
1.438   ! albertel 1743: sub register_insert_xml {
        !          1744:     my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
        !          1745: 				     .'/insertlist.xml');
        !          1746:     my ($tagnum,$in_help)=(0,0);
        !          1747:     my $tag;
        !          1748:     while (my $token = $parser->get_token()) {
        !          1749: 	if ($token->[0] eq 'S') {
        !          1750: 	    my $key;
        !          1751: 	    if      ($token->[1] eq 'tag') {
        !          1752: 		$tag = $token->[2]{'name'};
        !          1753: 		$insertlist{"$tagnum.tag"} = $tag;
        !          1754: 		$insertlist{"$tag.num"}   = $tagnum;
        !          1755: 	    } elsif ($in_help && $token->[1] eq 'file') {
        !          1756: 		$key = $tag.'.helpfile';
        !          1757: 	    } elsif ($in_help && $token->[1] eq 'description') {
        !          1758: 		$key = $tag.'.helpdesc';
        !          1759: 	    } elsif ($token->[1] eq 'description' ||
        !          1760: 		     $token->[1] eq 'color'       ||
        !          1761: 		     $token->[1] eq 'show'          ) {
        !          1762: 		$key = $tag.'.'.$token->[1];
        !          1763: 	    } elsif ($token->[1] eq 'insert_sub') {
        !          1764: 		$key = $tag.'.function';
        !          1765: 	    } elsif ($token->[1] eq 'help') {
        !          1766: 		$in_help=1;
        !          1767: 	    } elsif ($token->[1] eq 'allow') {
        !          1768: 		my $allow = $parser->get_text();
        !          1769: 		foreach my $element (split(',',$allow)) {
        !          1770: 		    $element =~ s/(^\s*|\s*$ )//gx;
        !          1771: 		    push(@{ $insertlist{$tag.'.which'} },$element);
        !          1772: 		}
        !          1773: 	    }
        !          1774: 	    if (defined($key)) {
        !          1775: 		$insertlist{$key} = $parser->get_text();
        !          1776: 		$insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
        !          1777: 	    }
        !          1778: 	} elsif ($token->[0] eq 'E') {
        !          1779: 	    if      ($token->[1] eq 'tag') {
        !          1780: 		undef($tag);
        !          1781: 		$tagnum++;
        !          1782: 	    } elsif ($token->[1] eq 'help') {
        !          1783: 		undef($in_help);
        !          1784: 	    }
        !          1785: 	}
        !          1786:     }
        !          1787: }
        !          1788: 
        !          1789: sub register_insert {
        !          1790: #    &register_insert_tab(@_);
        !          1791: #    &dump_insertlist('1');
        !          1792: #    undef(%insertlist);
        !          1793:     return &register_insert_xml(@_);
        !          1794: #    &dump_insertlist('2');
        !          1795: }
        !          1796: 
        !          1797: sub dump_insertlist {
        !          1798:     my ($ext) = @_;
        !          1799:     open(XML,">/tmp/insertlist.xml.$ext");
        !          1800:     print XML ("<insertlist>");
        !          1801:     my $i=0;
        !          1802: 
        !          1803:     while (exists($insertlist{"$i.tag"})) {
        !          1804: 	my $tag = $insertlist{"$i.tag"};
        !          1805: 	print XML ("
        !          1806: \t<tag name=\"$tag\">");
        !          1807: 	if (defined($insertlist{"$tag.description"})) {
        !          1808: 	    print XML ("
        !          1809: \t\t<description>".$insertlist{"$tag.description"}."</description>");
        !          1810: 	}
        !          1811: 	if (defined($insertlist{"$tag.color"})) {
        !          1812: 	    print XML ("
        !          1813: \t\t<color>".$insertlist{"$tag.color"}."</color>");
        !          1814: 	}
        !          1815: 	if (defined($insertlist{"$tag.function"})) {
        !          1816: 	    print XML ("
        !          1817: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
        !          1818: 	}
        !          1819: 	if (defined($insertlist{"$tag.show"})
        !          1820: 	    && $insertlist{"$tag.show"} ne 'yes') {
        !          1821: 	    print XML ("
        !          1822: \t\t<show>".$insertlist{"$tag.show"}."</show>");
        !          1823: 	}
        !          1824: 	if (defined($insertlist{"$tag.helpfile"})) {
        !          1825: 	    print XML ("
        !          1826: \t\t<help>
        !          1827: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
        !          1828: 	    if ($insertlist{"$tag.helpdesc"} ne '') {
        !          1829: 		print XML ("
        !          1830: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
        !          1831: 	    }
        !          1832: 	    print XML ("
        !          1833: \t\t</help>");
        !          1834: 	}
        !          1835: 	if (defined($insertlist{"$tag.which"})) {
        !          1836: 	    print XML ("
        !          1837: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
        !          1838: 	}
        !          1839: 	print XML ("
        !          1840: \t</tag>");
        !          1841: 	$i++;
        !          1842:     }
        !          1843:     print XML ("\n</insertlist>\n");
        !          1844:     close(XML);
        !          1845: }
        !          1846: 
1.98      albertel 1847: sub description {
1.437     albertel 1848:     my ($token)=@_;
                   1849:     my $tag = &get_tag($token);
                   1850:     return $insertlist{$tag.'.description'};
1.268     bowersj2 1851: }
                   1852: 
                   1853: # Returns a list containing the help file, and the description
                   1854: sub helpinfo {
1.437     albertel 1855:     my ($token)=@_;
                   1856:     my $tag = &get_tag($token);
                   1857:     return ($insertlist{$tag.'.helpfile'}, $insertlist{$tag.'.helpdesc'});
                   1858: }
                   1859: 
                   1860: sub get_tag {
                   1861:     my ($token)=@_;
                   1862:     my $tagnum;
                   1863:     my $tag=$token->[1];
                   1864:     foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
                   1865: 	my $testtag = $namespace.'::'.$tag;
                   1866: 	$tagnum = $insertlist{"$testtag.num"};
                   1867: 	last if (defined($tagnum));
                   1868:     }
                   1869:     if (!defined($tagnum)) {
                   1870: 	$tagnum = $Apache::lonxml::insertlist{"$tag.num"};
                   1871:     }
                   1872:     return $insertlist{"$tagnum.tag"};
1.98      albertel 1873: }
1.123     albertel 1874: 
1.1       sakharuk 1875: 1;
                   1876: __END__
1.68      www      1877: 
                   1878: 

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