File:  [LON-CAPA] / loncom / xml / lonxml.pm
Revision 1.168: download - view: text, annotated - select for diffs
Wed May 1 21:40:25 2002 UTC (22 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: stable_2002_april, HEAD
- fixes bug#314

    1: # The LearningOnline Network with CAPA
    2: # XML Parser Module 
    3: #
    4: # $Id: lonxml.pm,v 1.168 2002/05/01 21:40:25 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: # last modified 06/26/00 by Alexander Sakharuk
   40: # 11/6 Gerd Kortemeyer
   41: # 6/1/1 Gerd Kortemeyer
   42: # 2/21,3/13 Guy
   43: # 3/29,5/4 Gerd Kortemeyer
   44: # 5/10 Scott Harrison
   45: # 5/26 Gerd Kortemeyer
   46: # 5/27 H. K. Ng
   47: # 6/2,6/3,6/8,6/9 Gerd Kortemeyer
   48: # 6/12,6/13 H. K. Ng
   49: # 6/16 Gerd Kortemeyer
   50: # 7/27 H. K. Ng
   51: # 8/7,8/9,8/10,8/11,8/15,8/16,8/17,8/18,8/20,8/23,8/24 Gerd Kortemeyer
   52: # Guy Albertelli
   53: # 9/26 Gerd Kortemeyer
   54: # Dec Guy Albertelli
   55: # YEAR=2002
   56: # 1/1 Gerd Kortemeyer
   57: # 1/2 Matthew Hall
   58: # 1/3 Gerd Kortemeyer
   59: #
   60: 
   61: package Apache::lonxml; 
   62: use vars 
   63: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace);
   64: use strict;
   65: use HTML::LCParser();
   66: use HTML::TreeBuilder();
   67: use HTML::Entities();
   68: use Safe();
   69: use Safe::Hole();
   70: use Math::Cephes();
   71: use Math::Random();
   72: use Opcode();
   73: 
   74: sub register {
   75:   my ($space,@taglist) = @_;
   76:   foreach my $temptag (@taglist) {
   77:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
   78:   }
   79: }
   80: 
   81: sub deregister {
   82:   my ($space,@taglist) = @_;
   83:   foreach my $temptag (@taglist) {
   84:     my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
   85:     if ($tempspace eq $space) {
   86:       pop(@{ $Apache::lonxml::alltags{$temptag} });
   87:     }
   88:   }
   89:   #&printalltags();
   90: }
   91: 
   92: use Apache::Constants qw(:common);
   93: use Apache::lontexconvert();
   94: use Apache::style();
   95: use Apache::run();
   96: use Apache::londefdef();
   97: use Apache::scripttag();
   98: use Apache::edit();
   99: use Apache::lonnet();
  100: use Apache::File();
  101: use Apache::loncommon();
  102: 
  103: #==================================================   Main subroutine: xmlparse  
  104: #debugging control, to turn on debugging modify the correct handler
  105: $Apache::lonxml::debug=0;
  106: 
  107: #path to the directory containing the file currently being processed
  108: @pwd=();
  109: 
  110: #these two are used for capturing a subset of the output for later processing,
  111: #don't touch them directly use &startredirection and &endredirection
  112: @outputstack = ();
  113: $redirection = 0;
  114: 
  115: #controls wheter the <import> tag actually does
  116: $import = 1;
  117: @extlinks=();
  118: 
  119: # meta mode is a bit weird only some output is to be turned off
  120: #<output> tag turns metamode off (defined in londefdef.pm)
  121: $metamode = 0;
  122: 
  123: # turns on and of run::evaluate actually derefencing var refs
  124: $evaluate = 1;
  125: 
  126: # data structure for eidt mode, determines what tags can go into what other tags
  127: %insertlist=();
  128: 
  129: # stores the list of active tag namespaces
  130: @namespace=();
  131: 
  132: # has the dynamic menu been updated to know about this resource
  133: $Apache::lonxml::registered=0;
  134: 
  135: sub xmlbegin {
  136:   my $output='';
  137:   if ($ENV{'browser.mathml'}) {
  138:       $output='<?xml version="1.0"?>'
  139:             .'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'
  140:             .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
  141:             .'[<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">]>'
  142:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
  143: 		.'xmlns="http://www.w3.org/TR/REC-html40">';
  144:   } else {
  145:       $output='<html>';
  146:   }
  147:   return $output;
  148: }
  149: 
  150: sub xmlend {
  151:     my $discussion='';
  152:     if ($ENV{'request.course.id'}) {
  153:        my $crs='/'.$ENV{'request.course.id'};
  154:        if ($ENV{'request.course.sec'}) {
  155:           $crs.='_'.$ENV{'request.course.sec'};
  156:        }                 
  157:        $crs=~s/\_/\//g;
  158:        my $seeid=&Apache::lonnet::allowed('rin',$crs);
  159:        my $symb=&Apache::lonnet::symbread();
  160:        if ($symb) {
  161:           my %contrib=&Apache::lonnet::restore($symb,$ENV{'request.course.id'},
  162:                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  163: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  164:           if ($contrib{'version'}) {
  165:               $discussion.=
  166:                   '<address><hr /><h2>Course Discussion of Resource</h2>';
  167:               my $idx;
  168:               for ($idx=1;$idx<=$contrib{'version'};$idx++) {
  169: 		my $hidden=($contrib{'hidden'}=~/\.$idx\./);
  170: 		unless (($hidden) && (!$seeid)) {
  171:                  my $message=$contrib{$idx.':message'};
  172:                  $message=~s/\n/\<br \/\>/g;
  173:                  if ($message) {
  174:                   if ($hidden) {
  175: 		      $message='<font color="#888888">'.$message.'</font>';
  176:                   }
  177:                   my $sender='Anonymous';
  178:                   if ((!$contrib{$idx.':anonymous'}) || ($seeid)) {
  179:                       $sender=$contrib{$idx.':plainname'}.' ('.
  180:                               $contrib{$idx.':sendername'}.' at '.
  181: 		      $contrib{$idx.':senderdomain'}.')';
  182:                       if ($contrib{$idx.':anonymous'}) {
  183: 			  $sender.=' [anonymous] '.
  184:                                      $contrib{$idx.':screenname'};
  185:                       }
  186:                       if ($seeid) {
  187: 			  if ($hidden) {
  188:                              $sender.=' <a href="/adm/feedback?unhide='.
  189: 				 $symb.':::'.$idx.'">Make Visible</a>';
  190:                           } else {
  191:                              $sender.=' <a href="/adm/feedback?hide='.
  192: 				 $symb.':::'.$idx.'">Hide</a>';
  193: 			  }
  194:                       }                   
  195:                   } else {
  196:                       if ($contrib{$idx.':screenname'}) {
  197: 			  $sender='<i>'.$contrib{$idx.':screenname'}.'</i>';
  198:                       }
  199:                   }
  200: 		  $discussion.='<p><b>'.$sender.'</b> ('.
  201:                       localtime($contrib{$idx.':timestamp'}).
  202:                       '):<blockquote>'.$message.
  203:                       '</blockquote></p>';
  204: 	        }
  205:                } 
  206:               }
  207:               $discussion.='</address>';
  208:           }
  209:        }
  210:     }
  211:     return $discussion.'</html>';
  212: }
  213: 
  214: sub tokeninputfield {
  215:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
  216:     $defhost=~tr/a-z/A-Z/;
  217:     return (<<ENDINPUTFIELD)
  218: <script>
  219:     function updatetoken() {
  220: 	var comp=new Array;
  221:         var barcode=unescape(document.tokeninput.barcode.value);
  222:         comp=barcode.split('*');
  223:         if (typeof(comp[0])!="undefined") {
  224: 	    document.tokeninput.codeone.value=comp[0];
  225: 	}
  226:         if (typeof(comp[1])!="undefined") {
  227: 	    document.tokeninput.codetwo.value=comp[1];
  228: 	}
  229:         if (typeof(comp[2])!="undefined") {
  230:             comp[2]=comp[2].toUpperCase();
  231: 	    document.tokeninput.codethree.value=comp[2];
  232: 	}
  233:         document.tokeninput.barcode.value='';
  234:     }  
  235: </script>
  236: <form method="post" name="tokeninput">
  237: <table border="2" bgcolor="#FFFFBB">
  238: <tr><th>DocID Checkin</th></tr>
  239: <tr><td>
  240: <table>
  241: <tr>
  242: <td>Scan in Barcode</td>
  243: <td><input type="text" size="22" name="barcode" 
  244: onChange="updatetoken()"/></td>
  245: </tr>
  246: <tr><td><i>or</i> Type in DocID</td>
  247: <td>
  248: <input type="text" size="5" name="codeone" />
  249: <b><font size="+2">*</font></b>
  250: <input type="text" size="5" name="codetwo" />
  251: <b><font size="+2">*</font></b>
  252: <input type="text" size="10" name="codethree" value="$defhost" 
  253: onChange="this.value=this.value.toUpperCase()" />
  254: </td></tr>
  255: </table>
  256: </td></tr>
  257: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
  258: </table>
  259: </form>
  260: ENDINPUTFIELD
  261: }
  262: 
  263: sub maketoken {
  264:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
  265:     unless ($symb) {
  266: 	$symb=&Apache::lonnet::symbread();
  267:     }
  268:     unless ($tuname) {
  269: 	$tuname=$ENV{'user.name'};
  270:         $tudom=$ENV{'user.domain'};
  271:         $tcrsid=$ENV{'request.course.id'};
  272:     }
  273: 
  274:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
  275: }
  276: 
  277: sub printtokenheader {
  278:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
  279:     unless ($token) { return ''; }
  280: 
  281:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  282:     unless ($tsymb) {
  283: 	$tsymb=$symb;
  284:     }
  285:     unless ($tuname) {
  286: 	$tuname=$name;
  287:         $tudom=$domain;
  288:         $tcrsid=$courseid;
  289:     }
  290: 
  291:     my %reply=&Apache::lonnet::get('environment',
  292:               ['firstname','middlename','lastname','generation'],
  293:               $tudom,$tuname);
  294:     my $plainname=$reply{'firstname'}.' '. 
  295:                   $reply{'middlename'}.' '.
  296:                   $reply{'lastname'}.' '.
  297: 		  $reply{'generation'};
  298: 
  299:     if ($target eq 'web') {
  300:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
  301: 	return 
  302:  '<img align="right" src="/cgi-bin/barcode.gif?encode='.$token.'" />'.
  303:                'Checked out for '.$plainname.
  304:                '<br />User: '.$tuname.' at '.$tudom.
  305: 	       '<br />ID: '.$idhash{$tuname}.
  306: 	       '<br />CourseID: '.$tcrsid.
  307: 	       '<br />Course: '.$ENV{'course.'.$tcrsid.'.description'}.
  308:                '<br />DocID: '.$token.
  309:                '<br />Time: '.localtime().'<hr />';
  310:     } else {
  311:         return $token;
  312:     }
  313: }
  314: 
  315: sub fontsettings() {
  316:     my $headerstring='';
  317:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
  318:          $headerstring.=
  319:              '<meta Content-Type="text/html; charset=x-mac-roman">';
  320:     }
  321:     return $headerstring;
  322: }
  323: 
  324: sub registerurl {
  325:     my $forcereg=shift;
  326:     my $target = shift;
  327:     my $result = '';
  328:     if (($ENV{'request.publicaccess'}) || 
  329:        ($ENV{'REQUEST_URI'} eq '/res/adm/pages/menu.html')) {
  330: 	return 
  331:          '<script>function LONCAPAreg(){} function LONCAPAstale(){}</script>';
  332:     }
  333:     if ($Apache::lonxml::registered && !$forcereg) { return ''; }
  334:     $Apache::lonxml::registered=1;
  335:     my $nothing='';
  336:     if ($ENV{'browser.type'} eq 'explorer') { $nothing='javascript:void(0);'; }
  337:     if (($ENV{'REQUEST_URI'}!~/^\/(res\/)*adm\//) || ($forcereg)) {
  338:         my $hwkadd='';
  339:         if ($ENV{'request.filename'}=~/\.(problem|exam|quiz|assess|survey|form)$/) {
  340: 	    if (&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) {
  341: 		$hwkadd.=(<<ENDSUBM);
  342:                      menu.switchbutton(7,1,'subm.gif','view sub','missions','gocmd("/adm/grades","submission")');
  343: ENDSUBM
  344:             }
  345: 	    if (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) {
  346: 		$hwkadd.=(<<ENDGRDS);
  347:                      menu.switchbutton(7,2,'pgrd.gif','problem','grades','gocmd("/adm/grades","viewgrades")');
  348: ENDGRDS
  349:             }
  350: 	    if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  351: 		$hwkadd.=(<<ENDPARM);
  352:                      menu.switchbutton(7,3,'pparm.gif','problem','parms','gocmd("/adm/parmset","set")');
  353: ENDPARM
  354:             }
  355: 	}
  356: 	$result = (<<ENDREGTHIS);
  357:      
  358: <script language="JavaScript">
  359: // BEGIN LON-CAPA Internal
  360: 
  361:     function LONCAPAreg() {
  362: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
  363:           menu.clearTimeout(menu.menucltim);
  364: 	  menu.currentURL=window.location.pathname;
  365:           menu.currentStale=0;
  366:           menu.clearbut(3,1);
  367:           menu.switchbutton
  368:        (6,3,'catalog.gif','catalog','info','catalog_info()');
  369:           menu.switchbutton
  370:        (8,1,'eval.gif','evaluate','this','gopost("/adm/evaluate",currentURL)');
  371:           menu.switchbutton
  372:     (8,2,'fdbk.gif','feedback','on this','gopost("/adm/feedback",currentURL)');
  373:           menu.switchbutton
  374:      (8,3,'prt.gif','prepare','printout','gopost("/adm/printout",currentURL)');
  375:           menu.switchbutton
  376:        (2,1,'back.gif','backward','','gopost("/adm/flip","back:"+currentURL)');
  377:           menu.switchbutton
  378:      (2,3,'forw.gif','forward','','gopost("/adm/flip","forward:"+currentURL)');
  379:           menu.switchbutton
  380:                             (9,1,'sbkm.gif','set','bookmark','set_bookmark()');
  381:           menu.switchbutton
  382:                          (9,2,'vbkm.gif','view','bookmark','edit_bookmarks()');
  383:           menu.switchbutton
  384:                                (9,3,'anot.gif','anno-','tations','annotate()');
  385:           $hwkadd
  386:     }
  387: 
  388:     function LONCAPAstale() {
  389: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
  390:           menu.currentStale=1;
  391:           menu.switchbutton
  392:              (3,1,'reload.gif','return','location','go(currentURL)');
  393:           menu.clearbut(7,1);
  394:           menu.clearbut(7,2);
  395:           menu.clearbut(7,3);
  396:           menu.menucltim=menu.setTimeout(
  397:  'clearbut(2,1);clearbut(2,3);clearbut(8,1);clearbut(8,2);clearbut(8,3);'+
  398:  'clearbut(9,1);clearbut(9,2);clearbut(9,3);clearbut(6,3)',
  399: 			  2000);
  400: 
  401:       }
  402: 
  403: // END LON-CAPA Internal
  404: </script>
  405: ENDREGTHIS
  406: 
  407:     } else {
  408:         $result = (<<ENDDONOTREGTHIS);
  409: 
  410: <script language="JavaScript">
  411: // BEGIN LON-CAPA Internal
  412: 
  413:     function LONCAPAreg() {
  414: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
  415:           menu.currentStale=1;
  416:           menu.clearbut(2,1);
  417:           menu.clearbut(2,3);
  418:           menu.clearbut(8,1);
  419:           menu.clearbut(8,2);
  420:           menu.clearbut(8,3);
  421:           if (menu.currentURL) {
  422:              menu.switchbutton
  423:               (3,1,'reload.gif','return','location','go(currentURL)');
  424:  	  } else {
  425: 	      menu.clearbut(3,1);
  426:           }
  427:     }
  428: 
  429:     function LONCAPAstale() {
  430:     }
  431: 
  432: // END LON-CAPA Internal
  433: </script>
  434: ENDDONOTREGTHIS
  435:     }
  436:     if ($target eq 'edit') {
  437: 	# Javascript routines for construction space:
  438: 	# openbrowser and opensearcher will start the file browser
  439: 	# (lonindexer) and searcher (lonsearchcat) respectively.
  440: 	# Inputs are the name of the html form being used
  441: 	# and the name of the element the selected URL should
  442: 	# be placed in.
  443:         # openbrowser also takes arguments only and omit, which are
  444:         # comma deliminated lists of file extensions to (only) show 
  445:         # or omit.
  446:         # Here we also set currentURL=null.
  447:         $result .=<<"ENDBROWSERSCRIPT";
  448: <script>
  449:     menu.currentURL=null;
  450:     var editbrowser;
  451:     function openbrowser(formname,elementname,only,omit) {
  452:         var url = '/res/?';
  453:         if (editbrowser == null) {
  454:             url += 'launch=1&';
  455:         }
  456:         url += 'catalogmode=interactive&';
  457:         url += 'mode=edit&';
  458:         url += 'form=' + formname + '&';
  459:         if (only != null) {
  460:             url += 'only=' + only + '&';
  461:         } 
  462:         if (omit != null) {
  463:             url += 'omit=' + omit + '&';
  464:         }
  465:         url += 'element=' + elementname + '';
  466:         var title = 'Browser';
  467:         var options = 'scrollbars=1,resizable=1,menubar=0';
  468:         options += ',width=700,height=600';
  469:         editbrowser = open(url,title,options,'1');
  470:         editbrowser.focus();
  471:     }
  472:     var editsearcher;
  473:     function opensearcher(formname,elementname) {
  474:         var url = '/adm/searchcat?';
  475:         if (editsearcher == null) {
  476:             url += 'launch=1&';
  477:         }
  478:         url += 'catalogmode=interactive&';
  479:         url += 'mode=edit&';
  480:         url += 'form=' + formname + '&';
  481:         url += 'element=' + elementname + '';
  482:         var title = 'Search';
  483:         var options = 'scrollbars=1,resizable=1,menubar=0';
  484:         options += ',width=700,height=600';
  485:         editsearcher = open(url,title,options,'1');
  486:         editsearcher.focus();
  487:     }
  488: </script>
  489: ENDBROWSERSCRIPT
  490:     }
  491:     return $result;
  492: }
  493: 
  494: sub loadevents() {
  495:     return 'LONCAPAreg();';
  496: }
  497: 
  498: sub unloadevents() {
  499:     return 'LONCAPAstale();';
  500: }
  501: 
  502: sub printalltags {
  503:   my $temp;
  504:   foreach $temp (sort keys %Apache::lonxml::alltags) {
  505:     &Apache::lonxml::debug("$temp -- ".
  506: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
  507:   }
  508: }
  509: 
  510: sub xmlparse {
  511:  my ($target,$content_file_string,$safeinit,%style_for_target) = @_;
  512: 
  513:  &setup_globals($target);
  514:  #&printalltags();
  515:  my @pars = ();
  516:  my $pwd=$ENV{'request.filename'};
  517:  $pwd =~ s:/[^/]*$::;
  518:  &newparser(\@pars,\$content_file_string,$pwd);
  519: 
  520:  my $safeeval = new Safe;
  521:  my $safehole = new Safe::Hole;
  522:  &init_safespace($target,$safeeval,$safehole,$safeinit);
  523: #-------------------- Redefinition of the target in the case of compound target
  524: 
  525:  ($target, my @tenta) = split('&&',$target);
  526: 
  527:  my @stack = ();
  528:  my @parstack = ();
  529:  &initdepth;
  530: 
  531:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
  532: 				   $safeeval,\%style_for_target);
  533:  if ($ENV{'request.uri'}) {
  534:     &writeallows($ENV{'request.uri'});
  535:  }
  536:  return $finaloutput;
  537: }
  538: 
  539: sub htmlclean {
  540:     my ($raw,$full)=@_;
  541: 
  542:     my $tree = HTML::TreeBuilder->new;
  543:     $tree->ignore_unknown(0);
  544: 
  545:     $tree->parse($raw);
  546: 
  547:     my $output= $tree->as_HTML(undef,' ');
  548: 
  549:     $output=~s/\<(br|hr|img|meta|allow)(.*?)\>/\<$1$2 \/\>/gis;
  550:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
  551:     unless ($full) {
  552:        $output=~s/\<[\/]*(body|head|html)\>//gis;
  553:     }
  554: 
  555:     $tree = $tree->delete;
  556: 
  557:     return $output;
  558: }
  559: 
  560: sub inner_xmlparse {
  561:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
  562:   my $finaloutput = '';
  563:   my $result;
  564:   my $token;
  565:   while ( $#$pars > -1 ) {
  566:     while ($token = $$pars['-1']->get_token) {
  567:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
  568: 	if ($metamode<1) {
  569: 	  $result=$token->[1];
  570: 	}
  571:       } elsif ($token->[0] eq 'PI') {
  572: 	if ($metamode<1) {
  573: 	  $result=$token->[2];
  574: 	}
  575:       } elsif ($token->[0] eq 'S') {
  576: 	# add tag to stack
  577: 	push (@$stack,$token->[1]);
  578: 	# add parameters list to another stack
  579: 	push (@$parstack,&parstring($token));
  580: 	&increasedepth($token);
  581: 	if (exists $$style_for_target{$token->[1]}) {
  582: 	  if ($Apache::lonxml::redirection) {
  583: 	    $Apache::lonxml::outputstack['-1'] .=
  584: 	      &recurse($$style_for_target{$token->[1]},$target,$safeeval,
  585: 		       $style_for_target,@$parstack);
  586: 	  } else {
  587: 	    $finaloutput .= &recurse($$style_for_target{$token->[1]},$target,
  588: 				     $safeeval,$style_for_target,@$parstack);
  589: 	  }
  590: 	} else {
  591: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
  592: 			     $parstack, $pars, $safeeval, $style_for_target);
  593: 	}
  594:       } elsif ($token->[0] eq 'E') {
  595: 	#clear out any tags that didn't end
  596: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
  597: 	  my $lasttag=$$stack[-1];
  598: 	  if ($token->[1] =~ /^$lasttag$/i) {
  599: 	    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; as end tag to &lt;'.$$stack[-1].'&gt;');
  600: 	    last;
  601: 	  } else {
  602: 	    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; when looking for &lt;/'.$$stack[-1].'&gt; in file');
  603: 	    &end_tag($stack,$parstack,$token);
  604: 	  }
  605: 	}
  606: 
  607: 	if (exists($$style_for_target{'/'."$token->[1]"})) {
  608: 	  if ($Apache::lonxml::redirection) {
  609: 	    $Apache::lonxml::outputstack['-1'] .=  
  610: 	      &recurse($$style_for_target{'/'."$token->[1]"},
  611: 		       $target,$safeeval,$style_for_target,@$parstack);
  612: 	  } else {
  613: 	    $finaloutput .= &recurse($$style_for_target{'/'."$token->[1]"},
  614: 				     $target,$safeeval,$style_for_target,
  615: 				     @$parstack);
  616: 	  }
  617: 	} else {
  618: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
  619: 			     $parstack, $pars,$safeeval, $style_for_target);
  620: 	}
  621:       } else {
  622: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
  623:       }
  624:       #evaluate variable refs in result
  625:       if ($result ne "") {
  626: 	if ( $#$parstack > -1 ) {
  627: 	  if ($Apache::lonxml::redirection) {
  628: 	    $Apache::lonxml::outputstack['-1'] .= 
  629: 	      &Apache::run::evaluate($result,$safeeval,$$parstack['-1']);
  630: 	  } else {
  631: 	    $finaloutput .= &Apache::run::evaluate($result,$safeeval,
  632: 						   $$parstack['-1']);
  633: 	  }
  634: 	} else {
  635: 	  $finaloutput .= &Apache::run::evaluate($result,$safeeval,'');
  636: 	}
  637: 	$result = '';
  638:       }
  639:       if ($token->[0] eq 'E') { 
  640: 	&end_tag($stack,$parstack,$token);
  641:       }
  642:     }
  643:     pop @$pars;
  644:     pop @Apache::lonxml::pwd;
  645:   }
  646: 
  647:   # if ($target eq 'meta') {
  648:   #   $finaloutput.=&endredirection;
  649:   # }
  650: 
  651:   # Encode any high ASCII characters
  652:   $finaloutput=&HTML::Entities::encode($finaloutput,"\200-\377");
  653:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
  654:     $finaloutput=&afterburn($finaloutput);
  655:   }
  656:   return $finaloutput;
  657: }
  658: 
  659: sub recurse {
  660:   my @innerstack = (); 
  661:   my @innerparstack = ();
  662:   my ($newarg,$target,$safeeval,$style_for_target,@parstack) = @_;
  663:   my @pat = ();
  664:   &newparser(\@pat,\$newarg);
  665:   my $tokenpat;
  666:   my $partstring = '';
  667:   my $output='';
  668:   my $decls='';
  669:   &Apache::lonxml::debug("Recursing");
  670:   while ( $#pat > -1 ) {
  671:     while  ($tokenpat = $pat[$#pat]->get_token) {
  672:       if (($tokenpat->[0] eq 'T') || ($tokenpat->[0] eq 'C') || ($tokenpat->[0] eq 'D') ) {
  673: 	if ($metamode<1) { $partstring=$tokenpat->[1]; }
  674:       } elsif ($tokenpat->[0] eq 'PI') {
  675: 	if ($metamode<1) { $partstring=$tokenpat->[2]; }
  676:       } elsif ($tokenpat->[0] eq 'S') {
  677: 	push (@innerstack,$tokenpat->[1]);
  678: 	push (@innerparstack,&parstring($tokenpat));
  679: 	&increasedepth($tokenpat);
  680: 	$partstring = &callsub("start_$tokenpat->[1]", $target, $tokenpat,
  681: 			       \@innerstack, \@innerparstack, \@pat,
  682: 			       $safeeval, $style_for_target);
  683:       } elsif ($tokenpat->[0] eq 'E') {
  684: 	#clear out any tags that didn't end
  685: 	while ($tokenpat->[1] ne $innerstack[$#innerstack]
  686: 	       && ($#innerstack > -1)) {
  687: 	  my $lasttag=$innerstack[-1];
  688: 	  if ($tokenpat->[1] =~ /^$lasttag$/i) {
  689: 	    &Apache::lonxml::warning('Using tag &lt;/'.$tokenpat->[1].'&gt; as end tag to &lt;'.$innerstack[-1].'&gt;');
  690: 	    last;
  691: 	  } else {
  692: 	    &Apache::lonxml::warning('Found tag &lt;/'.$tokenpat->[1].'&gt; when looking for &lt;/'.$innerstack[-1].'&gt; in file');
  693: 	    &end_tag(\@innerstack,\@innerparstack,$tokenpat);
  694: 	  }
  695: 	}
  696: 	$partstring = &callsub("end_$tokenpat->[1]", $target, $tokenpat,
  697: 			       \@innerstack, \@innerparstack, \@pat,
  698: 			       $safeeval, $style_for_target);
  699:       } else {
  700: 	&Apache::lonxml::error("Unknown token event :$tokenpat->[0]:$tokenpat->[1]:");
  701:       }
  702:       #pass both the variable to the style tag, and the tag we 
  703:       #are processing inside the <definedtag>
  704:       if ( $partstring ne "" ) {
  705: 	if ( $#parstack > -1 ) { 
  706: 	  if ( $#innerparstack > -1 ) { 
  707: 	    $decls= $parstack[$#parstack].$innerparstack[$#innerparstack];
  708: 	  } else {
  709: 	    $decls= $parstack[$#parstack];
  710: 	  }
  711: 	} else {
  712: 	  if ( $#innerparstack > -1 ) { 
  713: 	    $decls=$innerparstack[$#innerparstack];
  714: 	  } else {
  715: 	    $decls='';
  716: 	  }
  717: 	}
  718: 	$output .= &Apache::run::evaluate($partstring,$safeeval,$decls);
  719: 	$partstring = '';
  720:       }
  721:       if ($tokenpat->[0] eq 'E') { pop @innerstack;pop @innerparstack;
  722: 				 &decreasedepth($tokenpat);}
  723:     }
  724:     pop @pat;
  725:     pop @Apache::lonxml::pwd;
  726:   }
  727:   &Apache::lonxml::debug("Exiting Recursing");
  728:   return $output;
  729: }
  730: 
  731: sub callsub {
  732:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  733:   my $currentstring='';
  734:   my $nodefault;
  735:   {
  736:     my $sub1;
  737:     no strict 'refs';
  738:     my $tag=$token->[1];
  739:     my $space=$Apache::lonxml::alltags{$tag}[-1];
  740:     if (!$space) {
  741:      	$tag=~tr/A-Z/a-z/;
  742: 	$sub=~tr/A-Z/a-z/;
  743: 	$space=$Apache::lonxml::alltags{$tag}[-1]
  744:     }
  745: 
  746:     my $deleted=0;
  747:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
  748:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
  749:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
  750: 					     $parstack,$parser,$safeeval,
  751: 					     $style);
  752:     }
  753:     if (!$deleted) {
  754:       if ($space) {
  755: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
  756: 	$sub1="$space\:\:$sub";
  757: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
  758: 					     $parstack,$parser,$safeeval,
  759: 					     $style);
  760:       } else {
  761: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
  762: 	if ($metamode <1) {
  763: 	  if (defined($token->[4]) && ($metamode < 1)) {
  764: 	    $currentstring = $token->[4];
  765: 	  } else {
  766: 	    $currentstring = $token->[2];
  767: 	  }
  768: 	}
  769:       }
  770:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
  771:       if ($currentstring eq '' && $nodefault eq '') {
  772: 	if ($target eq 'edit') {
  773: 	  &Apache::lonxml::debug("doing default edit for $token->[1]");
  774: 	  if ($token->[0] eq 'S') {
  775: 	    $currentstring = &Apache::edit::tag_start($target,$token);
  776: 	  } elsif ($token->[0] eq 'E') {
  777: 	    $currentstring = &Apache::edit::tag_end($target,$token);
  778: 	  }
  779: 	} elsif ($target eq 'modified') {
  780: 	  if ($token->[0] eq 'S') {
  781: 	    $currentstring = $token->[4];
  782: 	    $currentstring.=&Apache::edit::handle_insert();
  783: 	  } else {
  784: 	    $currentstring = $token->[2];
  785: 	  }
  786: 	}
  787:       }
  788:     }
  789:     use strict 'refs';
  790:   }
  791:   return $currentstring;
  792: }
  793: 
  794: sub setup_globals {
  795:   my ($target)=@_;
  796:   $Apache::lonxml::registered = 0;
  797:   @Apache::lonxml::pwd=();
  798:   @Apache::lonxml::extlinks=();
  799:   if ($target eq 'meta') {
  800:     $Apache::lonxml::redirection = 0;
  801:     $Apache::lonxml::metamode = 1;
  802:     $Apache::lonxml::evaluate = 1;
  803:     $Apache::lonxml::import = 0;
  804:   } elsif ($target eq 'answer') {
  805:     $Apache::lonxml::redirection = 0;
  806:     $Apache::lonxml::metamode = 1;
  807:     $Apache::lonxml::evaluate = 1;
  808:     $Apache::lonxml::import = 1;
  809:   } elsif ($target eq 'grade') {
  810:     &startredirection;
  811:     $Apache::lonxml::metamode = 0;
  812:     $Apache::lonxml::evaluate = 1;
  813:     $Apache::lonxml::import = 1;
  814:   } elsif ($target eq 'modified') {
  815:     $Apache::lonxml::redirection = 0;
  816:     $Apache::lonxml::metamode = 0;
  817:     $Apache::lonxml::evaluate = 0;
  818:     $Apache::lonxml::import = 0;
  819:   } elsif ($target eq 'edit') {
  820:     $Apache::lonxml::redirection = 0;
  821:     $Apache::lonxml::metamode = 0;
  822:     $Apache::lonxml::evaluate = 0;
  823:     $Apache::lonxml::import = 0;
  824:   } elsif ($target eq 'analyze') {
  825:     $Apache::lonxml::redirection = 0;
  826:     $Apache::lonxml::metamode = 0;
  827:     $Apache::lonxml::evaluate = 1;
  828:     $Apache::lonxml::import = 1;
  829:   } else {
  830:     $Apache::lonxml::redirection = 0;
  831:     $Apache::lonxml::metamode = 0;
  832:     $Apache::lonxml::evaluate = 1;
  833:     $Apache::lonxml::import = 1;
  834:   }
  835: }
  836: 
  837: sub init_safespace {
  838:   my ($target,$safeeval,$safehole,$safeinit) = @_;
  839:   $safeeval->permit("entereval");
  840:   $safeeval->permit(":base_math");
  841:   $safeeval->permit("sort");
  842:   $safeeval->deny(":base_io");
  843:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
  844:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  845:   
  846:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
  847:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
  848:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
  849:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
  850:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
  851:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
  852:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
  853:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
  854:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
  855:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
  856:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
  857:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
  858:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
  859:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
  860:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
  861:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
  862:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
  863:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
  864:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
  865:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
  866:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
  867:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
  868:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
  869:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
  870:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
  871:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
  872:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
  873:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
  874:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
  875:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
  876:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
  877:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
  878:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
  879:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
  880:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
  881:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
  882:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
  883:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
  884:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
  885:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
  886: 
  887: #need to inspect this class of ops
  888: # $safeeval->deny(":base_orig");
  889:   $safeinit .= ';$external::target="'.$target.'";';
  890:   my $rndseed;
  891:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  892:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
  893:   $safeinit .= ';$external::randomseed='.$rndseed.';';
  894:   &Apache::run::run($safeinit,$safeeval);
  895: }
  896: 
  897: sub startredirection {
  898:   $Apache::lonxml::redirection++;
  899:   push (@Apache::lonxml::outputstack, '');
  900: }
  901: 
  902: sub endredirection {
  903:   if (!$Apache::lonxml::redirection) {
  904:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
  905:     return '';
  906:   }
  907:   $Apache::lonxml::redirection--;
  908:   pop @Apache::lonxml::outputstack;
  909: }
  910: 
  911: sub end_tag {
  912:   my ($tagstack,$parstack,$token)=@_;
  913:   pop(@$tagstack);
  914:   pop(@$parstack);
  915:   &decreasedepth($token);
  916: }
  917: 
  918: sub initdepth {
  919:   @Apache::lonxml::depthcounter=();
  920:   $Apache::lonxml::depth=-1;
  921:   $Apache::lonxml::olddepth=-1;
  922: }
  923: 
  924: sub increasedepth {
  925:   my ($token) = @_;
  926:   $Apache::lonxml::depth++;
  927:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
  928:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
  929:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
  930:   }
  931:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  932:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
  933: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
  934: }
  935: 
  936: sub decreasedepth {
  937:   my ($token) = @_;
  938:   $Apache::lonxml::depth--;
  939:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
  940:     $#Apache::lonxml::depthcounter--;
  941:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
  942:   }
  943:   if (  $Apache::lonxml::depth < -1) {
  944:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
  945:     $Apache::lonxml::depth='-1';
  946:   }
  947:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
  948:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
  949: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
  950: }
  951: 
  952: sub get_all_text {
  953: 
  954:  my($tag,$pars)= @_;
  955:  my $depth=0;
  956:  my $token;
  957:  my $result='';
  958:  if ( $tag =~ m:^/: ) { 
  959:    my $tag=substr($tag,1); 
  960: #   &Apache::lonxml::debug("have:$tag:");
  961:    while (($depth >=0) && ($token = $pars->get_token)) {
  962: #     &Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]");
  963:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  964:        $result.=$token->[1];
  965:      } elsif ($token->[0] eq 'PI') {
  966:        $result.=$token->[2];
  967:      } elsif ($token->[0] eq 'S') {
  968:        if ($token->[1] =~ /^$tag$/i) { $depth++; }
  969:        $result.=$token->[4];
  970:      } elsif ($token->[0] eq 'E')  {
  971:        if ( $token->[1] =~ /^$tag$/i) { $depth--; }
  972:        #skip sending back the last end tag
  973:        if ($depth > -1) { $result.=$token->[2]; } else {
  974: 	 $pars->unget_token($token);
  975:        }
  976:      }
  977:    }
  978:  } else {
  979:    while ($token = $pars->get_token) {
  980: #     &Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
  981:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  982:        $result.=$token->[1];
  983:      } elsif ($token->[0] eq 'PI') {
  984:        $result.=$token->[2];
  985:      } elsif ($token->[0] eq 'S') {
  986:        if ( $token->[1] =~ /^$tag$/i) {
  987: 	 $pars->unget_token($token); last;
  988:        } else {
  989: 	 $result.=$token->[4];
  990:        }
  991:      } elsif ($token->[0] eq 'E')  {
  992:        $result.=$token->[2];
  993:      }
  994:    }
  995:  }
  996: # &Apache::lonxml::debug("Exit:$result:");
  997:  return $result
  998: }
  999: 
 1000: sub newparser {
 1001:   my ($parser,$contentref,$dir) = @_;
 1002:   push (@$parser,HTML::LCParser->new($contentref));
 1003:   $$parser['-1']->xml_mode('1');
 1004:   if ( $dir eq '' ) {
 1005:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
 1006:   } else {
 1007:     push (@Apache::lonxml::pwd, $dir);
 1008:   } 
 1009: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
 1010: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
 1011: }
 1012: 
 1013: sub parstring {
 1014:   my ($token) = @_;
 1015:   my $temp='';
 1016:   foreach (@{$token->[3]}) {
 1017:     unless ($_=~/\W/) {
 1018:       my $val=$token->[2]->{$_};
 1019:       $val =~ s/([\%\@\\\"])/\\$1/g;
 1020:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
 1021:       $temp .= "my \$$_=\"$val\";"
 1022:     }
 1023:   }
 1024:   return $temp;
 1025: }
 1026: 
 1027: sub writeallows {
 1028:     unless ($#extlinks>=0) { return; }
 1029:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
 1030:     if ($ENV{'httpref.'.$thisurl}) {
 1031: 	$thisurl=$ENV{'httpref.'.$thisurl};
 1032:     }
 1033:     my $thisdir=$thisurl;
 1034:     $thisdir=~s/\/[^\/]+$//;
 1035:     my %httpref=();
 1036:     foreach (@extlinks) {
 1037:        $httpref{'httpref.'.
 1038:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
 1039:     }
 1040:     @extlinks=();
 1041:     &Apache::lonnet::appenv(%httpref);
 1042: }
 1043: 
 1044: #
 1045: # Afterburner handles anchors, highlights and links
 1046: #
 1047: sub afterburn {
 1048:     my $result=shift;
 1049:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1050: 					    ['highlight','anchor','link']);
 1051:     if ($ENV{'form.highlight'}) {
 1052:        foreach (split(/\,/,$ENV{'form.highlight'})) {
 1053:            my $anchorname=$_;
 1054: 	   my $matchthis=$anchorname;
 1055:            $matchthis=~s/\_+/\\s\+/g;
 1056:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
 1057:        }
 1058:     }
 1059:     if ($ENV{'form.link'}) {
 1060:        foreach (split(/\,/,$ENV{'form.link'})) {
 1061:            my ($anchorname,$linkurl)=split(/\>/,$_);
 1062: 	   my $matchthis=$anchorname;
 1063:            $matchthis=~s/\_+/\\s\+/g;
 1064:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
 1065:        }
 1066:     }
 1067:     if ($ENV{'form.anchor'}) {
 1068:         my $anchorname=$ENV{'form.anchor'};
 1069: 	my $matchthis=$anchorname;
 1070:         $matchthis=~s/\_+/\\s\+/g;
 1071:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
 1072:         $result.=(<<"ENDSCRIPT");
 1073: <script>
 1074:     document.location.hash='$anchorname';
 1075: </script>
 1076: ENDSCRIPT
 1077:     }
 1078:     return $result;
 1079: }
 1080: 
 1081: sub storefile {
 1082:     my ($file,$contents)=@_;
 1083:     if (my $fh=Apache::File->new('>'.$file)) {
 1084: 	print $fh $contents;
 1085:         $fh->close();
 1086:     } else {
 1087:       &warning("Unable to save file $file");
 1088:     }
 1089: }
 1090: 
 1091: sub createnewhtml {
 1092:   my $filecontents=(<<SIMPLECONTENT);
 1093: <html>
 1094: <head>
 1095: <title>
 1096:                            Title of Document Goes Here
 1097: </title>
 1098: </head>
 1099: <body bgcolor="#FFFFFF">
 1100: 
 1101:                            Body of Document Goes Here
 1102: 
 1103: </body>
 1104: </html>
 1105: SIMPLECONTENT
 1106:   return $filecontents;
 1107: }
 1108: 
 1109: 
 1110: sub inserteditinfo {
 1111:       my ($result,$filecontents)=@_;
 1112:       $filecontents = &HTML::Entities::encode($filecontents);
 1113: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
 1114:       my $buttons=(<<BUTTONS);
 1115: <input type="submit" name="attemptclean" 
 1116:        value="Save and then attempt to clean HTML" />
 1117: <input type="submit" name="savethisfile" value="Save this" />
 1118: <input type="submit" name="viewmode" value="View" />
 1119: BUTTONS
 1120:       my $editfooter=(<<ENDFOOTER);
 1121: <hr />
 1122: <a name="editsection" />
 1123: <form method="post">
 1124: <input type="hidden" name="editmode" value="Edit" />
 1125: $buttons
 1126: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
 1127: $buttons
 1128: <br />
 1129: </form>
 1130: ENDFOOTER
 1131: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
 1132:       $result=~s/(\<\/body\>)/$editfooter/is;
 1133:       return $result;
 1134: }
 1135: 
 1136: sub get_target {
 1137:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
 1138:   if ( $ENV{'request.state'} eq 'published') {
 1139:     if ( defined($ENV{'form.grade_target'})
 1140: 	 && ($viewgrades == 'F' )) {
 1141:       return ($ENV{'form.grade_target'});
 1142:     } elsif (defined($ENV{'form.grade_target'})) {
 1143:       if (($ENV{'form.grade_target'} eq 'web') ||
 1144: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
 1145: 	return $ENV{'form.grade_target'}
 1146:       } else {
 1147: 	return 'web';
 1148:       }
 1149:     } else {
 1150:       return 'web';
 1151:     }
 1152:   } elsif ($ENV{'request.state'} eq 'construct') {
 1153:     if ( defined($ENV{'form.grade_target'})) {
 1154:       return ($ENV{'form.grade_target'});
 1155:     } else {
 1156:       return 'web';
 1157:     }
 1158:   } else {
 1159:     return 'web';
 1160:   }
 1161: }
 1162: 
 1163: sub handler {
 1164:   my $request=shift;
 1165: 
 1166:   my $target=&get_target();
 1167: 
 1168:   $Apache::lonxml::debug=0;
 1169: 
 1170:   if ($ENV{'browser.mathml'}) {
 1171:     $request->content_type('text/xml');
 1172:   } else {
 1173:     $request->content_type('text/html');
 1174:   }
 1175:   &Apache::loncommon::no_cache($request);
 1176:   $request->send_http_header;
 1177: 
 1178:   return OK if $request->header_only;
 1179: 
 1180: 
 1181:   my $file=&Apache::lonnet::filelocation("",$request->uri);
 1182: #
 1183: # Edit action? Save file.
 1184: #
 1185:   unless ($ENV{'request.state'} eq 'published') {
 1186:       if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
 1187: 	  &storefile($file,$ENV{'form.filecont'});
 1188:       }
 1189:   }
 1190:   my %mystyle;
 1191:   my $result = '';
 1192:   my $filecontents=&Apache::lonnet::getfile($file);
 1193:   if ($filecontents == -1) {
 1194:     $result=(<<ENDNOTFOUND);
 1195: <html>
 1196: <head>
 1197: <title>File not found</title>
 1198: </head>
 1199: <body bgcolor="#FFFFFF">
 1200: <b>File not found: $file</b>
 1201: </body>
 1202: </html>
 1203: ENDNOTFOUND
 1204:     $filecontents='';
 1205:     if ($ENV{'request.state'} ne 'published') {
 1206:       $filecontents=&createnewhtml();
 1207:       $ENV{'form.editmode'}='Edit'; #force edit mode
 1208:     }
 1209:   } else {
 1210:     unless ($ENV{'request.state'} eq 'published') {
 1211:       if ($ENV{'form.attemptclean'}) {
 1212: 	$filecontents=&htmlclean($filecontents,1);
 1213:       }
 1214:     }
 1215:     if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
 1216:       $result = &Apache::lonxml::xmlparse($target,$filecontents,'',%mystyle);
 1217:     }
 1218:   }
 1219: 
 1220: #
 1221: # Edit action? Insert editing commands
 1222: #
 1223:   unless ($ENV{'request.state'} eq 'published') {
 1224:     if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
 1225:       $result='<html><body bgcolor="#FFFFFF"></body></html>';
 1226:       $result=&inserteditinfo($result,$filecontents);
 1227:     }
 1228:   }
 1229: 
 1230:   writeallows($request->uri);
 1231: 
 1232:   $request->print($result);
 1233: 
 1234:   return OK;
 1235: }
 1236: 
 1237: sub debug {
 1238:   if ($Apache::lonxml::debug eq 1) {
 1239:     $|=1;
 1240:     print("DEBUG:".join('<br />',@_)."<br />\n");
 1241:   }
 1242: }
 1243: 
 1244: sub error {
 1245:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
 1246:     # If printing in construction space, put the error inside <pre></pre>
 1247:     print "<b>ERROR:</b>".join("\n",@_)."\n";
 1248:   } else {
 1249:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
 1250:     #notify author
 1251:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
 1252:     #notify course
 1253:     if ( $ENV{'request.course.id'} ) {
 1254:       my $users=$ENV{'course.'.$ENV{'request.course.id'}.'.comment.email'};
 1255:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
 1256:       foreach my $user (split /\,/, $users) {
 1257: 	($user,my $domain) = split /:/, $user;
 1258: 	&Apache::lonmsg::user_normal_msg($user,$domain,
 1259:         "Error [$declutter]",join('<br />',@_));
 1260:       }
 1261:     }
 1262: 
 1263:     #FIXME probably shouldn't have me get everything forever.
 1264:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
 1265:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
 1266:   }
 1267: }
 1268: 
 1269: sub warning {
 1270:   if ($ENV{'request.state'} eq 'construct') {
 1271:     print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
 1272:   }
 1273: }
 1274: 
 1275: sub get_param {
 1276:   my ($param,$parstack,$safeeval,$context) = @_;
 1277:   if ( ! $context ) { $context = -1; }
 1278:   my $args ='';
 1279:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1280:   if ( ! $args ) { return undef; }
 1281:   if ( $args =~ /my \$$param=\"/ ) {
 1282:     return &Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1283:   } else {
 1284:     return undef;
 1285:   }
 1286: }
 1287: 
 1288: sub get_param_var {
 1289:   my ($param,$parstack,$safeeval,$context) = @_;
 1290:   if ( ! $context ) { $context = -1; }
 1291:   my $args ='';
 1292:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
 1293:   if ( $args !~ /my \$$param=\"/ ) { return undef; }
 1294:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
 1295:   if ($value =~ /^[\$\@\%]/) {
 1296:     return &Apache::run::run("return $value",$safeeval,1);
 1297:   } else {
 1298:     return $value;
 1299:   }
 1300: }
 1301: 
 1302: sub register_insert {
 1303:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
 1304:   my $i;
 1305:   my $tagnum=0;
 1306:   my @order;
 1307:   for ($i=0;$i < $#data; $i++) {
 1308:     my $line = $data[$i];
 1309:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
 1310:     if ( $line =~ /TABLE/ ) { last; }
 1311:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
 1312:     if ($tag) {
 1313:       $insertlist{"$tagnum.tag"} = $tag;
 1314:       $insertlist{"$tagnum.description"} = $descrip;
 1315:       $insertlist{"$tagnum.color"} = $color;
 1316:       $insertlist{"$tagnum.function"} = $function;
 1317:       if (!defined($show)) { $show='yes'; }
 1318:       $insertlist{"$tagnum.show"}= $show;
 1319:       $insertlist{"$tag.num"}=$tagnum;
 1320:       $tagnum++;
 1321:     }
 1322:   }
 1323:   $i++; #skipping TABLE line
 1324:   $tagnum = 0;
 1325:   for (;$i < $#data;$i++) {
 1326:     my $line = $data[$i];
 1327:     my ($mnemonic,@which) = split(/ +/,$line);
 1328:     my $tag = $insertlist{"$tagnum.tag"};
 1329:     for (my $j=0;$j <=$#which;$j++) {
 1330:       if ( $which[$j] eq 'Y' ) {
 1331: 	if ($insertlist{"$j.show"} ne 'no') {
 1332: 	  push(@{ $insertlist{"$tag.which"} },$j);
 1333: 	}
 1334:       }
 1335:     }
 1336:     $tagnum++;
 1337:   }
 1338: }
 1339: 
 1340: sub description {
 1341:   my ($token)=@_;
 1342:   my $tagnum;
 1343:   my $tag=$token->[1];
 1344:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
 1345:     my $testtag=$namespace.'::'.$tag;
 1346:     $tagnum=$insertlist{"$testtag.num"};
 1347:     if (defined($tagnum)) { last; }
 1348:   }
 1349:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
 1350:   return $insertlist{$tagnum.'.description'};
 1351: }
 1352: 
 1353: # ----------------------------------------------------------------- whichuser
 1354: # returns a list of $symb, $courseid, $domain, $name that is correct for
 1355: # calls to lonnet functions for this setup.
 1356: # - looks for form.grade_ parameters
 1357: sub whichuser {
 1358:   my ($symb,$courseid,$domain,$name);
 1359:   if (defined($ENV{'form.grade_symb'})) {
 1360:     my $tmp_courseid=$ENV{'form.grade_courseid'};
 1361:     my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
 1362:     if ($allowed) {
 1363:       $symb=$ENV{'form.grade_symb'};
 1364:       $courseid=$ENV{'form.grade_courseid'};
 1365:       $domain=$ENV{'form.grade_domain'};
 1366:       $name=$ENV{'form.grade_username'};
 1367:     }
 1368:   } else {
 1369:     $symb=&Apache::lonnet::symbread();
 1370:     $courseid=$ENV{'request.course.id'};
 1371:     $domain=$ENV{'user.domain'};
 1372:     $name=$ENV{'user.name'};
 1373:   }
 1374:   return ($symb,$courseid,$domain,$name);
 1375: }
 1376: 
 1377: 1;
 1378: __END__
 1379: 
 1380: 

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