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

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

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