File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.107: download - view: text, annotated - select for diffs
Tue Aug 7 22:57:50 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Cleanup Button

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

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