File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.93: download - view: text, annotated - select for diffs
Wed Jun 13 20:02:28 2001 UTC (23 years ago) by ng
Branches: MAIN
CVS tags: HEAD
fixed safehole for random_permuted_index

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

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