File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.90: download - view: text, annotated - select for diffs
Sat Jun 9 14:23:27 2001 UTC (23 years ago) by www
Branches: MAIN
CVS tags: HEAD
Homeworkmenu goes away immediately.

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

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