File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.240: download - view: text, annotated - select for diffs
Wed Feb 26 17:52:14 2003 UTC (21 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- the last of BUG#1146

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.240 2003/02/26 17:52:14 albertel Exp $
    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: #
   39: # last modified 06/26/00 by Alexander Sakharuk
   40: # 11/6 Gerd Kortemeyer
   41: # 6/1/1 Gerd Kortemeyer
   42: # 2/21,3/13 Guy
   43: # 3/29,5/4 Gerd Kortemeyer
   44: # 5/26 Gerd Kortemeyer
   45: # 5/27 H. K. Ng
   46: # 6/2,6/3,6/8,6/9 Gerd Kortemeyer
   47: # 6/12,6/13 H. K. Ng
   48: # 6/16 Gerd Kortemeyer
   49: # 7/27 H. K. Ng
   50: # 8/7,8/9,8/10,8/11,8/15,8/16,8/17,8/18,8/20,8/23,8/24 Gerd Kortemeyer
   51: # Guy Albertelli
   52: # 9/26 Gerd Kortemeyer
   53: # Dec Guy Albertelli
   54: # YEAR=2002
   55: # 1/1 Gerd Kortemeyer
   56: # 1/2 Matthew Hall
   57: # 1/3 Gerd Kortemeyer
   58: #
   59: 
   60: package Apache::lonxml; 
   61: use vars 
   62: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $prevent_entity_encode $errorcount $warningcount);
   63: use strict;
   64: use HTML::LCParser();
   65: use HTML::TreeBuilder();
   66: use HTML::Entities();
   67: use Safe();
   68: use Safe::Hole();
   69: use Math::Cephes();
   70: use Math::Random();
   71: use Opcode();
   72: 
   73: sub register {
   74:   my ($space,@taglist) = @_;
   75:   foreach my $temptag (@taglist) {
   76:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   77:   }
   78: }
   79: 
   80: sub deregister {
   81:   my ($space,@taglist) = @_;
   82:   foreach my $temptag (@taglist) {
   83:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   84:     if ($tempspace eq $space) {
   85:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   86:     }
   87:   }
   88:   #&printalltags();
   89: }
   90: 
   91: use Apache::Constants qw(:common);
   92: use Apache::lontexconvert();
   93: use Apache::style();
   94: use Apache::run();
   95: use Apache::londefdef();
   96: use Apache::scripttag();
   97: use Apache::edit();
   98: use Apache::lonnet();
   99: use Apache::File();
  100: use Apache::loncommon();
  101: use Apache::lonfeedback();
  102: use Apache::lonmsg();
  103: use Apache::loncacc();
  104: 
  105: #==================================================   Main subroutine: xmlparse  
  106: #debugging control, to turn on debugging modify the correct handler
  107: $Apache::lonxml::debug=0;
  108: 
  109: # keeps count of the number of warnings and errors generated in a parse
  110: $warningcount=0;
  111: $errorcount=0;
  112: 
  113: #path to the directory containing the file currently being processed
  114: @pwd=();
  115: 
  116: #these two are used for capturing a subset of the output for later processing,
  117: #don't touch them directly use &startredirection and &endredirection
  118: @outputstack = ();
  119: $redirection = 0;
  120: 
  121: #controls wheter the <import> tag actually does
  122: $import = 1;
  123: @extlinks=();
  124: 
  125: # meta mode is a bit weird only some output is to be turned off
  126: #<output> tag turns metamode off (defined in londefdef.pm)
  127: $metamode = 0;
  128: 
  129: # turns on and of run::evaluate actually derefencing var refs
  130: $evaluate = 1;
  131: 
  132: # data structure for eidt mode, determines what tags can go into what other tags
  133: %insertlist=();
  134: 
  135: # stores the list of active tag namespaces
  136: @namespace=();
  137: 
  138: # if 0 all high ASCII characters will be encoded into HTML Entities
  139: $prevent_entity_encode=0;
  140: 
  141: # has the dynamic menu been updated to know about this resource
  142: $Apache::lonxml::registered=0;
  143: 
  144: # a pointer the the Apache request object
  145: $Apache::lonxml::request='';
  146: 
  147: # a problem number counter, and check on ether it is used
  148: $Apache::lonxml::counter=1;
  149: $Apache::lonxml::counter_changed=0;
  150: 
  151: #internal check on whether to look at style defs
  152: $Apache::lonxml::usestyle=1;
  153: 
  154: sub xmlbegin {
  155:   my $output='';
  156:   if ($ENV{'browser.mathml'}) {
  157:       $output='<?xml version="1.0"?>'
  158:             .'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'
  159:             .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
  160:             .'[<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">]>'
  161:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
  162: 		.'xmlns="http://www.w3.org/TR/REC-html40">';
  163:   } else {
  164:       $output='<html>';
  165:   }
  166:   return $output;
  167: }
  168: 
  169: sub xmlend {
  170:     my ($discussiononly,$symb)=@_;
  171:     my $discussion='';
  172:     if ($ENV{'request.course.id'}) {
  173:        my $crs='/'.$ENV{'request.course.id'};
  174:        if ($ENV{'request.course.sec'}) {
  175:           $crs.='_'.$ENV{'request.course.sec'};
  176:        }                 
  177:        $crs=~s/\_/\//g;
  178:        my $seeid=&Apache::lonnet::allowed('rin',$crs);
  179:        unless ($symb) {
  180:            $symb=&Apache::lonnet::symbread();
  181:        }
  182:        if ($symb) {
  183:           my %contrib=&Apache::lonnet::restore($symb,$ENV{'request.course.id'},
  184:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  185: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  186:           if ($contrib{'version'}) {
  187:               unless ($discussiononly) {
  188:                  $discussion.=
  189:                   '<address><hr />';
  190: 	     }
  191:               my $idx;
  192:               for ($idx=1;$idx<=$contrib{'version'};$idx++) {
  193: 		my $hidden=($contrib{'hidden'}=~/\.$idx\./);
  194: 		my $deleted=($contrib{'deleted'}=~/\.$idx\./);
  195: 		unless ((($hidden) && (!$seeid)) || ($deleted)) {
  196:                  my $message=$contrib{$idx.':message'};
  197:                  $message=~s/\n/\<br \/\>/g;
  198: 		 $message=&Apache::lontexconvert::msgtexconverted($message);
  199:                  if ($message) {
  200:                   if ($hidden) {
  201: 		      $message='<font color="#888888">'.$message.'</font>';
  202:                   }
  203:                   my $screenname=&Apache::loncommon::screenname(
  204:                                $contrib{$idx.':sendername'},
  205: 			       $contrib{$idx.':senderdomain'});
  206:                   my $plainname=&Apache::loncommon::nickname(
  207:                                $contrib{$idx.':sendername'},
  208: 			       $contrib{$idx.':senderdomain'});
  209: 
  210:                   my $sender='Anonymous';
  211:                   if ((!$contrib{$idx.':anonymous'}) || ($seeid)) {
  212:                       $sender=&Apache::loncommon::aboutmewrapper(
  213:                                $plainname,
  214:                                $contrib{$idx.':sendername'},
  215:                                $contrib{$idx.':senderdomain'}).' ('.
  216:                               $contrib{$idx.':sendername'}.' at '.
  217: 		      $contrib{$idx.':senderdomain'}.')';
  218:                       if ($contrib{$idx.':anonymous'}) {
  219: 			  $sender.=' [anonymous] '.
  220:                                      $screenname;
  221:                       }
  222:                       if ($seeid) {
  223: 			  if ($hidden) {
  224:                              $sender.=' <a href="/adm/feedback?unhide='.
  225: 				 $symb.':::'.$idx.'">Make Visible</a>';
  226:                           } else {
  227:                              $sender.=' <a href="/adm/feedback?hide='.
  228: 				 $symb.':::'.$idx.'">Hide</a>';
  229: 			  }                     
  230:                           $sender.=' <a href="/adm/feedback?deldisc='.
  231: 				 $symb.':::'.$idx.'">Delete</a>';
  232:                       }
  233:                   } else {
  234:                       if ($screenname) {
  235: 			  $sender='<i>'.$screenname.'</i>';
  236:                       }
  237:                   }
  238: 		  $discussion.='<p><b>'.$sender.'</b> ('.
  239:                       localtime($contrib{$idx.':timestamp'}).
  240:                       '):<blockquote>'.$message.
  241:                       '</blockquote></p>';
  242: 	        }
  243:                } 
  244:               }
  245:               unless ($discussiononly) {
  246:                  $discussion.='</address>';
  247: 	      }
  248:           }
  249:           if ($discussiononly) {
  250: 	      $discussion.=(<<ENDDISCUSS);
  251: <form action="/adm/feedback" method="post" name="mailform">
  252: <input type="submit" name="discuss" value="Post Discussion" />
  253: <input type="submit" name="anondiscuss" value="Post Anonymous Discussion" />
  254: <input type="hidden" name="symb" value="$symb" />
  255: <input type="hidden" name="sendit" value="true" />
  256: <br />
  257: <font size="1">Note: in anonymous discussion, your name is visible only to
  258: course faculty</font><br />
  259: <textarea name=comment cols=60 rows=10 wrap=hard></textarea>
  260: </form>
  261: ENDDISCUSS
  262:              $discussion.=&Apache::lonfeedback::generate_preview_button();
  263:           }
  264:        }
  265:     }
  266:     return $discussion.($discussiononly?'':'</html>');
  267: }
  268: 
  269: sub tokeninputfield {
  270:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  271:     $defhost=~tr/a-z/A-Z/;
  272:     return (<<ENDINPUTFIELD)
  273: <script type="text/javascript">
  274:     function updatetoken() {
  275: 	var comp=new Array;
  276:         var barcode=unescape(document.tokeninput.barcode.value);
  277:         comp=barcode.split('*');
  278:         if (typeof(comp[0])!="undefined") {
  279: 	    document.tokeninput.codeone.value=comp[0];
  280: 	}
  281:         if (typeof(comp[1])!="undefined") {
  282: 	    document.tokeninput.codetwo.value=comp[1];
  283: 	}
  284:         if (typeof(comp[2])!="undefined") {
  285:             comp[2]=comp[2].toUpperCase();
  286: 	    document.tokeninput.codethree.value=comp[2];
  287: 	}
  288:         document.tokeninput.barcode.value='';
  289:     }  
  290: </script>
  291: <form method="post" name="tokeninput">
  292: <table border="2" bgcolor="#FFFFBB">
  293: <tr><th>DocID Checkin</th></tr>
  294: <tr><td>
  295: <table>
  296: <tr>
  297: <td>Scan in Barcode</td>
  298: <td><input type="text" size="22" name="barcode" 
  299: onChange="updatetoken()"/></td>
  300: </tr>
  301: <tr><td><i>or</i> Type in DocID</td>
  302: <td>
  303: <input type="text" size="5" name="codeone" />
  304: <b><font size="+2">*</font></b>
  305: <input type="text" size="5" name="codetwo" />
  306: <b><font size="+2">*</font></b>
  307: <input type="text" size="10" name="codethree" value="$defhost" 
  308: onChange="this.value=this.value.toUpperCase()" />
  309: </td></tr>
  310: </table>
  311: </td></tr>
  312: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  313: </table>
  314: </form>
  315: ENDINPUTFIELD
  316: }
  317: 
  318: sub maketoken {
  319:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  320:     unless ($symb) {
  321: 	$symb=&Apache::lonnet::symbread();
  322:     }
  323:     unless ($tuname) {
  324: 	$tuname=$ENV{'user.name'};
  325:         $tudom=$ENV{'user.domain'};
  326:         $tcrsid=$ENV{'request.course.id'};
  327:     }
  328: 
  329:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  330: }
  331: 
  332: sub printtokenheader {
  333:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  334:     unless ($token) { return ''; }
  335: 
  336:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  337:     unless ($tsymb) {
  338: 	$tsymb=$symb;
  339:     }
  340:     unless ($tuname) {
  341: 	$tuname=$name;
  342:         $tudom=$domain;
  343:         $tcrsid=$courseid;
  344:     }
  345: 
  346:     my %reply=&Apache::lonnet::get('environment',
  347:               ['firstname','middlename','lastname','generation'],
  348:               $tudom,$tuname);
  349:     my $plainname=$reply{'firstname'}.' '. 
  350:                   $reply{'middlename'}.' '.
  351:                   $reply{'lastname'}.' '.
  352: 		  $reply{'generation'};
  353: 
  354:     if ($target eq 'web') {
  355:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  356: 	return 
  357:  '<img align="right" src="/cgi-bin/barcode.png?encode='.$token.'" />'.
  358:                'Checked out for '.$plainname.
  359:                '<br />User: '.$tuname.' at '.$tudom.
  360: 	       '<br />ID: '.$idhash{$tuname}.
  361: 	       '<br />CourseID: '.$tcrsid.
  362: 	       '<br />Course: '.$ENV{'course.'.$tcrsid.'.description'}.
  363:                '<br />DocID: '.$token.
  364:                '<br />Time: '.localtime().'<hr />';
  365:     } else {
  366:         return $token;
  367:     }
  368: }
  369: 
  370: sub fontsettings() {
  371:     my $headerstring='';
  372:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
  373:          $headerstring.=
  374:              '<meta Content-Type="text/html; charset=x-mac-roman">';
  375:     }
  376:     return $headerstring;
  377: }
  378: 
  379: sub printalltags {
  380:   my $temp;
  381:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  382:     &Apache::lonxml::debug("$temp -- ".
  383: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  384:   }
  385: }
  386: 
  387: sub xmlparse {
  388:  my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
  389: 
  390:  &setup_globals($request,$target);
  391:  &Apache::inputtags::initialize_inputtags();
  392:  &Apache::outputtags::initialize_outputtags();
  393:  &Apache::edit::initialize_edit();
  394: #
  395: # do we have a course style file?
  396: #
  397: 
  398:  if ($ENV{'request.course.id'} && $ENV{'request.state'} ne 'construct') {
  399:      my $bodytext=
  400: 	 $ENV{'course.'.$ENV{'request.course.id'}.'.default_xml_style'};
  401:      if ($bodytext) {
  402:        my $location=&Apache::lonnet::filelocation('',$bodytext);
  403:        my $styletext=&Apache::lonnet::getfile($location);
  404:        if ($styletext ne '-1') {
  405:           %style_for_target = (%style_for_target,
  406:                           &Apache::style::styleparser($target,$styletext));
  407:        }
  408:     }
  409:  }
  410: 
  411:  #&printalltags();
  412:  my @pars = ();
  413:  my $pwd=$ENV{'request.filename'};
  414:  $pwd =~ s:/[^/]*$::;
  415:  &newparser(\@pars,\$content_file_string,$pwd);
  416: 
  417:  my $safeeval = new Safe;
  418:  my $safehole = new Safe::Hole;
  419:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  420: #-------------------- Redefinition of the target in the case of compound target
  421: 
  422:  ($target, my @tenta) = split('&&',$target);
  423: 
  424:  my @stack = ();
  425:  my @parstack = ();
  426:  &initdepth;
  427: 
  428:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  429: 				   $safeeval,\%style_for_target);
  430:  if ($ENV{'request.uri'}) {
  431:     &writeallows($ENV{'request.uri'});
  432:  }
  433:  if ($Apache::lonxml::counter_changed) { &store_counter() }
  434:  return $finaloutput;
  435: }
  436: 
  437: sub htmlclean {
  438:     my ($raw,$full)=@_;
  439: 
  440:     my $tree = HTML::TreeBuilder->new;
  441:     $tree->ignore_unknown(0);
  442: 
  443:     $tree->parse($raw);
  444: 
  445:     my $output= $tree->as_HTML(undef,' ');
  446: 
  447:     $output=~s/\<(br|hr|img|meta|allow)(.*?)\>/\<$1$2 \/\>/gis;
  448:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
  449:     unless ($full) {
  450:        $output=~s/\<[\/]*(body|head|html)\>//gis;
  451:     }
  452: 
  453:     $tree = $tree->delete;
  454: 
  455:     return $output;
  456: }
  457: 
  458: sub latex_special_symbols {
  459:     my ($current_token,$stack,$parstack,$where)=@_;
  460:     if ($where eq 'header') {
  461: 	$current_token =~ s/(\\|_|\^)/ /g;
  462: 	$current_token =~ s/(\$|%|\#|&|\{|\})/\\$1/g;
  463:     } else {
  464: 	$current_token=~s/\\ /\\char92 /g;
  465: 	$current_token=~s/\^/\\char94 /g;
  466: 	$current_token=~s/\~/\\char126 /g;
  467: 	$current_token=~s/(&[^a-z\#])/\\$1/g;
  468: 	$current_token=~s/([^&])\#/$1\\#/g;
  469: 	$current_token=~s/(\$|_|{|})/\\$1/g;
  470: 	$current_token=~s/\\char92 /\\texttt{\\char92}/g;
  471: 	$current_token=~s/(>|<)/\$$1\$/g; #more or less
  472: 	if ($current_token=~m/\d%/) {$current_token =~ s/(\d)%/$1\\%/g;} #percent after digit
  473: 	if ($current_token=~m/\s%/) {$current_token =~ s/(\s)%/$1\\%/g;} #persent after space
  474:     }
  475:     return $current_token;
  476: }
  477: 
  478: sub inner_xmlparse {
  479:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  480:   my $finaloutput = '';
  481:   my $result;
  482:   my $token;
  483:   while ( $#$pars > -1 ) {
  484:     while ($token = $$pars['-1']->get_token) {
  485:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  486: 	if ($metamode<1) {
  487: 	    my $text=$token->[1];
  488: 	    if ($token->[0] eq 'C' && $target eq 'tex') {
  489: 		$text = '';
  490: #		$text = '%'.$text."\n";
  491: 	    }
  492: 	    $result.=$text;
  493: 	}
  494:       } elsif ($token->[0] eq 'PI') {
  495: 	if ($metamode<1) {
  496: 	  $result=$token->[2];
  497: 	}
  498:       } elsif ($token->[0] eq 'S') {
  499: 	# add tag to stack
  500: 	push (@$stack,$token->[1]);
  501: 	# add parameters list to another stack
  502: 	push (@$parstack,&parstring($token));
  503: 	&increasedepth($token);
  504: 	if ($Apache::lonxml::usestyle &&
  505: 	    exists($$style_for_target{$token->[1]})) {
  506: 	    $Apache::lonxml::usestyle=0;
  507: 	    my $string=$$style_for_target{$token->[1]}.
  508: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  509: 	    &Apache::lonxml::newparser($pars,\$string);
  510: 	} else {
  511: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  512: 			     $parstack, $pars, $safeeval, $style_for_target);
  513: 	}
  514:       } elsif ($token->[0] eq 'E') {
  515: 	#clear out any tags that didn't end
  516: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  517: 	  my $lasttag=$$stack[-1];
  518: 	  if ($token->[1] =~ /^$lasttag$/i) {
  519: 	    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; as end tag to &lt;'.$$stack[-1].'&gt;');
  520: 	    last;
  521: 	  } else {
  522: 	    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; when looking for &lt;/'.$$stack[-1].'&gt; in file');
  523: 	    &end_tag($stack,$parstack,$token);
  524: 	  }
  525: 	}
  526: 
  527: 	if ($Apache::lonxml::usestyle &&
  528: 	    exists($$style_for_target{'/'."$token->[1]"})) {
  529: 	    $Apache::lonxml::usestyle=0;
  530: 	    my $string=$$style_for_target{'/'.$token->[1]}.
  531: 	      '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
  532: 	    &Apache::lonxml::newparser($pars,\$string);
  533: 	} else {
  534: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
  535: 			     $parstack, $pars,$safeeval, $style_for_target);
  536: 	}
  537:       } else {
  538: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  539:       }
  540:       #evaluate variable refs in result
  541:       if ($result ne "") {
  542: 	if ( $#$parstack > -1 ) {
  543: 	  $result=&Apache::run::evaluate($result,$safeeval,$$parstack[-1]);
  544: 	} else {
  545: 	  $result= &Apache::run::evaluate($result,$safeeval,'');
  546: 	}
  547:       }
  548:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  549: 	if ($target eq 'tex') {
  550: 	    $result=&latex_special_symbols($result,$stack,$parstack);
  551: 	}
  552:       }
  553: 
  554:       # Encode any high ASCII characters
  555:       if (!$Apache::lonxml::prevent_entity_encode) {
  556: 	$result=&HTML::Entities::encode($result,"\200-\377");
  557:       }
  558:       if ($Apache::lonxml::redirection) {
  559: 	$Apache::lonxml::outputstack['-1'] .= $result;
  560:       } else {
  561: 	$finaloutput.=$result;
  562:       }
  563:       $result = '';
  564: 
  565:       if ($token->[0] eq 'E') { 
  566: 	&end_tag($stack,$parstack,$token);
  567:       }
  568:     }	
  569:     if ($#$pars > -1) {
  570: 	pop @$pars;
  571: 	pop @Apache::lonxml::pwd;
  572:     }
  573:   }
  574: 
  575:   # if ($target eq 'meta') {
  576:   #   $finaloutput.=&endredirection;
  577:   # }
  578: 
  579: 
  580:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  581:     $finaloutput=&afterburn($finaloutput);
  582:   }	    
  583:   return $finaloutput;
  584: }
  585: 
  586: sub callsub {
  587:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  588:   my $currentstring='';
  589:   my $nodefault;
  590:   {
  591:     my $sub1;
  592:     no strict 'refs';
  593:     my $tag=$token->[1];
  594: # get utterly rid of extended html tags
  595:     if ($tag=~/^x\-/i) { return ''; }
  596:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  597:     if (!$space) {
  598:      	$tag=~tr/A-Z/a-z/;
  599: 	$sub=~tr/A-Z/a-z/;
  600: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  601:     }
  602: 
  603:     my $deleted=0;
  604:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  605:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  606:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  607: 					     $parstack,$parser,$safeeval,
  608: 					     $style);
  609:     }
  610:     if (!$deleted) {
  611:       if ($space) {
  612: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  613: 	$sub1="$space\:\:$sub";
  614: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  615: 					     $parstack,$parser,$safeeval,
  616: 					     $style);
  617:       } else {
  618: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  619: 	if ($metamode <1) {
  620: 	  if (defined($token->[4]) && ($metamode < 1)) {
  621: 	    $currentstring = $token->[4];
  622: 	  } else {
  623: 	    $currentstring = $token->[2];
  624: 	  }
  625: 	}
  626:       }
  627:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  628:       if ($currentstring eq '' && $nodefault eq '') {
  629: 	if ($target eq 'edit') {
  630: 	  #&Apache::lonxml::debug("doing default edit for $token->[1]");
  631: 	  if ($token->[0] eq 'S') {
  632: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  633: 	  } elsif ($token->[0] eq 'E') {
  634: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  635: 	  }
  636: 	} elsif ($target eq 'modified') {
  637: 	  if ($token->[0] eq 'S') {
  638: 	    $currentstring = $token->[4];
  639: 	    $currentstring.=&Apache::edit::handle_insert();
  640: 	  } elsif ($token->[0] eq 'E') {
  641: 	    $currentstring = $token->[2];
  642:             $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
  643: 	  } else {
  644: 	    $currentstring = $token->[2];
  645: 	  }
  646: 	}
  647:       }
  648:     }
  649:     use strict 'refs';
  650:   }
  651:   return $currentstring;
  652: }
  653: 
  654: sub setup_globals {
  655:   my ($request,$target)=@_;
  656:   $Apache::lonxml::request=$request;
  657:   $Apache::lonxml::registered = 0;
  658:   $errorcount=0;
  659:   $warningcount=0;
  660:   $Apache::lonxml::default_homework_loaded=0;
  661:   $Apache::lonxml::usestyle=1;
  662:   &init_counter();
  663:   @Apache::lonxml::pwd=();
  664:   @Apache::lonxml::extlinks=();
  665:   if ($target eq 'meta') {
  666:     $Apache::lonxml::redirection = 0;
  667:     $Apache::lonxml::metamode = 1;
  668:     $Apache::lonxml::evaluate = 1;
  669:     $Apache::lonxml::import = 0;
  670:   } elsif ($target eq 'answer') {
  671:     $Apache::lonxml::redirection = 0;
  672:     $Apache::lonxml::metamode = 1;
  673:     $Apache::lonxml::evaluate = 1;
  674:     $Apache::lonxml::import = 1;
  675:   } elsif ($target eq 'grade') {
  676:     &startredirection;
  677:     $Apache::lonxml::metamode = 0;
  678:     $Apache::lonxml::evaluate = 1;
  679:     $Apache::lonxml::import = 1;
  680:   } elsif ($target eq 'modified') {
  681:     $Apache::lonxml::redirection = 0;
  682:     $Apache::lonxml::metamode = 0;
  683:     $Apache::lonxml::evaluate = 0;
  684:     $Apache::lonxml::import = 0;
  685:   } elsif ($target eq 'edit') {
  686:     $Apache::lonxml::redirection = 0;
  687:     $Apache::lonxml::metamode = 0;
  688:     $Apache::lonxml::evaluate = 0;
  689:     $Apache::lonxml::import = 0;
  690:   } elsif ($target eq 'analyze') {
  691:     $Apache::lonxml::redirection = 0;
  692:     $Apache::lonxml::metamode = 0;
  693:     $Apache::lonxml::evaluate = 1;
  694:     $Apache::lonxml::import = 1;
  695:   } else {
  696:     $Apache::lonxml::redirection = 0;
  697:     $Apache::lonxml::metamode = 0;
  698:     $Apache::lonxml::evaluate = 1;
  699:     $Apache::lonxml::import = 1;
  700:   }
  701: }
  702: 
  703: sub init_safespace {
  704:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  705:   $safeeval->permit("entereval");
  706:   $safeeval->permit(":base_math");
  707:   $safeeval->permit("sort");
  708:   $safeeval->deny(":base_io");
  709:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  710:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  711:   
  712:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  713:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  714:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  715:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  716:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  717:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  718:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  719:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  720:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  721:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  722:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  723:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  724:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  725:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  726:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  727:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  728:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  729:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  730:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  731:   
  732:   $safehole->wrap(\&Math::Cephes::bdtr  ,$safeeval,'&bdtr'  );
  733:   $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
  734:   $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
  735:   $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
  736:   $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
  737:   $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
  738:   $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
  739:   $safehole->wrap(\&Math::Cephes::fdtr  ,$safeeval,'&fdtr'  );
  740:   $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
  741:   $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
  742:   $safehole->wrap(\&Math::Cephes::gdtr  ,$safeeval,'&gdtr'  );
  743:   $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
  744:   $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
  745:   $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
  746:   $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
  747:   $safehole->wrap(\&Math::Cephes::ndtr  ,$safeeval,'&ndtr'  );
  748:   $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
  749:   $safehole->wrap(\&Math::Cephes::pdtr  ,$safeeval,'&pdtr'  );
  750:   $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
  751:   $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
  752:   $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
  753:   $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
  754: 
  755: #  $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
  756: #  $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
  757: #  $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
  758: #  $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
  759: #  $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
  760: #  $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
  761: 
  762:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  763:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  764:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  765:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  766:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  767:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  768:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  769:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  770:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  771:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  772:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  773:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  774:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  775:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  776:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  777:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  778:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  779:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  780:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  781:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  782:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  783: 
  784: #need to inspect this class of ops
  785: # $safeeval->deny(":base_orig");
  786:   $safeinit .= ';$external::target="'.$target.'";';
  787:   my $rndseed;
  788:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  789:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  790:   $safeinit .= ';$external::randomseed='.$rndseed.';';
  791:   &Apache::run::run($safeinit,$safeeval);
  792: }
  793: 
  794: sub default_homework_load {
  795:     my ($safeeval)=@_;
  796:     &Apache::lonxml::debug('Loading default_homework');
  797:     my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
  798:     if ($default == -1) {
  799: 	&Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
  800:     } else {
  801: 	&Apache::run::run($default,$safeeval);
  802: 	$Apache::lonxml::default_homework_loaded=1;
  803:     }
  804: }
  805: 
  806: sub startredirection {
  807:   $Apache::lonxml::redirection++;
  808:   push (@Apache::lonxml::outputstack, '');
  809: }
  810: 
  811: sub endredirection {
  812:   if (!$Apache::lonxml::redirection) {
  813:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  814:     return '';
  815:   }
  816:   $Apache::lonxml::redirection--;
  817:   pop @Apache::lonxml::outputstack;
  818: }
  819: 
  820: sub end_tag {
  821:   my ($tagstack,$parstack,$token)=@_;
  822:   pop(@$tagstack);
  823:   pop(@$parstack);
  824:   &decreasedepth($token);
  825: }
  826: 
  827: sub initdepth {
  828:   @Apache::lonxml::depthcounter=();
  829:   $Apache::lonxml::depth=-1;
  830:   $Apache::lonxml::olddepth=-1;
  831: }
  832: 
  833: sub increasedepth {
  834:   my ($token) = @_;
  835:   $Apache::lonxml::depth++;
  836:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  837:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  838:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  839:   }
  840:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  841:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  842: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  843: }
  844: 
  845: sub decreasedepth {
  846:   my ($token) = @_;
  847:   $Apache::lonxml::depth--;
  848:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  849:     $#Apache::lonxml::depthcounter--;
  850:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  851:   }
  852:   if (  $Apache::lonxml::depth < -1) {
  853:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
  854:     $Apache::lonxml::depth='-1';
  855:   }
  856:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  857:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  858: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  859: }
  860: 
  861: sub get_all_text_unbalanced {
  862: #there is a copy of this in lonpublisher.pm
  863:  my($tag,$pars)= @_;
  864:  my $token;
  865:  my $result='';
  866:  $tag='<'.$tag.'>';
  867:  while ($token = $$pars[-1]->get_token) {
  868:    if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  869:      $result.=$token->[1];
  870:    } elsif ($token->[0] eq 'PI') {
  871:      $result.=$token->[2];
  872:    } elsif ($token->[0] eq 'S') {
  873:      $result.=$token->[4];
  874:    } elsif ($token->[0] eq 'E')  {
  875:      $result.=$token->[2];
  876:    }
  877:    if ($result =~ /(.*)\Q$tag\E(.*)/s) {
  878:      &Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
  879:      &Apache::lonxml::debug('Result is :'.$1);
  880:      $result=$1;
  881:      my $redo=$tag.$2;
  882:      &Apache::lonxml::newparser($pars,\$redo);
  883:      last;
  884:    }
  885:  }
  886:  return $result
  887: }
  888: 
  889: sub increment_counter {
  890:     $Apache::lonxml::counter++;
  891:     $Apache::lonxml::counter_changed=1;
  892: }
  893: 
  894: sub init_counter {
  895:     if (defined($ENV{'form.counter'})) {
  896: 	$Apache::lonxml::counter=$ENV{'form.counter'};
  897:     } else {
  898: 	$Apache::lonxml::counter=1;
  899: 	&store_counter();
  900:     }
  901:     $Apache::lonxml::counter_changed=0;
  902: }
  903: 
  904: sub store_counter {
  905:     &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
  906:     return '';
  907: }
  908: 
  909: sub get_all_text {
  910:  my($tag,$pars)= @_;
  911:  &Apache::lonxml::debug("Got a ".ref($pars));
  912:  my $gotfullstack=1;
  913:  if (ref($pars) ne 'ARRAY') {
  914:      $gotfullstack=0;
  915:      $pars=[$pars];
  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') {
  932: 	 if ($token->[1] =~ /^$tag$/i) { $depth++; }
  933: 	 $result.=$token->[4];
  934:        } elsif ($token->[0] eq 'E')  {
  935: 	 if ( $token->[1] =~ /^$tag$/i) { $depth--; }
  936: 	 #skip sending back the last end tag
  937: 	 if ($depth > -1) { $result.=$token->[2]; } else {
  938: 	   $$pars[-1]->unget_token($token);
  939: 	 }
  940:        }
  941:      }
  942:      if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
  943:      if (($depth >=0) && ($#$pars > 0) ) {
  944:        pop(@$pars);
  945:        pop(@Apache::lonxml::pwd);
  946:      }
  947:    }
  948:    if ($top_empty && $depth >= 0) {
  949:        #never found the end tag ran out of text, throw error send back blank
  950:        &error('Never found end tag for &lt;'.$tag.'&gt;');
  951:        if ($gotfullstack) {
  952: 	   my $newstring='</'.$tag.'>'.$result;
  953: 	   &Apache::lonxml::newparser($pars,\$newstring);
  954:        }
  955:        $result='';
  956:    }
  957:  } else {
  958:      while ($#$pars > -1) {
  959: 	 while ($token = $$pars[-1]->get_token) {
  960: 	     #&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
  961: 	     if (($token->[0] eq 'T')||($token->[0] eq 'C')||
  962: 		 ($token->[0] eq 'D')) {
  963: 		 $result.=$token->[1];
  964: 	     } elsif ($token->[0] eq 'PI') {
  965: 		 $result.=$token->[2];
  966: 	     } elsif ($token->[0] eq 'S') {
  967: 		 if ( $token->[1] =~ /^$tag$/i) {
  968: 		     $$pars[-1]->unget_token($token); last;
  969: 		 } else {
  970: 		     $result.=$token->[4];
  971: 		 }
  972: 	     } elsif ($token->[0] eq 'E')  {
  973: 		 $result.=$token->[2];
  974: 	     }
  975: 	 }
  976: 	 if (($#$pars > 0) ) {
  977: 	     pop(@$pars);
  978: 	     pop(@Apache::lonxml::pwd);
  979: 	 } else { last; }
  980:      }
  981:  }
  982:  if ($result =~ m|<LONCAPA_INTERNAL_TURN_STYLE_ON />|) {
  983:      $Apache::lonxml::usestyle=1;
  984:  }
  985:  #&Apache::lonxml::debug("Exit:$result:");
  986:  return $result
  987: }
  988: 
  989: sub newparser {
  990:   my ($parser,$contentref,$dir) = @_;
  991:   push (@$parser,HTML::LCParser->new($contentref));
  992:   $$parser['-1']->xml_mode('1');
  993:   if ( $dir eq '' ) {
  994:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
  995:   } else {
  996:     push (@Apache::lonxml::pwd, $dir);
  997:   } 
  998: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
  999: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
 1000: }
 1001: 
 1002: sub parstring {
 1003:   my ($token) = @_;
 1004:   my $temp='';
 1005:   foreach (@{$token->[3]}) {
 1006:     unless ($_=~/\W/) {
 1007:       my $val=$token->[2]->{$_};
 1008:       $val =~ s/([\%\@\\\"\'])/\\$1/g;
 1009:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1010:       $temp .= "my \$$_=\"$val\";"
 1011:     }
 1012:   }
 1013:   return $temp;
 1014: }
 1015: 
 1016: sub writeallows {
 1017:     unless ($#extlinks>=0) { return; }
 1018:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
 1019:     if ($ENV{'httpref.'.$thisurl}) {
 1020: 	$thisurl=$ENV{'httpref.'.$thisurl};
 1021:     }
 1022:     my $thisdir=$thisurl;
 1023:     $thisdir=~s/\/[^\/]+$//;
 1024:     my %httpref=();
 1025:     foreach (@extlinks) {
 1026:        $httpref{'httpref.'.
 1027:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1028:     }
 1029:     @extlinks=();
 1030:     &Apache::lonnet::appenv(%httpref);
 1031: }
 1032: 
 1033: #
 1034: # Afterburner handles anchors, highlights and links
 1035: #
 1036: sub afterburn {
 1037:     my $result=shift;
 1038:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1039: 					    ['highlight','anchor','link']);
 1040:     if ($ENV{'form.highlight'}) {
 1041:        foreach (split(/\,/,$ENV{'form.highlight'})) {
 1042:            my $anchorname=$_;
 1043: 	   my $matchthis=$anchorname;
 1044:            $matchthis=~s/\_+/\\s\+/g;
 1045:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1046:        }
 1047:     }
 1048:     if ($ENV{'form.link'}) {
 1049:        foreach (split(/\,/,$ENV{'form.link'})) {
 1050:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1051: 	   my $matchthis=$anchorname;
 1052:            $matchthis=~s/\_+/\\s\+/g;
 1053:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1054:        }
 1055:     }
 1056:     if ($ENV{'form.anchor'}) {
 1057:         my $anchorname=$ENV{'form.anchor'};
 1058: 	my $matchthis=$anchorname;
 1059:         $matchthis=~s/\_+/\\s\+/g;
 1060:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1061:         $result.=(<<"ENDSCRIPT");
 1062: <script type="text/javascript">
 1063:     document.location.hash='$anchorname';
 1064: </script>
 1065: ENDSCRIPT
 1066:     }
 1067:     return $result;
 1068: }
 1069: 
 1070: sub storefile {
 1071:     my ($file,$contents)=@_;
 1072:     if (my $fh=Apache::File->new('>'.$file)) {
 1073: 	print $fh $contents;
 1074:         $fh->close();
 1075:     } else {
 1076:       &warning("Unable to save file $file");
 1077:     }
 1078: }
 1079: 
 1080: sub createnewhtml {
 1081:   my $filecontents=(<<SIMPLECONTENT);
 1082: <html>
 1083: <head>
 1084: <title>
 1085:                            Title of Document Goes Here
 1086: </title>
 1087: </head>
 1088: <body bgcolor="#FFFFFF">
 1089: 
 1090:                            Body of Document Goes Here
 1091: 
 1092: </body>
 1093: </html>
 1094: SIMPLECONTENT
 1095:   return $filecontents;
 1096: }
 1097: 
 1098: 
 1099: sub inserteditinfo {
 1100:       my ($result,$filecontents)=@_;
 1101:       $filecontents = &HTML::Entities::encode($filecontents);
 1102: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1103:       my $xml_help = '<table><tr><td>'.
 1104: 	  &Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
 1105: 					      undef,undef,600)
 1106: 	      .'</td><td>'.
 1107:           &Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
 1108: 					      undef,undef,600)
 1109: 	      .'</td></tr></table>';
 1110:       my $buttons=(<<BUTTONS);
 1111: <input type="submit" name="attemptclean" 
 1112:        value="Save and then attempt to clean HTML" />
 1113: <input type="submit" name="savethisfile" value="Save this" />
 1114: <input type="submit" name="viewmode" value="View" />
 1115: BUTTONS
 1116:       my $editfooter=(<<ENDFOOTER);
 1117: <hr />
 1118: <a name="editsection" />
 1119: <form method="post">
 1120: $xml_help
 1121: <input type="hidden" name="editmode" value="Edit" />
 1122: $buttons<br />
 1123: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
 1124: <br />$buttons
 1125: <br />
 1126: </form>
 1127: ENDFOOTER
 1128: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1129:       $result=~s/(\<\/body\>)/$editfooter/is;
 1130:       return $result;
 1131: }
 1132: 
 1133: sub get_target {
 1134:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
 1135:   if ( $ENV{'request.state'} eq 'published') {
 1136:     if ( defined($ENV{'form.grade_target'})
 1137: 	 && ($viewgrades == 'F' )) {
 1138:       return ($ENV{'form.grade_target'});
 1139:     } elsif (defined($ENV{'form.grade_target'})) {
 1140:       if (($ENV{'form.grade_target'} eq 'web') ||
 1141: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
 1142: 	return $ENV{'form.grade_target'}
 1143:       } else {
 1144: 	return 'web';
 1145:       }
 1146:     } else {
 1147:       return 'web';
 1148:     }
 1149:   } elsif ($ENV{'request.state'} eq 'construct') {
 1150:     if ( defined($ENV{'form.grade_target'})) {
 1151:       return ($ENV{'form.grade_target'});
 1152:     } else {
 1153:       return 'web';
 1154:     }
 1155:   } else {
 1156:     return 'web';
 1157:   }
 1158: }
 1159: 
 1160: sub handler {
 1161:   my $request=shift;
 1162: 
 1163:   my $target=&get_target();
 1164: 
 1165:   $Apache::lonxml::debug=0;
 1166: 
 1167:   if ($ENV{'browser.mathml'}) {
 1168:     $request->content_type('text/xml');
 1169:   } else {
 1170:     $request->content_type('text/html');
 1171:   }
 1172:   &Apache::loncommon::no_cache($request);
 1173:   $request->send_http_header;
 1174: 
 1175:   return OK if $request->header_only;
 1176: 
 1177: 
 1178:   my $file=&Apache::lonnet::filelocation("",$request->uri);
 1179: #
 1180: # Edit action? Save file.
 1181: #
 1182:   unless ($ENV{'request.state'} eq 'published') {
 1183:       if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
 1184: 	  &storefile($file,$ENV{'form.filecont'});
 1185:       }
 1186:   }
 1187:   my %mystyle;
 1188:   my $result = '';
 1189:   my $filecontents=&Apache::lonnet::getfile($file);
 1190:   if ($filecontents == -1) {
 1191:     $result=(<<ENDNOTFOUND);
 1192: <html>
 1193: <head>
 1194: <title>File not found</title>
 1195: </head>
 1196: <body bgcolor="#FFFFFF">
 1197: <b>File not found: $file</b>
 1198: </body>
 1199: </html>
 1200: ENDNOTFOUND
 1201:     $filecontents='';
 1202:     if ($ENV{'request.state'} ne 'published') {
 1203:       $filecontents=&createnewhtml();
 1204:       $ENV{'form.editmode'}='Edit'; #force edit mode
 1205:     }
 1206:   } else {
 1207:     unless ($ENV{'request.state'} eq 'published') {
 1208:       if ($ENV{'form.attemptclean'}) {
 1209: 	$filecontents=&htmlclean($filecontents,1);
 1210:       }
 1211:     }
 1212:     if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
 1213:       $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
 1214: 					  '',%mystyle);
 1215:     }
 1216:   }
 1217: 
 1218: #
 1219: # Edit action? Insert editing commands
 1220: #
 1221:   unless ($ENV{'request.state'} eq 'published') {
 1222:     if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
 1223: 	my $displayfile=$request->uri;
 1224:         $displayfile=~s/^\/[^\/]*//;
 1225:       $result='<html><body bgcolor="#FFFFFF"><h3>'.$displayfile.
 1226:               '</h3></body></html>';
 1227:       $result=&inserteditinfo($result,$filecontents);
 1228:     }
 1229:   }
 1230: 
 1231:   writeallows($request->uri);
 1232: 
 1233:   $request->print($result);
 1234: 
 1235:   return OK;
 1236: }
 1237: 
 1238: sub debug {
 1239:   if ($Apache::lonxml::debug eq 1) {
 1240:     $|=1;
 1241:     print('<font size="-2"<pre>DEBUG:'.&HTML::Entities::encode($_[0])."</pre></font>\n");
 1242:   }
 1243: }
 1244: 
 1245: sub error {
 1246:   $errorcount++;
 1247:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
 1248:     # If printing in construction space, put the error inside <pre></pre>
 1249:     print "<b>ERROR:</b>".join("\n",@_)."\n";
 1250:   } else {
 1251:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
 1252:     #notify author
 1253:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
 1254:     #notify course
 1255:     if ( $ENV{'request.course.id'} ) {
 1256:       my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
 1257:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
 1258:       foreach (keys %users) {
 1259: 	my ($user,$domain) = split(/:/, $_);
 1260: 	&Apache::lonmsg::user_normal_msg($user,$domain,
 1261:         "Error [$declutter]",join('<br />',@_));
 1262:       }
 1263:     }
 1264: 
 1265:     #FIXME probably shouldn't have me get everything forever.
 1266:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
 1267:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
 1268:   }
 1269: }
 1270: 
 1271: sub warning {
 1272:   $warningcount++;
 1273:   if ($ENV{'request.state'} eq 'construct') {
 1274:     print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
 1275:   }
 1276: }
 1277: 
 1278: sub get_param {
 1279:     my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1280:     if ( ! $context ) { $context = -1; }
 1281:     my $args ='';
 1282:     if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1283:     if ( ! $args ) { return undef; }
 1284:     if ( $case_insensitive ) {
 1285: 	if ($args =~ s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei) {
 1286: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1287:                                      $safeeval); #'
 1288: 	} else {
 1289: 	    return undef;
 1290: 	}
 1291:     } else {
 1292: 	if ( $args =~ /my \$\Q$param\E=\"/ ) {
 1293: 	    return &Apache::run::run("{$args;".'return $'.$param.'}',
 1294:                                      $safeeval); #'
 1295: 	} else {
 1296: 	    return undef;
 1297: 	}
 1298:     }
 1299: }
 1300: 
 1301: sub get_param_var {
 1302:   my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
 1303:   if ( ! $context ) { $context = -1; }
 1304:   my $args ='';
 1305:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1306:   &Apache::lonxml::debug("Args are $args param is $param");
 1307:   if ($case_insensitive) {
 1308:       if (! ($args=~s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei)) {
 1309: 	  return undef;
 1310:       }
 1311:   } elsif ( $args !~ /my \$\Q$param\E=\"/ ) { return undef; }
 1312:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1313:   &Apache::lonxml::debug("first run is $value");
 1314:   if ($value =~ /^[\$\@\%]\w+$/) {
 1315:       &Apache::lonxml::debug("doing second");
 1316:       my @result=&Apache::run::run("return $value",$safeeval,1);
 1317:       if (!defined($result[0])) {
 1318: 	  return $value
 1319:       } else {
 1320: 	  if (wantarray) { return @result; } else { return $result[0]; }
 1321:       }
 1322:   } else {
 1323:     return $value;
 1324:   }
 1325: }
 1326: 
 1327: sub register_insert {
 1328:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1329:   my $i;
 1330:   my $tagnum=0;
 1331:   my @order;
 1332:   for ($i=0;$i < $#data; $i++) {
 1333:     my $line = $data[$i];
 1334:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1335:     if ( $line =~ /TABLE/ ) { last; }
 1336:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
 1337:     if ($tag) {
 1338:       $insertlist{"$tagnum.tag"} = $tag;
 1339:       $insertlist{"$tagnum.description"} = $descrip;
 1340:       $insertlist{"$tagnum.color"} = $color;
 1341:       $insertlist{"$tagnum.function"} = $function;
 1342:       if (!defined($show)) { $show='yes'; }
 1343:       $insertlist{"$tagnum.show"}= $show;
 1344:       $insertlist{"$tag.num"}=$tagnum;
 1345:       $tagnum++;
 1346:     }
 1347:   }
 1348:   $i++; #skipping TABLE line
 1349:   $tagnum = 0;
 1350:   for (;$i < $#data;$i++) {
 1351:     my $line = $data[$i];
 1352:     my ($mnemonic,@which) = split(/ +/,$line);
 1353:     my $tag = $insertlist{"$tagnum.tag"};
 1354:     for (my $j=0;$j <=$#which;$j++) {
 1355:       if ( $which[$j] eq 'Y' ) {
 1356: 	if ($insertlist{"$j.show"} ne 'no') {
 1357: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1358: 	}
 1359:       }
 1360:     }
 1361:     $tagnum++;
 1362:   }
 1363: }
 1364: 
 1365: sub description {
 1366:   my ($token)=@_;
 1367:   my $tagnum;
 1368:   my $tag=$token->[1];
 1369:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1370:     my $testtag=$namespace.'::'.$tag;
 1371:     $tagnum=$insertlist{"$testtag.num"};
 1372:     if (defined($tagnum)) { last; }
 1373:   }
 1374:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1375:   return $insertlist{$tagnum.'.description'};
 1376: }
 1377: 
 1378: # ----------------------------------------------------------------- whichuser
 1379: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1380: # calls to lonnet functions for this setup.
 1381: # - looks for form.grade_ parameters
 1382: sub whichuser {
 1383:   my ($symb,$courseid,$domain,$name);
 1384:   if (defined($ENV{'form.grade_symb'})) {
 1385:     my $tmp_courseid=$ENV{'form.grade_courseid'};
 1386:     my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
 1387:     if ($allowed) {
 1388:       $symb=$ENV{'form.grade_symb'};
 1389:       $courseid=$ENV{'form.grade_courseid'};
 1390:       $domain=$ENV{'form.grade_domain'};
 1391:       $name=$ENV{'form.grade_username'};
 1392:     }
 1393:   } else {
 1394:     $symb=&Apache::lonnet::symbread();
 1395:     $courseid=$ENV{'request.course.id'};
 1396:     $domain=$ENV{'user.domain'};
 1397:     $name=$ENV{'user.name'};
 1398:   }
 1399:   return ($symb,$courseid,$domain,$name);
 1400: }
 1401: 
 1402: 1;
 1403: __END__
 1404: 
 1405: 

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