Annotation of loncom/xml/lonxml.pm, revision 1.160

1.2       sakharuk    1: # The LearningOnline Network with CAPA
1.3       sakharuk    2: # XML Parser Module 
1.2       sakharuk    3: #
1.160   ! www         4: # $Id: lonxml.pm,v 1.159 2002/03/21 20:51:10 www Exp $
1.139     www         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: #
1.3       sakharuk   39: # last modified 06/26/00 by Alexander Sakharuk
1.33      www        40: # 11/6 Gerd Kortemeyer
1.45      www        41: # 6/1/1 Gerd Kortemeyer
1.56      albertel   42: # 2/21,3/13 Guy
1.68      www        43: # 3/29,5/4 Gerd Kortemeyer
1.73      harris41   44: # 5/10 Scott Harrison
1.78      www        45: # 5/26 Gerd Kortemeyer
1.80      harris41   46: # 5/27 H. K. Ng
1.89      www        47: # 6/2,6/3,6/8,6/9 Gerd Kortemeyer
1.93      ng         48: # 6/12,6/13 H. K. Ng
1.95      www        49: # 6/16 Gerd Kortemeyer
1.104     ng         50: # 7/27 H. K. Ng
1.127     www        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
1.130     www        52: # Guy Albertelli
                     53: # 9/26 Gerd Kortemeyer
1.143     www        54: # Dec Guy Albertelli
                     55: # YEAR=2002
                     56: # 1/1 Gerd Kortemeyer
1.145     www        57: # 1/2 Matthew Hall
                     58: # 1/3 Gerd Kortemeyer
1.143     www        59: #
1.2       sakharuk   60: 
1.4       albertel   61: package Apache::lonxml; 
1.33      www        62: use vars 
1.76      albertel   63: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace);
1.1       sakharuk   64: use strict;
                     65: use HTML::TokeParser;
1.106     www        66: use HTML::TreeBuilder;
1.157     albertel   67: use HTML::Entities;
1.3       sakharuk   68: use Safe;
1.40      albertel   69: use Safe::Hole;
1.81      ng         70: use Math::Cephes qw(:trigs :hypers :bessels erf erfc);
1.91      ng         71: use Math::Random qw(:all);
1.13      albertel   72: use Opcode;
1.72      albertel   73: 
                     74: sub register {
1.141     albertel   75:   my ($space,@taglist) = @_;
                     76:   foreach my $temptag (@taglist) {
                     77:     push(@{ $Apache::lonxml::alltags{$temptag} },$space);
1.72      albertel   78:   }
                     79: }
                     80: 
1.141     albertel   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:   }
1.142     albertel   89:   #&printalltags();
1.141     albertel   90: }
                     91: 
1.46      www        92: use Apache::Constants qw(:common);
1.71      www        93: use Apache::lontexconvert;
1.72      albertel   94: use Apache::style;
                     95: use Apache::run;
                     96: use Apache::londefdef;
                     97: use Apache::scripttag;
                     98: use Apache::edit;
1.79      www        99: use Apache::lonnet;
                    100: use Apache::File;
1.136     albertel  101: use Apache::loncommon;
1.79      www       102: 
1.72      albertel  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;
1.7       albertel  125: 
1.74      albertel  126: # data structure for eidt mode, determines what tags can go into what other tags
                    127: %insertlist=();
1.68      www       128: 
1.99      albertel  129: # stores the list of active tag namespaces
1.76      albertel  130: @namespace=();
                    131: 
1.99      albertel  132: # has the dynamic menu been updated to know about this resource
                    133: $Apache::lonxml::registered=0;
                    134: 
1.68      www       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 {
1.103     www       151:     my $discussion='';
                    152:     if ($ENV{'request.course.id'}) {
1.109     www       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);
1.103     www       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++) {
1.110     www       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:                   }
1.109     www       177:                   my $sender='Anonymous';
                    178:                   if ((!$contrib{$idx.':anonymous'}) || ($seeid)) {
                    179:                       $sender=$contrib{$idx.':sendername'}.' at '.
                    180: 		      $contrib{$idx.':senderdomain'};
                    181:                       if ($contrib{$idx.':anonymous'}) {
                    182: 			  $sender.=' (anonymous)';
1.110     www       183:                       }
                    184:                       if ($seeid) {
                    185: 			  if ($hidden) {
                    186:                              $sender.=' <a href="/adm/feedback?unhide='.
                    187: 				 $symb.':::'.$idx.'">Make Visible</a>';
                    188:                           } else {
                    189:                              $sender.=' <a href="/adm/feedback?hide='.
                    190: 				 $symb.':::'.$idx.'">Hide</a>';
                    191: 			  }
1.109     www       192:                       }                   
                    193:                   }
                    194: 		  $discussion.='<p><b>'.$sender.'</b> ('.
1.103     www       195:                       localtime($contrib{$idx.':timestamp'}).
                    196:                       '):<blockquote>'.$message.
1.110     www       197:                       '</blockquote></p>';
                    198: 	        }
                    199:                } 
1.103     www       200:               }
                    201:               $discussion.='</address>';
                    202:           }
                    203:        }
                    204:     }
                    205:     return $discussion.'</html>';
1.119     www       206: }
                    207: 
                    208: sub tokeninputfield {
1.120     www       209:     my $defhost=$Apache::lonnet::perlvar{'lonHostID'};
                    210:     $defhost=~tr/a-z/A-Z/;
1.119     www       211:     return (<<ENDINPUTFIELD)
1.120     www       212: <script>
                    213:     function updatetoken() {
                    214: 	var comp=new Array;
                    215:         var barcode=unescape(document.tokeninput.barcode.value);
                    216:         comp=barcode.split('*');
                    217:         if (typeof(comp[0])!="undefined") {
                    218: 	    document.tokeninput.codeone.value=comp[0];
                    219: 	}
                    220:         if (typeof(comp[1])!="undefined") {
                    221: 	    document.tokeninput.codetwo.value=comp[1];
                    222: 	}
                    223:         if (typeof(comp[2])!="undefined") {
                    224:             comp[2]=comp[2].toUpperCase();
                    225: 	    document.tokeninput.codethree.value=comp[2];
                    226: 	}
                    227:         document.tokeninput.barcode.value='';
                    228:     }  
                    229: </script>
                    230: <form method="post" name="tokeninput">
1.119     www       231: <table border="2" bgcolor="#FFFFBB">
                    232: <tr><th>DocID Checkin</th></tr>
                    233: <tr><td>
                    234: <table>
                    235: <tr>
                    236: <td>Scan in Barcode</td>
1.120     www       237: <td><input type="text" size="22" name="barcode" 
                    238: onChange="updatetoken()"/></td>
1.119     www       239: </tr>
                    240: <tr><td><i>or</i> Type in DocID</td>
                    241: <td>
                    242: <input type="text" size="5" name="codeone" />
1.120     www       243: <b><font size="+2">*</font></b>
1.119     www       244: <input type="text" size="5" name="codetwo" />
1.120     www       245: <b><font size="+2">*</font></b>
                    246: <input type="text" size="10" name="codethree" value="$defhost" 
                    247: onChange="this.value=this.value.toUpperCase()" />
1.119     www       248: </td></tr>
                    249: </table>
                    250: </td></tr>
                    251: <tr><td><input type="submit" value="Check in DocID" /></td></tr>
                    252: </table>
                    253: </form>
                    254: ENDINPUTFIELD
1.112     www       255: }
                    256: 
