File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.91: download - view: text, annotated - select for diffs
Tue Jun 12 21:10:22 2001 UTC (23 years ago) by ng
Branches: MAIN
CVS tags: HEAD
added math::random module
provide safeholes for the random distribution functions, get and set seed
random number generator.

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

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