File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.104: download - view: text, annotated - select for diffs
Fri Jul 27 18:16:22 2001 UTC (22 years, 10 months ago) by ng
Branches: MAIN
CVS tags: HEAD
fix safehole for random_multivariate function

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # last modified 06/26/00 by Alexander Sakharuk
    5: # 11/6 Gerd Kortemeyer
    6: # 6/1/1 Gerd Kortemeyer
    7: # 2/21,3/13 Guy
    8: # 3/29,5/4 Gerd Kortemeyer
    9: # 5/10 Scott Harrison
   10: # 5/26 Gerd Kortemeyer
   11: # 5/27 H. K. Ng
   12: # 6/2,6/3,6/8,6/9 Gerd Kortemeyer
   13: # 6/12,6/13 H. K. Ng
   14: # 6/16 Gerd Kortemeyer
   15: # 7/27 H. K. Ng
   16: 
   17: package Apache::lonxml; 
   18: use vars 
   19: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace);
   20: use strict;
   21: use HTML::TokeParser;
   22: use Safe;
   23: use Safe::Hole;
   24: use Math::Cephes qw(:trigs :hypers :bessels erf erfc);
   25: use Math::Random qw(:all);
   26: use Opcode;
   27: 
   28: sub register {
   29:   my $space;
   30:   my @taglist;
   31:   my $temptag;
   32:   ($space,@taglist) = @_;
   33:   foreach $temptag (@taglist) {
   34:     $Apache::lonxml::alltags{$temptag}=$space;
   35:   }
   36: }
   37: 
   38: use Apache::Constants qw(:common);
   39: use Apache::lontexconvert;
   40: use Apache::style;
   41: use Apache::run;
   42: use Apache::londefdef;
   43: use Apache::scripttag;
   44: use Apache::edit;
   45: use Apache::lonnet;
   46: use Apache::File;
   47: 
   48: #==================================================   Main subroutine: xmlparse  
   49: #debugging control, to turn on debugging modify the correct handler
   50: $Apache::lonxml::debug=0;
   51: 
   52: #path to the directory containing the file currently being processed
   53: @pwd=();
   54: 
   55: #these two are used for capturing a subset of the output for later processing,
   56: #don't touch them directly use &startredirection and &endredirection
   57: @outputstack = ();
   58: $redirection = 0;
   59: 
   60: #controls wheter the <import> tag actually does
   61: $import = 1;
   62: @extlinks=();
   63: 
   64: # meta mode is a bit weird only some output is to be turned off
   65: #<output> tag turns metamode off (defined in londefdef.pm)
   66: $metamode = 0;
   67: 
   68: # turns on and of run::evaluate actually derefencing var refs
   69: $evaluate = 1;
   70: 
   71: # data structure for eidt mode, determines what tags can go into what other tags
   72: %insertlist=();
   73: 
   74: # stores the list of active tag namespaces
   75: @namespace=();
   76: 
   77: # has the dynamic menu been updated to know about this resource
   78: $Apache::lonxml::registered=0;
   79: 
   80: sub xmlbegin {
   81:   my $output='';
   82:   if ($ENV{'browser.mathml'}) {
   83:       $output='<?xml version="1.0"?>'
   84:             .'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'
   85:             .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
   86:             .'[<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">]>'
   87:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
   88: 		.'xmlns="http://www.w3.org/TR/REC-html40">';
   89:   } else {
   90:       $output='<html>';
   91:   }
   92:   return $output;
   93: }
   94: 
   95: sub xmlend {
   96:     my $discussion='';
   97:     if ($ENV{'request.course.id'}) {
   98:        my $symb=&Apache::lonnet::symbread();
   99:        if ($symb) {
  100:           my %contrib=&Apache::lonnet::restore($symb,$ENV{'request.course.id'},
  101:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  102: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  103:           if ($contrib{'version'}) {
  104:               $discussion.=
  105:                   '<address><hr /><h2>Course Discussion of Resource</h2>';
  106:               my $idx;
  107:               for ($idx=1;$idx<=$contrib{'version'};$idx++) {
  108:                   my $message=$contrib{$idx.':message'};
  109:                   $message=~s/\n/\<br \/\>/g;
  110: 		  $discussion.='<p><b>'.$contrib{$idx.':sendername'}.' at '.
  111: 		      $contrib{$idx.':senderdomain'}.'</b> ('.
  112:                       localtime($contrib{$idx.':timestamp'}).
  113:                       '):<blockquote>'.$message.
  114:                       '</blockquote></p>'; 
  115:               }
  116:               $discussion.='</address>';
  117:           }
  118:        }
  119:     }
  120:     return $discussion.'</html>';
  121: }
  122: 
  123: sub fontsettings() {
  124:     my $headerstring='';
  125:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
  126:          $headerstring.=
  127:              '<meta Content-Type="text/html; charset=x-mac-roman">';
  128:     }
  129:     return $headerstring;
  130: }
  131: 
  132: sub registerurl {
  133:     my $forcereg=shift;
  134:     if ($Apache::lonxml::registered) { return ''; }
  135:     if (($ENV{'REQUEST_URI'}!~/^\/(res\/)*adm\//) || ($forcereg)) {
  136:         my $hwkadd='';
  137:         if ($ENV{'REQUEST_URI'}=~/\.(problem|exam|quiz|assess|survey|form)$/) {
  138: 	    if (&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) {
  139: 		$hwkadd.=(<<ENDSUBM);
  140:                      menu.switchbutton
  141:            (7,1,'subm.gif','view sub','missions',
  142:                 'gocmd("/adm/grades","submission")');
  143: ENDSUBM
  144:             }
  145: 	    if (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) {
  146: 		$hwkadd.=(<<ENDGRDS);
  147:                      menu.switchbutton
  148:            (7,2,'pgrd.gif','problem','grades',
  149:                 'gocmd("/adm/grades","viewgrades")');
  150: ENDGRDS
  151:             }
  152: 	    if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  153: 		$hwkadd.=(<<ENDPARM);
  154:                      menu.switchbutton
  155:            (7,3,'pparm.gif','problem','parms',
  156:                 'gocmd("/adm/parmset","set")');
  157: ENDPARM
  158:             }
  159: 	}
  160: 	return (<<ENDREGTHIS);
  161:      
  162: <script language="JavaScript">
  163: // BEGIN LON-CAPA Internal
  164: 
  165:     function LONCAPAreg() {
  166: 	  menu=window.open("","LONCAPAmenu");
  167:           menu.clearTimeout(menu.menucltim);
  168: 	  menu.currentURL=window.location.pathname;
  169:           menu.currentStale=0;
  170:           menu.clearbut(3,1);
  171:           menu.switchbutton
  172:        (8,1,'eval.gif','evaluate','this','gopost("/adm/evaluate",currentURL)');
  173:           menu.switchbutton
  174:     (8,2,'fdbk.gif','feedback','on this','gopost("/adm/feedback",currentURL)');
  175:           menu.switchbutton
  176:      (8,3,'prt.gif','prepare','printout','gopost("/adm/printout",currentURL)');
  177:           menu.switchbutton
  178:        (2,1,'back.gif','backward','','gopost("/adm/flip","back:"+currentURL)');
  179:           menu.switchbutton
  180:      (2,3,'forw.gif','forward','','gopost("/adm/flip","forward:"+currentURL)');
  181:           menu.switchbutton
  182:                             (9,1,'sbkm.gif','set','bookmark','set_bookmark()');
  183:           menu.switchbutton
  184:                          (9,2,'vbkm.gif','view','bookmark','edit_bookmarks()');
  185:           menu.switchbutton
  186:                                (9,3,'anot.gif','anno-','tations','annotate()');
  187:           $hwkadd
  188:     }
  189: 
  190:     function LONCAPAstale() {
  191: 	  menu=window.open("","LONCAPAmenu");
  192:           menu.currentStale=1;
  193:           menu.switchbutton
  194:             (3,1,'reload.gif','return','location','go(currentURL)');
  195:           menu.clearbut(7,1);
  196:           menu.clearbut(7,2);
  197:           menu.clearbut(7,3);
  198:           menu.menucltim=menu.setTimeout(
  199:  'clearbut(2,1);clearbut(2,3);clearbut(8,1);clearbut(8,2);clearbut(8,3);'+
  200:  'clearbut(9,1);clearbut(9,2);clearbut(9,3);',
  201: 			  2000);
  202: 
  203:       }
  204: 
  205: // END LON-CAPA Internal
  206: </script>
  207: ENDREGTHIS
  208: 
  209:     } else {
  210:         return (<<ENDDONOTREGTHIS);
  211: 
  212: <script language="JavaScript">
  213: // BEGIN LON-CAPA Internal
  214: 
  215:     function LONCAPAreg() {
  216: 	  menu=window.open("","LONCAPAmenu");
  217:           menu.currentStale=1;
  218:           menu.clearbut(2,1);
  219:           menu.clearbut(2,3);
  220:           menu.clearbut(8,1);
  221:           menu.clearbut(8,2);
  222:           menu.clearbut(8,3);
  223:           if (menu.currentURL) {
  224:              menu.switchbutton
  225:               (3,1,'reload.gif','return','location','go(currentURL)');
  226:  	  } else {
  227: 	      menu.clearbut(3,1);
  228:           }
  229:     }
  230: 
  231:     function LONCAPAstale() {
  232:     }
  233: 
  234: // END LON-CAPA Internal
  235: </script>
  236: ENDDONOTREGTHIS
  237: 
  238:     }
  239: }
  240: 
  241: sub loadevents() {
  242:     return 'LONCAPAreg();';
  243: }
  244: 
  245: sub unloadevents() {
  246:     return 'LONCAPAstale();';
  247: }
  248: 
  249: sub printalltags {
  250:   my $temp;
  251:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  252:     &Apache::lonxml::debug("$temp -- $Apache::lonxml::alltags{$temp}");
  253:   }
  254: }
  255: 
  256: sub xmlparse {
  257:  my ($target,$content_file_string,$safeinit,%style_for_target) = @_;
  258: 
  259:  &setup_globals($target);
  260:  #&printalltags();
  261:  my @pars = ();
  262:  my $pwd=$ENV{'request.filename'};
  263:  $pwd =~ s:/[^/]*$::;
  264:  &newparser(\@pars,\$content_file_string,$pwd);
  265: 
  266:  my $safeeval = new Safe;
  267:  my $safehole = new Safe::Hole;
  268:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  269: #-------------------- Redefinition of the target in the case of compound target
  270: 
  271:  ($target, my @tenta) = split('&&',$target);
  272: 
  273:  my @stack = (); 
  274:  my @parstack = ();
  275:  &initdepth;
  276: 
  277:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  278: 				   $safeeval,\%style_for_target);
  279: 
  280:  return $finaloutput;
  281: }
  282: 
  283: sub inner_xmlparse {
  284:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  285:   &Apache::lonxml::debug('Reentrant parser starting, again?');
  286:   my $finaloutput = '';
  287:   my $result;
  288:   my $token;
  289:   while ( $#$pars > -1 ) {
  290:     while ($token = $$pars['-1']->get_token) {
  291:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  292: 	if ($metamode<1) {
  293: 	  $result=$token->[1];
  294: 	}
  295:       } elsif ($token->[0] eq 'PI') {
  296: 	if ($metamode<1) {
  297: 	  $result=$token->[2];
  298: 	}
  299:       } elsif ($token->[0] eq 'S') {
  300: 	# add tag to stack 	    
  301: 	push (@$stack,$token->[1]);
  302: 	# add parameters list to another stack
  303: 	push (@$parstack,&parstring($token));
  304: 	&increasedepth($token);       
  305: 	if (exists $$style_for_target{$token->[1]}) {
  306: 	  if ($Apache::lonxml::redirection) {
  307: 	    $Apache::lonxml::outputstack['-1'] .=  
  308: 	      &recurse($$style_for_target{$token->[1]},$target,$safeeval,
  309: 		       $style_for_target,@$parstack);
  310: 	  } else {
  311: 	    $finaloutput .= &recurse($$style_for_target{$token->[1]},$target,
  312: 				     $safeeval,$style_for_target,@$parstack);
  313: 	  }
  314: 	} else {
  315: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  316: 			     $parstack, $pars, $safeeval, $style_for_target);
  317: 	}              
  318:       } elsif ($token->[0] eq 'E') {
  319: 	#clear out any tags that didn't end
  320: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  321: 	  &Apache::lonxml::warning("Unbalanced tags in resource $$stack['-1']");
  322: 	  &end_tag($stack,$parstack,$token);
  323: 	}
  324: 		
  325: 	if (exists $$style_for_target{'/'."$token->[1]"}) {
  326: 	  if ($Apache::lonxml::redirection) {
  327: 	    $Apache::lonxml::outputstack['-1'] .=  
  328: 	      &recurse($$style_for_target{'/'."$token->[1]"},
  329: 		       $target,$safeeval,$style_for_target,@$parstack);
  330: 	  } else {
  331: 	    $finaloutput .= &recurse($$style_for_target{'/'."$token->[1]"},
  332: 				     $target,$safeeval,$style_for_target,
  333: 				     @$parstack);
  334: 	  }
  335: 		    
  336: 	} else {
  337: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
  338: 			     $parstack, $pars,$safeeval, $style_for_target);
  339: 	}
  340:       } else {
  341: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  342:       }
  343:       #evaluate variable refs in result
  344:       if ($result ne "") {
  345: 	if ( $#$parstack > -1 ) {
  346: 	  if ($Apache::lonxml::redirection) {
  347: 	    $Apache::lonxml::outputstack['-1'] .= 
  348: 	      &Apache::run::evaluate($result,$safeeval,$$parstack['-1']);
  349: 	  } else {
  350: 	    $finaloutput .= &Apache::run::evaluate($result,$safeeval,
  351: 						   $$parstack['-1']);
  352: 	  }
  353: 	} else {
  354: 	  $finaloutput .= &Apache::run::evaluate($result,$safeeval,'');
  355: 	}
  356: 	$result = '';
  357:       } 
  358:       if ($token->[0] eq 'E') { 
  359: 	&end_tag($stack,$parstack,$token);
  360:       }
  361:     }
  362:     pop @$pars;
  363:     pop @Apache::lonxml::pwd;
  364:   }
  365: 
  366:   # if ($target eq 'meta') {
  367:   #   $finaloutput.=&endredirection;
  368:   # }
  369: 
  370:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  371:     $finaloutput=&afterburn($finaloutput);
  372:   }
  373:   return $finaloutput;
  374: }
  375: 
  376: sub recurse {
  377:   my @innerstack = (); 
  378:   my @innerparstack = ();
  379:   my ($newarg,$target,$safeeval,$style_for_target,@parstack) = @_;
  380:   my @pat = ();
  381:   &newparser(\@pat,\$newarg);
  382:   my $tokenpat;
  383:   my $partstring = '';
  384:   my $output='';
  385:   my $decls='';
  386:   while ( $#pat > -1 ) {
  387:     while  ($tokenpat = $pat[$#pat]->get_token) {
  388:       if (($tokenpat->[0] eq 'T') || ($tokenpat->[0] eq 'C') || ($tokenpat->[0] eq 'D') ) {
  389: 	if ($metamode<1) { $partstring=$tokenpat->[1]; }
  390:       } elsif ($tokenpat->[0] eq 'PI') {
  391: 	if ($metamode<1) { $partstring=$tokenpat->[2]; }
  392:       } elsif ($tokenpat->[0] eq 'S') {
  393: 	push (@innerstack,$tokenpat->[1]);
  394: 	push (@innerparstack,&parstring($tokenpat));
  395: 	&increasedepth($tokenpat);
  396: 	$partstring = &callsub("start_$tokenpat->[1]", $target, $tokenpat,
  397: 			       \@innerstack, \@innerparstack, \@pat,
  398: 			       $safeeval, $style_for_target);
  399:       } elsif ($tokenpat->[0] eq 'E') {
  400: 	#clear out any tags that didn't end
  401: 	while ($tokenpat->[1] ne $innerstack[$#innerstack] 
  402: 	       && ($#innerstack > -1)) {
  403: 	  &Apache::lonxml::warning("Unbalanced tags in resource $innerstack['-1']");
  404: 	  &end_tag(\@innerstack,\@innerparstack,$tokenpat);
  405: 	}
  406: 	$partstring = &callsub("end_$tokenpat->[1]", $target, $tokenpat,
  407: 			       \@innerstack, \@innerparstack, \@pat,
  408: 			       $safeeval, $style_for_target);
  409:       } else {
  410: 	&Apache::lonxml::error("Unknown token event :$tokenpat->[0]:$tokenpat->[1]:");
  411:       }
  412:       #pass both the variable to the style tag, and the tag we 
  413:       #are processing inside the <definedtag>
  414:       if ( $partstring ne "" ) {
  415: 	if ( $#parstack > -1 ) { 
  416: 	  if ( $#innerparstack > -1 ) { 
  417: 	    $decls= $parstack[$#parstack].$innerparstack[$#innerparstack];
  418: 	  } else {
  419: 	    $decls= $parstack[$#parstack];
  420: 	  }
  421: 	} else {
  422: 	  if ( $#innerparstack > -1 ) { 
  423: 	    $decls=$innerparstack[$#innerparstack];
  424: 	  } else {
  425: 	    $decls='';
  426: 	  }
  427: 	}
  428: 	$output .= &Apache::run::evaluate($partstring,$safeeval,$decls);
  429: 	$partstring = '';
  430:       }
  431:       if ($tokenpat->[0] eq 'E') { pop @innerstack;pop @innerparstack;
  432: 				 &decreasedepth($tokenpat);}
  433:     }
  434:     pop @pat;
  435:     pop @Apache::lonxml::pwd;
  436:   }
  437:   return $output;
  438: }
  439: 
  440: sub callsub {
  441:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  442:   my $currentstring='';
  443:   my $nodefault;
  444:   {
  445:     my $sub1;
  446:     no strict 'refs';
  447:     my $tag=$token->[1];
  448:     my $space=$Apache::lonxml::alltags{$tag};
  449:     if (!$space) {
  450: 	$tag=~tr/A-Z/a-z/;
  451: 	$sub=~tr/A-Z/a-z/;
  452: 	$space=$Apache::lonxml::alltags{$tag}
  453:     }
  454: 
  455:     my $deleted=0;
  456:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  457:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  458:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  459: 					     $parstack,$parser,$safeeval,
  460: 					     $style);
  461:     }
  462:     if (!$deleted) {
  463:       if ($space) {
  464: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode<br />\n");
  465: 	$sub1="$space\:\:$sub";
  466: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  467: 					     $parstack,$parser,$safeeval,
  468: 					     $style);
  469:       } else {
  470: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode<br />\n");
  471: 	if ($metamode <1) {
  472: 	  if (defined($token->[4]) && ($metamode < 1)) {
  473: 	    $currentstring = $token->[4];
  474: 	  } else {
  475: 	    $currentstring = $token->[2];
  476: 	  }
  477: 	}
  478:       }
  479:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  480:       if ($currentstring eq '' && $nodefault eq '') {
  481: 	if ($target eq 'edit') {
  482: 	  &Apache::lonxml::debug("doing default edit for $token->[1]");
  483: 	  if ($token->[0] eq 'S') {
  484: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  485: 	  } elsif ($token->[0] eq 'E') {
  486: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  487: 	  }
  488: 	} elsif ($target eq 'modified') {
  489: 	  if ($token->[0] eq 'S') {
  490: 	    $currentstring = $token->[4];
  491: 	    $currentstring.=&Apache::edit::handle_insert();
  492: 	  } else {
  493: 	    $currentstring = $token->[2];
  494: 	  }
  495: 	}
  496:       }
  497:     }
  498:     use strict 'refs';
  499:   }
  500:   return $currentstring;
  501: }
  502: 
  503: sub setup_globals {
  504:   my ($target)=@_;
  505:   $Apache::lonxml::registered = 0;
  506:   @Apache::lonxml::pwd=();
  507:   if ($target eq 'meta') {
  508:     $Apache::lonxml::redirection = 0;
  509:     $Apache::lonxml::metamode = 1;
  510:     $Apache::lonxml::evaluate = 1;
  511:     $Apache::lonxml::import = 0;
  512:   } elsif ($target eq 'grade') {
  513:     &startredirection;
  514:     $Apache::lonxml::metamode = 0;
  515:     $Apache::lonxml::evaluate = 1;
  516:     $Apache::lonxml::import = 1;
  517:   } elsif ($target eq 'modified') {
  518:     $Apache::lonxml::redirection = 0;
  519:     $Apache::lonxml::metamode = 0;
  520:     $Apache::lonxml::evaluate = 0;
  521:     $Apache::lonxml::import = 0;
  522:   } elsif ($target eq 'edit') {
  523:     $Apache::lonxml::redirection = 0;
  524:     $Apache::lonxml::metamode = 0;
  525:     $Apache::lonxml::evaluate = 0;
  526:     $Apache::lonxml::import = 0;
  527:   } else {
  528:     $Apache::lonxml::redirection = 0;
  529:     $Apache::lonxml::metamode = 0;
  530:     $Apache::lonxml::evaluate = 1;
  531:     $Apache::lonxml::import = 1;
  532:   }
  533: }
  534: 
  535: sub init_safespace {
  536:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  537:   $safeeval->permit("entereval");
  538:   $safeeval->permit(":base_math");
  539:   $safeeval->permit("sort");
  540:   $safeeval->deny(":base_io");
  541:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  542:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  543:   
  544:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  545:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  546:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  547:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  548:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  549:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  550:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  551:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  552:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  553:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  554:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  555:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  556:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  557:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  558:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  559:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  560:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  561:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  562:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  563:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  564:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  565:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  566:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  567:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  568:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  569:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  570:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  571:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  572:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  573:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  574:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  575:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  576:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  577:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  578:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  579:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  580:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  581:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  582:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  583:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  584: 
  585: #need to inspect this class of ops
  586: # $safeeval->deny(":base_orig");
  587:   $safeinit .= ';$external::target="'.$target.'";';
  588:   $safeinit .= ';$external::randomseed='.&Apache::lonnet::rndseed().';';
  589:   &Apache::run::run($safeinit,$safeeval);
  590: }
  591: 
  592: sub startredirection {
  593:   $Apache::lonxml::redirection++;
  594:   push (@Apache::lonxml::outputstack, '');
  595: }
  596: 
  597: sub endredirection {
  598:   if (!$Apache::lonxml::redirection) {
  599:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  600:     return '';
  601:   }
  602:   $Apache::lonxml::redirection--;
  603:   pop @Apache::lonxml::outputstack;
  604: }
  605: 
  606: sub end_tag {
  607:   my ($tagstack,$parstack,$token)=@_;
  608:   pop(@$tagstack);
  609:   pop(@$parstack);
  610:   &decreasedepth($token);
  611: }
  612: 
  613: sub initdepth {
  614:   @Apache::lonxml::depthcounter=();
  615:   $Apache::lonxml::depth=-1;
  616:   $Apache::lonxml::olddepth=-1;
  617: }
  618: 
  619: sub increasedepth {
  620:   my ($token) = @_;
  621:   $Apache::lonxml::depth++;
  622:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  623:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  624:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  625:   }
  626:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  627:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  628: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  629: }
  630: 
  631: sub decreasedepth {
  632:   my ($token) = @_;
  633:   $Apache::lonxml::depth--;
  634:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  635:     $#Apache::lonxml::depthcounter--;
  636:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  637:   }
  638:   if (  $Apache::lonxml::depth < -1) {
  639:     &Apache::lonxml::warning("Unbalanced tags in resource");   
  640:     $Apache::lonxml::depth='-1';
  641:   }
  642:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  643:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  644: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  645: }
  646: 
  647: sub get_all_text {
  648: 
  649:  my($tag,$pars)= @_;
  650:  my $depth=0;
  651:  my $token;
  652:  my $result='';
  653:  if ( $tag =~ m:^/: ) { 
  654:    my $tag=substr($tag,1); 
  655: #   &Apache::lonxml::debug("have:$tag:");
  656:    while (($depth >=0) && ($token = $pars->get_token)) {
  657: #     &Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]");
  658:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  659:        $result.=$token->[1];
  660:      } elsif ($token->[0] eq 'PI') {
  661:        $result.=$token->[2];
  662:      } elsif ($token->[0] eq 'S') {
  663:        if ($token->[1] eq $tag) { $depth++; }
  664:        $result.=$token->[4];
  665:      } elsif ($token->[0] eq 'E')  {
  666:        if ( $token->[1] eq $tag) { $depth--; }
  667:        #skip sending back the last end tag
  668:        if ($depth > -1) { $result.=$token->[2]; } else {
  669: 	 $pars->unget_token($token);
  670:        }
  671:      }
  672:    }
  673:  } else {
  674:    while ($token = $pars->get_token) {
  675: #     &Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
  676:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  677:        $result.=$token->[1];
  678:      } elsif ($token->[0] eq 'PI') {
  679:        $result.=$token->[2];
  680:      } elsif ($token->[0] eq 'S') {
  681:        if ( $token->[1] eq $tag) { 
  682: 	 $pars->unget_token($token); last;
  683:        } else {
  684: 	 $result.=$token->[4];
  685:        }
  686:      } elsif ($token->[0] eq 'E')  {
  687:        $result.=$token->[2];
  688:      }
  689:    }
  690:  }
  691: # &Apache::lonxml::debug("Exit:$result:");
  692:  return $result
  693: }
  694: 
  695: sub newparser {
  696:   my ($parser,$contentref,$dir) = @_;
  697:   push (@$parser,HTML::TokeParser->new($contentref));
  698:   $$parser['-1']->xml_mode('1');
  699:   if ( $dir eq '' ) {
  700:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
  701:   } else {
  702:     push (@Apache::lonxml::pwd, $dir);
  703:   } 
  704: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
  705: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
  706: }
  707: 
  708: sub parstring {
  709:   my ($token) = @_;
  710:   my $temp='';
  711:   map {
  712:     unless ($_=~/\W/) {
  713:       my $val=$token->[2]->{$_};
  714:       $val =~ s/([\%\@\\])/\\$1/g;
  715:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
  716:       $temp .= "my \$$_=\"$val\";"
  717:     }
  718:   } @{$token->[3]};
  719:   return $temp;
  720: }
  721: 
  722: sub writeallows {
  723:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
  724:     my $thisdir=$thisurl;
  725:     $thisdir=~s/\/[^\/]+$//;
  726:     my %httpref=();
  727:     map {
  728:        $httpref{'httpref.'.
  729:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;              } @extlinks;
  730:     &Apache::lonnet::appenv(%httpref);
  731: }
  732: 
  733: #
  734: # Afterburner handles anchors, highlights and links
  735: #
  736: sub afterburn {
  737:     my $result=shift;
  738:     map {
  739:        my ($name, $value) = split(/=/,$_);
  740:        $value =~ tr/+/ /;
  741:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  742:        if (($name eq 'highlight')||($name eq 'anchor')||($name eq 'link')) {
  743:            unless ($ENV{'form.'.$name}) {
  744:               $ENV{'form.'.$name}=$value;
  745: 	   }
  746:        }
  747:     } (split(/&/,$ENV{'QUERY_STRING'}));
  748:     if ($ENV{'form.highlight'}) {
  749:         map {
  750:            my $anchorname=$_;
  751: 	   my $matchthis=$anchorname;
  752:            $matchthis=~s/\_+/\\s\+/g;
  753:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
  754:        } split(/\,/,$ENV{'form.highlight'});
  755:     }
  756:     if ($ENV{'form.link'}) {
  757:         map {
  758:            my ($anchorname,$linkurl)=split(/\>/,$_);
  759: 	   my $matchthis=$anchorname;
  760:            $matchthis=~s/\_+/\\s\+/g;
  761:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
  762:        } split(/\,/,$ENV{'form.link'});
  763:     }
  764:     if ($ENV{'form.anchor'}) {
  765:         my $anchorname=$ENV{'form.anchor'};
  766: 	my $matchthis=$anchorname;
  767:         $matchthis=~s/\_+/\\s\+/g;
  768:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
  769:         $result.=(<<"ENDSCRIPT");
  770: <script>
  771:     document.location.hash='$anchorname';
  772: </script>
  773: ENDSCRIPT
  774:     }
  775:     return $result;
  776: }
  777: 
  778: sub storefile {
  779:     my ($file,$contents)=@_;
  780:     if (my $fh=Apache::File->new('>'.$file)) {
  781: 	print $fh $contents;
  782:         $fh->close();
  783:     }
  784: }
  785: 
  786: sub inserteditinfo {
  787:       my ($result,$filecontents)=@_;
  788:       unless ($filecontents) {
  789: 	  $filecontents=(<<SIMPLECONTENT);
  790: <html>
  791: <head>
  792: <title>
  793:                            Title of Document Goes Here
  794: </title>
  795: </head>
  796: <body bgcolor="#FFFFFF">
  797: 
  798:                            Body of Document Goes Here
  799: 
  800: </body>
  801: </html>
  802: SIMPLECONTENT
  803:       }
  804:       my $editheader='<a href="#editsection">Edit below</a><hr />';
  805:       my $editfooter=(<<ENDFOOTER);
  806: <hr />
  807: <a name="editsection" />
  808: <form method="post">
  809: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
  810: <br />
  811: <input type="submit" name="savethisfile" value="Save this file" />
  812: </form>
  813: ENDFOOTER
  814:       $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
  815:       $result=~s/(\<\/body\>)/$editfooter/is;
  816:       return $result;
  817: }
  818: 
  819: sub handler {
  820:   my $request=shift;
  821: 
  822:   my $target='web';
  823: 
  824:   $Apache::lonxml::debug=0;
  825: 
  826:   if ($ENV{'browser.mathml'}) {
  827:     $request->content_type('text/xml');
  828:   } else {
  829:     $request->content_type('text/html');
  830:   }
  831:   
  832:   $request->send_http_header;
  833:   
  834:   return OK if $request->header_only;
  835: 
  836: 
  837:   my $file=&Apache::lonnet::filelocation("",$request->uri);
  838: #
  839: # Edit action? Save file.
  840: #
  841:   unless ($ENV{'request.state'} eq 'published') {
  842:       if ($ENV{'form.savethisfile'}) {
  843: 	  &storefile($file,$ENV{'form.filecont'});
  844:       }
  845:   }
  846:   my %mystyle;
  847:   my $result = ''; 
  848:   my $filecontents=&Apache::lonnet::getfile($file);
  849:   if ($filecontents == -1) {
  850:     $result=(<<ENDNOTFOUND);
  851: <html>
  852: <head>
  853: <title>File not found</title>
  854: </head>
  855: <body bgcolor="#FFFFFF">
  856: <b>File not found: $file</b>
  857: </body>
  858: </html>
  859: ENDNOTFOUND
  860:     $filecontents='';
  861:   } else {
  862:     $result = &Apache::lonxml::xmlparse($target,$filecontents,'',%mystyle);
  863:   }
  864: 
  865: #
  866: # Edit action? Insert editing commands
  867: #
  868:   unless ($ENV{'request.state'} eq 'published') {
  869:       $result=&inserteditinfo($result,$filecontents);
  870:   }
  871: 
  872:   $request->print($result);
  873: 
  874:   writeallows($request->uri);
  875:   return OK;
  876: }
  877:  
  878: sub debug {
  879:   if ($Apache::lonxml::debug eq 1) {
  880:     print("DEBUG:".$_[0]."<br />\n");
  881:   }
  882: }
  883: 
  884: sub error {
  885:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
  886:     print "<b>ERROR:</b>".$_[0]."<br />\n";
  887:   } else {
  888:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
  889:     #notify author
  890:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},$_[0]);
  891:     #notify course
  892:     if ( $ENV{'request.course.id'} ) {
  893:       my $users=$ENV{'course.'.$ENV{'request.course.id'}.'.comment.email'};
  894:       foreach my $user (split /\,/, $users) {
  895: 	($user,my $domain) = split /:/, $user;
  896: 	&Apache::lonmsg::user_normal_msg($user,$domain,"Error in $ENV{'request.filename'}",$_[0]);
  897:       }
  898:     }
  899: 
  900:     #FIXME probably shouldn't have me get everything forever.
  901:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",$_[0]);
  902:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
  903:   }
  904: }
  905: 
  906: sub warning {
  907:   if ($ENV{'request.state'} eq 'construct') {
  908:     print "<b>W</b>ARNING<b>:</b>".$_[0]."<br />\n";
  909:   }
  910: }
  911: 
  912: sub get_param {
  913:   my ($param,$parstack,$safeeval,$context) = @_;
  914:   if ( ! $context ) { $context = -1; }
  915:   my $args ='';
  916:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
  917:   return &Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
  918: }
  919: 
  920: sub register_insert {
  921:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
  922:   my $i;
  923:   my $tagnum=0;
  924:   my @order;
  925:   for ($i=0;$i < $#data; $i++) {
  926:     my $line = $data[$i];
  927:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
  928:     if ( $line =~ /TABLE/ ) { last; }
  929:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
  930:     $insertlist{"$tagnum.tag"} = $tag;
  931:     $insertlist{"$tagnum.description"} = $descrip;
  932:     $insertlist{"$tagnum.color"} = $color;
  933:     $insertlist{"$tagnum.function"} = $function;
  934:     $insertlist{"$tagnum.show"}= $show;
  935:     $insertlist{"$tag.num"}=$tagnum;
  936:     $tagnum++;
  937:   }
  938:   $i++; #skipping TABLE line
  939:   $tagnum = 0;
  940:   for (;$i < $#data;$i++) {
  941:     my $line = $data[$i];
  942:     my ($mnemonic,@which) = split(/ +/,$line);
  943:     my $tag = $insertlist{"$tagnum.tag"};
  944:     for (my $j=0;$j <$#which;$j++) {
  945:       if ( $which[$j] eq 'Y' ) {
  946: 	if ($insertlist{"$j.show"} ne 'no') {
  947: 	  push(@{ $insertlist{"$tag.which"} },$j);
  948: 	}
  949:       }
  950:     }
  951:     $tagnum++;
  952:   }
  953: }
  954: 
  955: sub description {
  956:   my ($token)=@_;
  957:   return $insertlist{$insertlist{"$token->[1].num"}.'.description'};
  958: }
  959: 1;
  960: __END__
  961: 
  962: 

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