1.116     www       257: sub maketoken {
1.118     www       258:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
1.112     www       259:     unless ($symb) {
                    260: 	$symb=&Apache::lonnet::symbread();
                    261:     }
                    262:     unless ($tuname) {
                    263: 	$tuname=$ENV{'user.name'};
                    264:         $tudom=$ENV{'user.domain'};
                    265:         $tcrsid=$ENV{'request.course.id'};
                    266:     }
1.116     www       267: 
1.118     www       268:     return &Apache::lonnet::checkout($symb,$tuname,$tudom,$tcrsid);
                    269: }
                    270: 
                    271: sub printtokenheader {
1.133     albertel  272:     my ($target,$token,$tsymb,$tcrsid,$tudom,$tuname)=@_;
1.116     www       273:     unless ($token) { return ''; }
1.118     www       274: 
1.133     albertel  275:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                    276:     unless ($tsymb) {
                    277: 	$tsymb=$symb;
1.118     www       278:     }
                    279:     unless ($tuname) {
1.133     albertel  280: 	$tuname=$name;
                    281:         $tudom=$domain;
                    282:         $tcrsid=$courseid;
1.118     www       283:     }
1.114     www       284: 
                    285:     my %reply=&Apache::lonnet::get('environment',
                    286:               ['firstname','middlename','lastname','generation'],
                    287:               $tudom,$tuname);
                    288:     my $plainname=$reply{'firstname'}.' '. 
                    289:                   $reply{'middlename'}.' '.
                    290:                   $reply{'lastname'}.' '.
                    291: 		  $reply{'generation'};
                    292: 
1.112     www       293:     if ($target eq 'web') {
1.145     www       294:         my %idhash=&Apache::lonnet::idrget($tudom,($tuname));
1.115     www       295: 	return 
                    296:  '<img align="right" src="/cgi-bin/barcode.gif?encode='.$token.'" />'.
                    297:                'Checked out for '.$plainname.
1.114     www       298:                '<br />User: '.$tuname.' at '.$tudom.
1.145     www       299: 	       '<br />ID: '.$idhash{$tuname}.
1.117     www       300: 	       '<br />CourseID: '.$tcrsid.
1.145     www       301: 	       '<br />Course: '.$ENV{'course.'.$tcrsid.'.description'}.
1.114     www       302:                '<br />DocID: '.$token.
1.116     www       303:                '<br />Time: '.localtime().'<hr />';
1.112     www       304:     } else {
1.121     albertel  305:         return $token;
1.112     www       306:     }
1.68      www       307: }
                    308: 
1.70      www       309: sub fontsettings() {
                    310:     my $headerstring='';
                    311:     if (($ENV{'browser.os'} eq 'mac') && (!$ENV{'browser.mathml'})) { 
                    312:          $headerstring.=
                    313:              '<meta Content-Type="text/html; charset=x-mac-roman">';
                    314:     }
                    315:     return $headerstring;
                    316: }
                    317: 
1.68      www       318: sub registerurl {
1.100     www       319:     my $forcereg=shift;
1.155     matthew   320:     my $target = shift;
                    321:     my $result = '';
1.160   ! www       322:     if (($ENV{'request.publicaccess'}) || 
        !           323:        ($ENV{'REQUEST_URI'} eq '/res/adm/pages/menu.html')) {
1.130     www       324: 	return 
                    325:          '<script>function LONCAPAreg(){} function LONCAPAstale(){}</script>';
                    326:     }
1.128     albertel  327:     if ($Apache::lonxml::registered && !$forcereg) { return ''; }
1.105     albertel  328:     $Apache::lonxml::registered=1;
1.159     www       329:     my $nothing='';
                    330:     if ($ENV{'browser.type'} eq 'explorer') { $nothing='javascript:void(0);'; }
1.100     www       331:     if (($ENV{'REQUEST_URI'}!~/^\/(res\/)*adm\//) || ($forcereg)) {
1.87      www       332:         my $hwkadd='';
                    333:         if ($ENV{'REQUEST_URI'}=~/\.(problem|exam|quiz|assess|survey|form)$/) {
                    334: 	    if (&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) {
                    335: 		$hwkadd.=(<<ENDSUBM);
                    336:                      menu.switchbutton
                    337:            (7,1,'subm.gif','view sub','missions',
1.88      www       338:                 'gocmd("/adm/grades","submission")');
1.87      www       339: ENDSUBM
                    340:             }
                    341: 	    if (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) {
                    342: 		$hwkadd.=(<<ENDGRDS);
                    343:                      menu.switchbutton
                    344:            (7,2,'pgrd.gif','problem','grades',
1.88      www       345:                 'gocmd("/adm/grades","viewgrades")');
1.87      www       346: ENDGRDS
                    347:             }
                    348: 	    if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
                    349: 		$hwkadd.=(<<ENDPARM);
                    350:                      menu.switchbutton
                    351:            (7,3,'pparm.gif','problem','parms',
1.88      www       352:                 'gocmd("/adm/parmset","set")');
1.87      www       353: ENDPARM
                    354:             }
                    355: 	}
1.155     matthew   356: 	$result = (<<ENDREGTHIS);
1.87      www       357:      
1.68      www       358: <script language="JavaScript">
1.71      www       359: // BEGIN LON-CAPA Internal
1.86      www       360: 
1.69      www       361:     function LONCAPAreg() {
1.159     www       362: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
1.86      www       363:           menu.clearTimeout(menu.menucltim);
1.69      www       364: 	  menu.currentURL=window.location.pathname;
                    365:           menu.currentStale=0;
1.85      www       366:           menu.clearbut(3,1);
                    367:           menu.switchbutton
1.108     www       368:        (6,3,'catalog.gif','catalog','info','catalog_info()');
                    369:           menu.switchbutton
1.85      www       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)');
1.94      www       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
1.95      www       384:                                (9,3,'anot.gif','anno-','tations','annotate()');
1.87      www       385:           $hwkadd
1.69      www       386:     }
1.86      www       387: 
1.69      www       388:     function LONCAPAstale() {
1.159     www       389: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
1.86      www       390:           menu.currentStale=1;
1.127     www       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);
1.86      www       396:           menu.menucltim=menu.setTimeout(
1.94      www       397:  'clearbut(2,1);clearbut(2,3);clearbut(8,1);clearbut(8,2);clearbut(8,3);'+
1.108     www       398:  'clearbut(9,1);clearbut(9,2);clearbut(9,3);clearbut(6,3)',
1.86      www       399: 			  2000);
                    400: 
1.87      www       401:       }
1.86      www       402: 
                    403: // END LON-CAPA Internal
                    404: </script>
                    405: ENDREGTHIS
                    406: 
                    407:     } else {
1.155     matthew   408:         $result = (<<ENDDONOTREGTHIS);
1.86      www       409: 
                    410: <script language="JavaScript">
                    411: // BEGIN LON-CAPA Internal
                    412: 
                    413:     function LONCAPAreg() {
1.159     www       414: 	  menu=window.open("$nothing","LONCAPAmenu","",false);
1.69      www       415:           menu.currentStale=1;
1.85      www       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);
1.86      www       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() {
1.68      www       430:     }
1.86      www       431: 
1.71      www       432: // END LON-CAPA Internal
1.68      www       433: </script>
1.86      www       434: ENDDONOTREGTHIS
                    435:     }
