File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.102: download - view: text, annotated - select for diffs
Thu Jul 12 15:53:44 2001 UTC (22 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- &xmlparse() should work well now.

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

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