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

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

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