1.155     matthew   436:     if ($target eq 'edit') {
1.156     matthew   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.
1.155     matthew   443:         $result .=<<"ENDBROWSERSCRIPT";
                    444: <script>
1.156     matthew   445:     var editbrowser;
1.155     matthew   446:     function openbrowser(formname,elementname) {
                    447:         var url = '/res/?';
1.156     matthew   448:         if (editbrowser == null) {
1.155     matthew   449:             url += 'launch=1&';
                    450:         }
                    451:         url += 'catalogmode=interactive&';
                    452:         url += 'mode=edit&';
                    453:         url += 'form=' + formname + '&';
                    454:         url += 'element=' + elementname + '';
                    455:         var title = 'Browser';
                    456:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    457:         options += ',width=700,height=600';
1.156     matthew   458:         editbrowser = open(url,title,options,'1');
                    459:         editbrowser.focus();
                    460:     }
                    461:     var editsearcher;
                    462:     function opensearcher(formname,elementname) {
                    463:         var url = '/adm/searchcat?';
                    464:         if (editsearcher == null) {
                    465:             url += 'launch=1&';
                    466:         }
                    467:         url += 'catalogmode=interactive&';
                    468:         url += 'mode=edit&';
                    469:         url += 'form=' + formname + '&';
                    470:         url += 'element=' + elementname + '';
                    471:         var title = 'Search';
                    472:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    473:         options += ',width=700,height=600';
                    474:         editsearcher = open(url,title,options,'1');
                    475:         editsearcher.focus();
1.155     matthew   476:     }
                    477: </script>
                    478: ENDBROWSERSCRIPT
                    479:     }
                    480:     return $result;
1.69      www       481: }
                    482: 
                    483: sub loadevents() {
                    484:     return 'LONCAPAreg();';
                    485: }
                    486: 
                    487: sub unloadevents() {
                    488:     return 'LONCAPAstale();';
1.68      www       489: }
                    490: 
1.48      albertel  491: sub printalltags {
                    492:   my $temp;
                    493:   foreach $temp (sort keys %Apache::lonxml::alltags) {
1.141     albertel  494:     &Apache::lonxml::debug("$temp -- ".
                    495: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
1.48      albertel  496:   }
                    497: }
1.31      sakharuk  498: 
1.3       sakharuk  499: sub xmlparse {
1.18      albertel  500:  my ($target,$content_file_string,$safeinit,%style_for_target) = @_;
1.96      albertel  501: 
                    502:  &setup_globals($target);
1.48      albertel  503:  #&printalltags();
1.16      albertel  504:  my @pars = ();
1.23      albertel  505:  my $pwd=$ENV{'request.filename'};
                    506:  $pwd =~ s:/[^/]*$::;
                    507:  &newparser(\@pars,\$content_file_string,$pwd);
1.24      sakharuk  508: 
1.3       sakharuk  509:  my $safeeval = new Safe;
1.40      albertel  510:  my $safehole = new Safe::Hole;
1.82      ng        511:  &init_safespace($target,$safeeval,$safehole,$safeinit);
1.3       sakharuk  512: #-------------------- Redefinition of the target in the case of compound target
                    513: 
                    514:  ($target, my @tenta) = split('&&',$target);
                    515: 
1.150     albertel  516:  my @stack = ();
1.3       sakharuk  517:  my @parstack = ();
1.17      albertel  518:  &initdepth;
1.67      www       519: 
1.101     albertel  520:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
                    521: 				   $safeeval,\%style_for_target);
1.125     www       522:  if ($ENV{'request.uri'}) {
                    523:     &writeallows($ENV{'request.uri'});
                    524:  }
1.3       sakharuk  525:  return $finaloutput;
1.106     www       526: }
                    527: 
                    528: sub htmlclean {
1.107     www       529:     my ($raw,$full)=@_;
1.106     www       530: 
                    531:     my $tree = HTML::TreeBuilder->new;
                    532:     $tree->ignore_unknown(0);
1.140     albertel  533: 
1.106     www       534:     $tree->parse($raw);
                    535: 
1.107     www       536:     my $output= $tree->as_HTML(undef,' ');
1.140     albertel  537: 
1.111     www       538:     $output=~s/\<(br|hr|img|meta|allow)([^\>\/]*)\>/\<$1$2 \/\>/gis;
                    539:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
1.107     www       540:     unless ($full) {
                    541:        $output=~s/\<[\/]*(body|head|html)\>//gis;
                    542:     }
1.106     www       543: 
                    544:     $tree = $tree->delete;
                    545: 
                    546:     return $output;
1.15      albertel  547: }
                    548: 
