File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.111: download - view: text, annotated - select for diffs
Sat Aug 11 20:16:10 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Recursive allow

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

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