File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.109: download - view: text, annotated - select for diffs
Fri Aug 10 15:49:46 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Anonymous

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

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