1.101     albertel  549: sub inner_xmlparse {
                    550:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
                    551:   my $finaloutput = '';
                    552:   my $result;
                    553:   my $token;
                    554:   while ( $#$pars > -1 ) {
                    555:     while ($token = $$pars['-1']->get_token) {
                    556:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
                    557: 	if ($metamode<1) {
                    558: 	  $result=$token->[1];
                    559: 	}
                    560:       } elsif ($token->[0] eq 'PI') {
                    561: 	if ($metamode<1) {
                    562: 	  $result=$token->[2];
                    563: 	}
                    564:       } elsif ($token->[0] eq 'S') {
1.140     albertel  565: 	# add tag to stack
1.101     albertel  566: 	push (@$stack,$token->[1]);
                    567: 	# add parameters list to another stack
                    568: 	push (@$parstack,&parstring($token));
1.140     albertel  569: 	&increasedepth($token);
1.101     albertel  570: 	if (exists $$style_for_target{$token->[1]}) {
                    571: 	  if ($Apache::lonxml::redirection) {
1.140     albertel  572: 	    $Apache::lonxml::outputstack['-1'] .=
1.101     albertel  573: 	      &recurse($$style_for_target{$token->[1]},$target,$safeeval,
                    574: 		       $style_for_target,@$parstack);
                    575: 	  } else {
                    576: 	    $finaloutput .= &recurse($$style_for_target{$token->[1]},$target,
                    577: 				     $safeeval,$style_for_target,@$parstack);
                    578: 	  }
                    579: 	} else {
                    580: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
                    581: 			     $parstack, $pars, $safeeval, $style_for_target);
1.140     albertel  582: 	}
1.101     albertel  583:       } elsif ($token->[0] eq 'E') {
                    584: 	#clear out any tags that didn't end
                    585: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
1.150     albertel  586: 	  my $lasttag=$$stack[-1];
                    587: 	  if ($token->[1] =~ /^$lasttag$/i) {
                    588: 	    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; as end tag to &lt;'.$$stack[-1].'&gt;');
                    589: 	    last;
                    590: 	  } else {
1.152     albertel  591: 	    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; when looking for &lt;/'.$$stack[-1].'&gt; in file');
1.150     albertel  592: 	    &end_tag($stack,$parstack,$token);
                    593: 	  }
1.101     albertel  594: 	}
1.140     albertel  595: 
                    596: 	if (exists($$style_for_target{'/'."$token->[1]"})) {
1.101     albertel  597: 	  if ($Apache::lonxml::redirection) {
                    598: 	    $Apache::lonxml::outputstack['-1'] .=  
                    599: 	      &recurse($$style_for_target{'/'."$token->[1]"},
                    600: 		       $target,$safeeval,$style_for_target,@$parstack);
                    601: 	  } else {
                    602: 	    $finaloutput .= &recurse($$style_for_target{'/'."$token->[1]"},
                    603: 				     $target,$safeeval,$style_for_target,
                    604: 				     @$parstack);
                    605: 	  }
                    606: 	} else {
                    607: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
                    608: 			     $parstack, $pars,$safeeval, $style_for_target);
                    609: 	}
                    610:       } else {
                    611: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
                    612:       }
                    613:       #evaluate variable refs in result
                    614:       if ($result ne "") {
                    615: 	if ( $#$parstack > -1 ) {
                    616: 	  if ($Apache::lonxml::redirection) {
                    617: 	    $Apache::lonxml::outputstack['-1'] .= 
                    618: 	      &Apache::run::evaluate($result,$safeeval,$$parstack['-1']);
                    619: 	  } else {
                    620: 	    $finaloutput .= &Apache::run::evaluate($result,$safeeval,
                    621: 						   $$parstack['-1']);
                    622: 	  }
                    623: 	} else {
                    624: 	  $finaloutput .= &Apache::run::evaluate($result,$safeeval,'');
                    625: 	}
                    626: 	$result = '';
                    627:       } 
                    628:       if ($token->[0] eq 'E') { 
                    629: 	&end_tag($stack,$parstack,$token);
                    630:       }
                    631:     }
                    632:     pop @$pars;
                    633:     pop @Apache::lonxml::pwd;
                    634:   }
                    635: 
                    636:   # if ($target eq 'meta') {
                    637:   #   $finaloutput.=&endredirection;
                    638:   # }
                    639: 
                    640:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
                    641:     $finaloutput=&afterburn($finaloutput);
                    642:   }
                    643:   return $finaloutput;
                    644: }
