File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.117: download - view: text, annotated - select for diffs
Fri Aug 17 19:50:28 2001 UTC (22 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Generate Token bug fixes

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

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