File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.118: download - view: text, annotated - select for diffs
Sat Aug 18 15:49:28 2001 UTC (22 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Separate generation and printing of token header

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

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