1.67      www       645: 
1.15      albertel  646: sub recurse {
                    647:   my @innerstack = (); 
                    648:   my @innerparstack = ();
                    649:   my ($newarg,$target,$safeeval,$style_for_target,@parstack) = @_;
1.16      albertel  650:   my @pat = ();
1.23      albertel  651:   &newparser(\@pat,\$newarg);
1.15      albertel  652:   my $tokenpat;
                    653:   my $partstring = '';
                    654:   my $output='';
1.16      albertel  655:   my $decls='';
1.140     albertel  656:   &Apache::lonxml::debug("Recursing");
1.16      albertel  657:   while ( $#pat > -1 ) {
                    658:     while  ($tokenpat = $pat[$#pat]->get_token) {
1.57      albertel  659:       if (($tokenpat->[0] eq 'T') || ($tokenpat->[0] eq 'C') || ($tokenpat->[0] eq 'D') ) {
1.61      albertel  660: 	if ($metamode<1) { $partstring=$tokenpat->[1]; }
1.57      albertel  661:       } elsif ($tokenpat->[0] eq 'PI') {
1.61      albertel  662: 	if ($metamode<1) { $partstring=$tokenpat->[2]; }
1.16      albertel  663:       } elsif ($tokenpat->[0] eq 'S') {
                    664: 	push (@innerstack,$tokenpat->[1]);
                    665: 	push (@innerparstack,&parstring($tokenpat));
1.19      albertel  666: 	&increasedepth($tokenpat);
1.84      albertel  667: 	$partstring = &callsub("start_$tokenpat->[1]", $target, $tokenpat,
                    668: 			       \@innerstack, \@innerparstack, \@pat,
                    669: 			       $safeeval, $style_for_target);
1.16      albertel  670:       } elsif ($tokenpat->[0] eq 'E') {
                    671: 	#clear out any tags that didn't end
1.150     albertel  672: 	while ($tokenpat->[1] ne $innerstack[$#innerstack]
1.43      albertel  673: 	       && ($#innerstack > -1)) {
1.150     albertel  674: 	  my $lasttag=$innerstack[-1];
                    675: 	  if ($tokenpat->[1] =~ /^$lasttag$/i) {
                    676: 	    &Apache::lonxml::warning('Using tag &lt;/'.$tokenpat->[1].'&gt; as end tag to &lt;'.$innerstack[-1].'&gt;');
                    677: 	    last;
                    678: 	  } else {
1.152     albertel  679: 	    &Apache::lonxml::warning('Found tag &lt;/'.$tokenpat->[1].'&gt; when looking for &lt;/'.$innerstack[-1].'&gt; in file');
1.150     albertel  680: 	    &end_tag(\@innerstack,\@innerparstack,$tokenpat);
                    681: 	  }
1.43      albertel  682: 	}
1.84      albertel  683: 	$partstring = &callsub("end_$tokenpat->[1]", $target, $tokenpat,
                    684: 			       \@innerstack, \@innerparstack, \@pat,
                    685: 			       $safeeval, $style_for_target);
1.57      albertel  686:       } else {
                    687: 	&Apache::lonxml::error("Unknown token event :$tokenpat->[0]:$tokenpat->[1]:");
1.16      albertel  688:       }
                    689:       #pass both the variable to the style tag, and the tag we 
                    690:       #are processing inside the <definedtag>
                    691:       if ( $partstring ne "" ) {
                    692: 	if ( $#parstack > -1 ) { 
                    693: 	  if ( $#innerparstack > -1 ) { 
                    694: 	    $decls= $parstack[$#parstack].$innerparstack[$#innerparstack];
                    695: 	  } else {
                    696: 	    $decls= $parstack[$#parstack];
                    697: 	  }
                    698: 	} else {
                    699: 	  if ( $#innerparstack > -1 ) { 
                    700: 	    $decls=$innerparstack[$#innerparstack];
                    701: 	  } else {
                    702: 	    $decls='';
                    703: 	  }
                    704: 	}
                    705: 	$output .= &Apache::run::evaluate($partstring,$safeeval,$decls);
                    706: 	$partstring = '';
                    707:       }
1.17      albertel  708:       if ($tokenpat->[0] eq 'E') { pop @innerstack;pop @innerparstack;
1.19      albertel  709: 				 &decreasedepth($tokenpat);}
1.15      albertel  710:     }
1.16      albertel  711:     pop @pat;
1.23      albertel  712:     pop @Apache::lonxml::pwd;
1.15      albertel  713:   }
1.140     albertel  714:   &Apache::lonxml::debug("Exiting Recursing");
1.15      albertel  715:   return $output;
1.7       albertel  716: }
                    717: 
                    718: sub callsub {
1.84      albertel  719:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.7       albertel  720:   my $currentstring='';
1.72      albertel  721:   my $nodefault;
1.7       albertel  722:   {
1.59      albertel  723:     my $sub1;
1.7       albertel  724:     no strict 'refs';
1.68      www       725:     my $tag=$token->[1];
1.141     albertel  726:     my $space=$Apache::lonxml::alltags{$tag}[-1];
1.68      www       727:     if (!$space) {
1.141     albertel  728:      	$tag=~tr/A-Z/a-z/;
1.68      www       729: 	$sub=~tr/A-Z/a-z/;
1.141     albertel  730: 	$space=$Apache::lonxml::alltags{$tag}[-1]
1.68      www       731:     }
1.97      albertel  732: 
                    733:     my $deleted=0;
                    734:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
                    735:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
                    736:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
                    737: 					     $parstack,$parser,$safeeval,
                    738: 					     $style);
                    739:     }
                    740:     if (!$deleted) {
                    741:       if ($space) {
1.152     albertel  742: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
1.97      albertel  743: 	$sub1="$space\:\:$sub";
                    744: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
                    745: 					     $parstack,$parser,$safeeval,
                    746: 					     $style);
                    747:       } else {
1.152     albertel  748: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
1.97      albertel  749: 	if ($metamode <1) {
                    750: 	  if (defined($token->[4]) && ($metamode < 1)) {
                    751: 	    $currentstring = $token->[4];
                    752: 	  } else {
                    753: 	    $currentstring = $token->[2];
                    754: 	  }
1.62      sakharuk  755: 	}
1.7       albertel  756:       }
1.97      albertel  757:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
                    758:       if ($currentstring eq '' && $nodefault eq '') {
                    759: 	if ($target eq 'edit') {
                    760: 	  &Apache::lonxml::debug("doing default edit for $token->[1]");
                    761: 	  if ($token->[0] eq 'S') {
                    762: 	    $currentstring = &Apache::edit::tag_start($target,$token);
                    763: 	  } elsif ($token->[0] eq 'E') {
                    764: 	    $currentstring = &Apache::edit::tag_end($target,$token);
                    765: 	  }
                    766: 	} elsif ($target eq 'modified') {
                    767: 	  if ($token->[0] eq 'S') {
                    768: 	    $currentstring = $token->[4];
                    769: 	    $currentstring.=&Apache::edit::handle_insert();
                    770: 	  } else {
                    771: 	    $currentstring = $token->[2];
                    772: 	  }
1.72      albertel  773: 	}
                    774:       }
1.7       albertel  775:     }
                    776:     use strict 'refs';
                    777:   }
                    778:   return $currentstring;
1.82      ng        779: }
                    780: 
1.96      albertel  781: sub setup_globals {
                    782:   my ($target)=@_;
1.99      albertel  783:   $Apache::lonxml::registered = 0;
1.101     albertel  784:   @Apache::lonxml::pwd=();
1.124     albertel  785:   @Apache::lonxml::extlinks=();
1.96      albertel  786:   if ($target eq 'meta') {
                    787:     $Apache::lonxml::redirection = 0;
                    788:     $Apache::lonxml::metamode = 1;
                    789:     $Apache::lonxml::evaluate = 1;
                    790:     $Apache::lonxml::import = 0;
1.129     albertel  791:   } elsif ($target eq 'answer') {
                    792:     $Apache::lonxml::redirection = 0;
                    793:     $Apache::lonxml::metamode = 1;
                    794:     $Apache::lonxml::evaluate = 1;
                    795:     $Apache::lonxml::import = 1;
1.96      albertel  796:   } elsif ($target eq 'grade') {
                    797:     &startredirection;
                    798:     $Apache::lonxml::metamode = 0;
                    799:     $Apache::lonxml::evaluate = 1;
                    800:     $Apache::lonxml::import = 1;
                    801:   } elsif ($target eq 'modified') {
                    802:     $Apache::lonxml::redirection = 0;
                    803:     $Apache::lonxml::metamode = 0;
                    804:     $Apache::lonxml::evaluate = 0;
                    805:     $Apache::lonxml::import = 0;
                    806:   } elsif ($target eq 'edit') {
                    807:     $Apache::lonxml::redirection = 0;
                    808:     $Apache::lonxml::metamode = 0;
                    809:     $Apache::lonxml::evaluate = 0;
                    810:     $Apache::lonxml::import = 0;
                    811:   } else {
                    812:     $Apache::lonxml::redirection = 0;
                    813:     $Apache::lonxml::metamode = 0;
                    814:     $Apache::lonxml::evaluate = 1;
                    815:     $Apache::lonxml::import = 1;
                    816:   }
                    817: }
                    818: 
1.82      ng        819: sub init_safespace {
                    820:   my ($target,$safeeval,$safehole,$safeinit) = @_;
                    821:   $safeeval->permit("entereval");
                    822:   $safeeval->permit(":base_math");
                    823:   $safeeval->permit("sort");
                    824:   $safeeval->deny(":base_io");
1.102     albertel  825:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
1.82      ng        826:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
                    827:   
                    828:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
                    829:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
                    830:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
                    831:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
                    832:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
                    833:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
                    834:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
                    835:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
                    836:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
                    837:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
                    838:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
                    839:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
                    840:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
                    841:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
                    842:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
                    843:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
                    844:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
                    845:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
                    846:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
1.91      ng        847:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
                    848:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
                    849:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
                    850:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
                    851:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
                    852:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
                    853:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
                    854:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
                    855:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
                    856:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
                    857:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
1.93      ng        858:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
1.91      ng        859:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
                    860:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
                    861:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
                    862:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
                    863:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
                    864:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
                    865:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
                    866:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
                    867:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
                    868: 
1.82      ng        869: #need to inspect this class of ops
                    870: # $safeeval->deny(":base_orig");
1.91      ng        871:   $safeinit .= ';$external::target="'.$target.'";';
1.121     albertel  872:   my $rndseed;
1.123     albertel  873:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                    874:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
1.121     albertel  875:   $safeinit .= ';$external::randomseed='.$rndseed.';';
1.82      ng        876:   &Apache::run::run($safeinit,$safeeval);
1.17      albertel  877: }
                    878: 
1.55      albertel  879: sub startredirection {
                    880:   $Apache::lonxml::redirection++;
                    881:   push (@Apache::lonxml::outputstack, '');
                    882: }
                    883: 
                    884: sub endredirection {
                    885:   if (!$Apache::lonxml::redirection) {
1.72      albertel  886:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
1.55      albertel  887:     return '';
                    888:   }
                    889:   $Apache::lonxml::redirection--;
                    890:   pop @Apache::lonxml::outputstack;
1.97      albertel  891: }
                    892: 
                    893: sub end_tag {
                    894:   my ($tagstack,$parstack,$token)=@_;
                    895:   pop(@$tagstack);
                    896:   pop(@$parstack);
                    897:   &decreasedepth($token);
1.55      albertel  898: }
                    899: 
1.17      albertel  900: sub initdepth {
                    901:   @Apache::lonxml::depthcounter=();
                    902:   $Apache::lonxml::depth=-1;
                    903:   $Apache::lonxml::olddepth=-1;
                    904: }
                    905: 
                    906: sub increasedepth {
1.19      albertel  907:   my ($token) = @_;
1.17      albertel  908:   $Apache::lonxml::depth++;
                    909:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
                    910:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
                    911:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
                    912:   }
1.42      albertel  913:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
1.64      albertel  914:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
1.54      albertel  915: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
1.17      albertel  916: }
                    917: 
                    918: sub decreasedepth {
1.19      albertel  919:   my ($token) = @_;
1.17      albertel  920:   $Apache::lonxml::depth--;
1.36      albertel  921:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
                    922:     $#Apache::lonxml::depthcounter--;
                    923:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
                    924:   }
1.43      albertel  925:   if (  $Apache::lonxml::depth < -1) {
1.140     albertel  926:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
1.43      albertel  927:     $Apache::lonxml::depth='-1';
                    928:   }
1.42      albertel  929:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
1.64      albertel  930:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
1.54      albertel  931: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
1.1       sakharuk  932: }
1.19      albertel  933: 
                    934: sub get_all_text {
                    935: 
                    936:  my($tag,$pars)= @_;
                    937:  my $depth=0;
                    938:  my $token;
                    939:  my $result='';
1.57      albertel  940:  if ( $tag =~ m:^/: ) { 
                    941:    my $tag=substr($tag,1); 
                    942: #   &Apache::lonxml::debug("have:$tag:");
                    943:    while (($depth >=0) && ($token = $pars->get_token)) {
                    944: #     &Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]");
                    945:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
                    946:        $result.=$token->[1];
                    947:      } elsif ($token->[0] eq 'PI') {
                    948:        $result.=$token->[2];
                    949:      } elsif ($token->[0] eq 'S') {
1.151     albertel  950:        if ($token->[1] =~ /^$tag$/i) { $depth++; }
1.57      albertel  951:        $result.=$token->[4];
                    952:      } elsif ($token->[0] eq 'E')  {
1.151     albertel  953:        if ( $token->[1] =~ /^$tag$/i) { $depth--; }
1.57      albertel  954:        #skip sending back the last end tag
                    955:        if ($depth > -1) { $result.=$token->[2]; } else {
                    956: 	 $pars->unget_token($token);
                    957:        }
                    958:      }
                    959:    }
                    960:  } else {
                    961:    while ($token = $pars->get_token) {
                    962: #     &Apache::lonxml::debug("s 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') {
1.151     albertel  968:        if ( $token->[1] =~ /^$tag$/i) {
1.57      albertel  969: 	 $pars->unget_token($token); last;
                    970:        } else {
                    971: 	 $result.=$token->[4];
                    972:        }
                    973:      } elsif ($token->[0] eq 'E')  {
                    974:        $result.=$token->[2];
1.36      albertel  975:      }
1.19      albertel  976:    }
                    977:  }
