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

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

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