File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.242: download - view: text, annotated - select for diffs
Sat Mar 29 22:50:22 2003 UTC (21 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Work on small attachments for discussion and feedback

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

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