1.49      albertel  978: # &Apache::lonxml::debug("Exit:$result:");
1.19      albertel  979:  return $result
                    980: }
                    981: 
1.23      albertel  982: sub newparser {
                    983:   my ($parser,$contentref,$dir) = @_;
                    984:   push (@$parser,HTML::TokeParser->new($contentref));
1.56      albertel  985:   $$parser['-1']->xml_mode('1');
1.23      albertel  986:   if ( $dir eq '' ) {
                    987:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
                    988:   } else {
                    989:     push (@Apache::lonxml::pwd, $dir);
                    990:   } 
                    991: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
                    992: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
                    993: }
1.1       sakharuk  994: 
1.8       albertel  995: sub parstring {
                    996:   my ($token) = @_;
                    997:   my $temp='';
1.142     albertel  998:   foreach (@{$token->[3]}) {
1.35      www       999:     unless ($_=~/\W/) {
1.42      albertel 1000:       my $val=$token->[2]->{$_};
1.150     albertel 1001:       $val =~ s/([\%\@\\\"])/\\$1/g;
1.51      albertel 1002:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
1.42      albertel 1003:       $temp .= "my \$$_=\"$val\";"
1.20      albertel 1004:     }
1.142     albertel 1005:   }
1.8       albertel 1006:   return $temp;
                   1007: }
1.22      albertel 1008: 
1.34      www      1009: sub writeallows {
1.126     www      1010:     unless ($#extlinks>=0) { return; }
1.34      www      1011:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
1.111     www      1012:     if ($ENV{'httpref.'.$thisurl}) {
                   1013: 	$thisurl=$ENV{'httpref.'.$thisurl};
                   1014:     }
1.34      www      1015:     my $thisdir=$thisurl;
                   1016:     $thisdir=~s/\/[^\/]+$//;
                   1017:     my %httpref=();
1.142     albertel 1018:     foreach (@extlinks) {
1.34      www      1019:        $httpref{'httpref.'.
1.125     www      1020:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
1.142     albertel 1021:     }
1.126     www      1022:     @extlinks=();
1.34      www      1023:     &Apache::lonnet::appenv(%httpref);
                   1024: }
                   1025: 
1.66      www      1026: #
                   1027: # Afterburner handles anchors, highlights and links
                   1028: #
                   1029: sub afterburn {
                   1030:     my $result=shift;
1.154     albertel 1031:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1032: 					    ['highlight','anchor','link']);
1.66      www      1033:     if ($ENV{'form.highlight'}) {
1.142     albertel 1034:        foreach (split(/\,/,$ENV{'form.highlight'})) {
1.66      www      1035:            my $anchorname=$_;
                   1036: 	   my $matchthis=$anchorname;
                   1037:            $matchthis=~s/\_+/\\s\+/g;
                   1038:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
1.142     albertel 1039:        }
1.66      www      1040:     }
                   1041:     if ($ENV{'form.link'}) {
1.142     albertel 1042:        foreach (split(/\,/,$ENV{'form.link'})) {
1.66      www      1043:            my ($anchorname,$linkurl)=split(/\>/,$_);
                   1044: 	   my $matchthis=$anchorname;
                   1045:            $matchthis=~s/\_+/\\s\+/g;
                   1046:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1.142     albertel 1047:        }
1.66      www      1048:     }
                   1049:     if ($ENV{'form.anchor'}) {
                   1050:         my $anchorname=$ENV{'form.anchor'};
                   1051: 	my $matchthis=$anchorname;
                   1052:         $matchthis=~s/\_+/\\s\+/g;
                   1053:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
                   1054:         $result.=(<<"ENDSCRIPT");
                   1055: <script>
                   1056:     document.location.hash='$anchorname';
                   1057: </script>
                   1058: ENDSCRIPT
                   1059:     }
                   1060:     return $result;
                   1061: }
                   1062: 
1.79      www      1063: sub storefile {
                   1064:     my ($file,$contents)=@_;
                   1065:     if (my $fh=Apache::File->new('>'.$file)) {
                   1066: 	print $fh $contents;
                   1067:         $fh->close();
1.147     albertel 1068:     } else {
                   1069:       &warning("Unable to save file $file");
1.79      www      1070:     }
                   1071: }
                   1072: 
1.151     albertel 1073: sub createnewhtml {
                   1074:   my $filecontents=(<<SIMPLECONTENT);
1.78      www      1075: <html>
                   1076: <head>
                   1077: <title>
                   1078:                            Title of Document Goes Here
                   1079: </title>
                   1080: </head>
                   1081: <body bgcolor="#FFFFFF">
                   1082: 
                   1083:                            Body of Document Goes Here
                   1084: 
                   1085: </body>
                   1086: </html>
                   1087: SIMPLECONTENT
1.151     albertel 1088:   return $filecontents;
                   1089: }
                   1090: 
1.147     albertel 1091: 
1.151     albertel 1092: sub inserteditinfo {
                   1093:       my ($result,$filecontents)=@_;
1.157     albertel 1094:       $filecontents = &HTML::Entities::encode($filecontents);
1.147     albertel 1095: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
1.78      www      1096:       my $editfooter=(<<ENDFOOTER);
                   1097: <hr />
                   1098: <a name="editsection" />
                   1099: <form method="post">
                   1100: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
                   1101: <br />
1.147     albertel 1102: <input type="hidden" name="showmode" value="Edit" />
1.107     www      1103: <input type="submit" name="attemptclean" 
                   1104:        value="Save and then attempt to clean HTML" />
                   1105: <input type="submit" name="savethisfile" value="Save this" />
1.147     albertel 1106: <input type="submit" name="showmode" value="View" />
1.78      www      1107: </form>
                   1108: ENDFOOTER
1.147     albertel 1109: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
1.78      www      1110:       $result=~s/(\<\/body\>)/$editfooter/is;
                   1111:       return $result;
                   1112: }
                   1113: 
1.152     albertel 1114: sub get_target {
                   1115:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
                   1116:   if ( $ENV{'request.state'} eq 'published') {
                   1117:     if ( defined($ENV{'form.grade_target'})
                   1118: 	 && ($viewgrades == 'F' )) {
                   1119:       return ($ENV{'form.grade_target'});
1.153     albertel 1120:     } elsif (defined($ENV{'form.grade_target'})) {
                   1121:       if (($ENV{'form.grade_target'} eq 'web') ||
                   1122: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
                   1123: 	return $ENV{'form.grade_target'}
                   1124:       } else {
                   1125: 	return 'web';
                   1126:       }
1.152     albertel 1127:     } else {
                   1128:       return 'web';
                   1129:     }
                   1130:   } elsif ($ENV{'request.state'} eq 'construct') {
                   1131:     if ( defined($ENV{'form.grade_target'})) {
                   1132:       return ($ENV{'form.grade_target'});
                   1133:     } else {
                   1134:       return 'web';
                   1135:     }
                   1136:   } else {
                   1137:     return 'web';
                   1138:   }
                   1139: }
                   1140: 
1.24      sakharuk 1141: sub handler {
                   1142:   my $request=shift;
1.68      www      1143: 
1.152     albertel 1144:   my $target=&get_target();
1.68      www      1145: 
1.65      albertel 1146:   $Apache::lonxml::debug=0;
1.68      www      1147: 
1.25      sakharuk 1148:   if ($ENV{'browser.mathml'}) {
1.27      albertel 1149:     $request->content_type('text/xml');
                   1150:   } else {
                   1151:     $request->content_type('text/html');
1.25      sakharuk 1152:   }
1.141     albertel 1153:   &Apache::loncommon::no_cache($request);
1.27      albertel 1154:   $request->send_http_header;
1.141     albertel 1155: 
1.45      www      1156:   return OK if $request->header_only;
1.27      albertel 1157: 
1.79      www      1158: 
                   1159:   my $file=&Apache::lonnet::filelocation("",$request->uri);
1.78      www      1160: #
                   1161: # Edit action? Save file.
                   1162: #
                   1163:   unless ($ENV{'request.state'} eq 'published') {
1.107     www      1164:       if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
1.79      www      1165: 	  &storefile($file,$ENV{'form.filecont'});
1.78      www      1166:       }
                   1167:   }
1.24      sakharuk 1168:   my %mystyle;
1.147     albertel 1169:   my $result = '';
1.50      albertel 1170:   my $filecontents=&Apache::lonnet::getfile($file);
                   1171:   if ($filecontents == -1) {
1.78      www      1172:     $result=(<<ENDNOTFOUND);
                   1173: <html>
                   1174: <head>
                   1175: <title>File not found</title>
                   1176: </head>
                   1177: <body bgcolor="#FFFFFF">
                   1178: <b>File not found: $file</b>
                   1179: </body>
                   1180: </html>
                   1181: ENDNOTFOUND
1.50      albertel 1182:     $filecontents='';
1.151     albertel 1183:     if ($ENV{'request.state'} ne 'published') {
                   1184:       $filecontents=&createnewhtml();
                   1185:       $ENV{'form.showmode'}='Edit'; #force edit mode
                   1186:     }
1.50      albertel 1187:   } else {
1.147     albertel 1188:     unless ($ENV{'request.state'} eq 'published') {
                   1189:       if ($ENV{'form.attemptclean'}) {
                   1190: 	$filecontents=&htmlclean($filecontents,1);
1.107     www      1191:       }
1.147     albertel 1192:     }
                   1193:     if ($ENV{'form.showmode'} ne 'Edit') {
                   1194:       $result = &Apache::lonxml::xmlparse($target,$filecontents,'',%mystyle);
                   1195:     }
1.78      www      1196:   }
                   1197: 
                   1198: #
                   1199: # Edit action? Insert editing commands
                   1200: #
                   1201:   unless ($ENV{'request.state'} eq 'published') {
1.147     albertel 1202:     if ($ENV{'form.showmode'} eq 'Edit') {
                   1203:       $result='<html><body bgcolor="#FFFFFF"></body></html>';
1.78      www      1204:       $result=&inserteditinfo($result,$filecontents);
1.147     albertel 1205:     }
1.66      www      1206:   }
1.147     albertel 1207: 
1.126     www      1208:   writeallows($request->uri);
1.50      albertel 1209: 
1.67      www      1210:   $request->print($result);
1.64      albertel 1211: 
1.45      www      1212:   return OK;
1.24      sakharuk 1213: }
1.147     albertel 1214: 
1.22      albertel 1215: sub debug {
                   1216:   if ($Apache::lonxml::debug eq 1) {
1.146     albertel 1217:     $|=1;
                   1218:     print("DEBUG:".join('<br />',@_)."<br />\n");
1.22      albertel 1219:   }
                   1220: }
1.49      albertel 1221: 
1.22      albertel 1222: sub error {
1.74      albertel 1223:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
1.146     albertel 1224:     print "<b>ERROR:</b>".join('<br />',@_)."<br />\n";
1.52      albertel 1225:   } else {
                   1226:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
                   1227:     #notify author
1.146     albertel 1228:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
1.52      albertel 1229:     #notify course
                   1230:     if ( $ENV{'request.course.id'} ) {
                   1231:       my $users=$ENV{'course.'.$ENV{'request.course.id'}.'.comment.email'};
1.143     www      1232:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
1.52      albertel 1233:       foreach my $user (split /\,/, $users) {
                   1234: 	($user,my $domain) = split /:/, $user;
1.143     www      1235: 	&Apache::lonmsg::user_normal_msg($user,$domain,
1.146     albertel 1236:         "Error [$declutter]",join('<br />',@_));
1.52      albertel 1237:       }
                   1238:     }
1.74      albertel 1239: 
1.52      albertel 1240:     #FIXME probably shouldn't have me get everything forever.
1.146     albertel 1241:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
1.74      albertel 1242:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
1.52      albertel 1243:   }
1.22      albertel 1244: }
1.49      albertel 1245: 
1.22      albertel 1246: sub warning {
1.73      harris41 1247:   if ($ENV{'request.state'} eq 'construct') {
1.146     albertel 1248:     print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
1.73      harris41 1249:   }
1.83      albertel 1250: }
                   1251: 
                   1252: sub get_param {
                   1253:   my ($param,$parstack,$safeeval,$context) = @_;
                   1254:   if ( ! $context ) { $context = -1; }
                   1255:   my $args ='';
                   1256:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.157     albertel 1257:   if ( ! $args ) { return undef; }
1.131     albertel 1258:   if ( $args =~ /my \$$param=\"/ ) {
                   1259:     return &Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
                   1260:   } else {
                   1261:     return undef;
                   1262:   }
1.22      albertel 1263: }
                   1264: 
1.132     albertel 1265: sub get_param_var {
                   1266:   my ($param,$parstack,$safeeval,$context) = @_;
                   1267:   if ( ! $context ) { $context = -1; }
                   1268:   my $args ='';
                   1269:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
                   1270:   if ( $args !~ /my \$$param=\"/ ) { return undef; }
                   1271:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
                   1272:   if ($value =~ /^[\$\@\%]/) {
                   1273:     return &Apache::run::run("return $value",$safeeval,1);
                   1274:   } else {
                   1275:     return $value;
                   1276:   }
                   1277: }
                   1278: 
1.74      albertel 1279: sub register_insert {
1.75      albertel 1280:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
1.74      albertel 1281:   my $i;
1.76      albertel 1282:   my $tagnum=0;
1.74      albertel 1283:   my @order;
                   1284:   for ($i=0;$i < $#data; $i++) {
                   1285:     my $line = $data[$i];
                   1286:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
                   1287:     if ( $line =~ /TABLE/ ) { last; }
1.92      albertel 1288:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
1.135     albertel 1289:     if ($tag) {
                   1290:       $insertlist{"$tagnum.tag"} = $tag;
                   1291:       $insertlist{"$tagnum.description"} = $descrip;
                   1292:       $insertlist{"$tagnum.color"} = $color;
                   1293:       $insertlist{"$tagnum.function"} = $function;
                   1294:       if (!defined($show)) { $show='yes'; }
                   1295:       $insertlist{"$tagnum.show"}= $show;
                   1296:       $insertlist{"$tag.num"}=$tagnum;
                   1297:       $tagnum++;
                   1298:     }
1.74      albertel 1299:   }
1.76      albertel 1300:   $i++; #skipping TABLE line
                   1301:   $tagnum = 0;
1.74      albertel 1302:   for (;$i < $#data;$i++) {
                   1303:     my $line = $data[$i];
1.76      albertel 1304:     my ($mnemonic,@which) = split(/ +/,$line);
                   1305:     my $tag = $insertlist{"$tagnum.tag"};
1.144     matthew  1306:     for (my $j=0;$j <=$#which;$j++) {
1.74      albertel 1307:       if ( $which[$j] eq 'Y' ) {
1.76      albertel 1308: 	if ($insertlist{"$j.show"} ne 'no') {
                   1309: 	  push(@{ $insertlist{"$tag.which"} },$j);
                   1310: 	}
1.74      albertel 1311:       }
                   1312:     }
1.76      albertel 1313:     $tagnum++;
1.74      albertel 1314:   }
                   1315: }
1.98      albertel 1316: 
                   1317: sub description {
                   1318:   my ($token)=@_;
1.138     albertel 1319:   my $tagnum;
                   1320:   my $tag=$token->[1];
                   1321:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
                   1322:     my $testtag=$namespace.'::'.$tag;
                   1323:     $tagnum=$insertlist{"$testtag.num"};
                   1324:     if (defined($tagnum)) { last; }
                   1325:   }
                   1326:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
                   1327:   return $insertlist{$tagnum.'.description'};
1.98      albertel 1328: }
1.123     albertel 1329: 
                   1330: # ----------------------------------------------------------------- whichuser
                   1331: # returns a list of $symb, $courseid, $domain, $name that is correct for
                   1332: # calls to lonnet functions for this setup.
                   1333: # - looks for form.grade_ parameters
                   1334: sub whichuser {
1.134     albertel 1335:   my ($symb,$courseid,$domain,$name);
1.123     albertel 1336:   if (defined($ENV{'form.grade_symb'})) {
                   1337:     my $tmp_courseid=$ENV{'form.grade_courseid'};
                   1338:     my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
                   1339:     if ($allowed) {
                   1340:       $symb=$ENV{'form.grade_symb'};
                   1341:       $courseid=$ENV{'form.grade_courseid'};
                   1342:       $domain=$ENV{'form.grade_domain'};
                   1343:       $name=$ENV{'form.grade_username'};
                   1344:     }
1.134     albertel 1345:   } else {
                   1346:     $symb=&Apache::lonnet::symbread();
                   1347:     $courseid=$ENV{'request.course.id'};
                   1348:     $domain=$ENV{'user.domain'};
                   1349:     $name=$ENV{'user.name'};
1.123     albertel 1350:   }
                   1351:   return ($symb,$courseid,$domain,$name);
                   1352: }
                   1353: 
1.1       sakharuk 1354: 1;
                   1355: __END__
1.68      www      1356: 
                   1357: 

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