File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.105: download - view: text, annotated - select for diffs
Mon Aug 6 19:44:54 2001 UTC (22 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- forgot to say that I had registered the url

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

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