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

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

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