File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.113: download - view: text, annotated - select for diffs
Wed Aug 15 14:22:07 2001 UTC (22 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Other barcode

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

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