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

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

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