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

1.2       sakharuk    1: # The LearningOnline Network with CAPA
1.3       sakharuk    2: # XML Parser Module 
1.2       sakharuk    3: #
1.158   ! matthew     4: # $Id: lonxml.pm,v 1.157 2002/03/14 20:30:36 albertel 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.130     www       322:     if ($ENV{'request.publicaccess'}) {
                    323: 	return 
                    324:          '<script>function LONCAPAreg(){} function LONCAPAstale(){}</script>';
                    325:     }
1.128     albertel  326:     if ($Apache::lonxml::registered && !$forcereg) { return ''; }
1.105     albertel  327:     $Apache::lonxml::registered=1;
1.100     www       328:     if (($ENV{'REQUEST_URI'}!~/^\/(res\/)*adm\//) || ($forcereg)) {
1.87      www       329:         my $hwkadd='';
                    330:         if ($ENV{'REQUEST_URI'}=~/\.(problem|exam|quiz|assess|survey|form)$/) {
                    331: 	    if (&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) {
                    332: 		$hwkadd.=(<<ENDSUBM);
                    333:                      menu.switchbutton
                    334:            (7,1,'subm.gif','view sub','missions',
1.88      www       335:                 'gocmd("/adm/grades","submission")');
1.87      www       336: ENDSUBM
                    337:             }
                    338: 	    if (&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) {
                    339: 		$hwkadd.=(<<ENDGRDS);
                    340:                      menu.switchbutton
                    341:            (7,2,'pgrd.gif','problem','grades',
1.88      www       342:                 'gocmd("/adm/grades","viewgrades")');
1.87      www       343: ENDGRDS
                    344:             }
                    345: 	    if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
                    346: 		$hwkadd.=(<<ENDPARM);
                    347:                      menu.switchbutton
                    348:            (7,3,'pparm.gif','problem','parms',
1.88      www       349:                 'gocmd("/adm/parmset","set")');
1.87      www       350: ENDPARM
                    351:             }
                    352: 	}
1.155     matthew   353: 	$result = (<<ENDREGTHIS);
1.87      www       354:      
1.68      www       355: <script language="JavaScript">
1.71      www       356: // BEGIN LON-CAPA Internal
1.86      www       357: 
1.69      www       358:     function LONCAPAreg() {
1.158   ! matthew   359: 	  menu=window.open("","LONCAPAmenu","",false);
1.86      www       360:           menu.clearTimeout(menu.menucltim);
1.69      www       361: 	  menu.currentURL=window.location.pathname;
                    362:           menu.currentStale=0;
1.85      www       363:           menu.clearbut(3,1);
                    364:           menu.switchbutton
1.108     www       365:        (6,3,'catalog.gif','catalog','info','catalog_info()');
                    366:           menu.switchbutton
1.85      www       367:        (8,1,'eval.gif','evaluate','this','gopost("/adm/evaluate",currentURL)');
                    368:           menu.switchbutton
                    369:     (8,2,'fdbk.gif','feedback','on this','gopost("/adm/feedback",currentURL)');
                    370:           menu.switchbutton
                    371:      (8,3,'prt.gif','prepare','printout','gopost("/adm/printout",currentURL)');
                    372:           menu.switchbutton
                    373:        (2,1,'back.gif','backward','','gopost("/adm/flip","back:"+currentURL)');
                    374:           menu.switchbutton
                    375:      (2,3,'forw.gif','forward','','gopost("/adm/flip","forward:"+currentURL)');
1.94      www       376:           menu.switchbutton
                    377:                             (9,1,'sbkm.gif','set','bookmark','set_bookmark()');
                    378:           menu.switchbutton
                    379:                          (9,2,'vbkm.gif','view','bookmark','edit_bookmarks()');
                    380:           menu.switchbutton
1.95      www       381:                                (9,3,'anot.gif','anno-','tations','annotate()');
1.87      www       382:           $hwkadd
1.69      www       383:     }
1.86      www       384: 
1.69      www       385:     function LONCAPAstale() {
1.158   ! matthew   386: 	  menu=window.open("","LONCAPAmenu","",false);
1.86      www       387:           menu.currentStale=1;
1.127     www       388:           menu.switchbutton
                    389:              (3,1,'reload.gif','return','location','go(currentURL)');
                    390:           menu.clearbut(7,1);
                    391:           menu.clearbut(7,2);
                    392:           menu.clearbut(7,3);
1.86      www       393:           menu.menucltim=menu.setTimeout(
1.94      www       394:  'clearbut(2,1);clearbut(2,3);clearbut(8,1);clearbut(8,2);clearbut(8,3);'+
1.108     www       395:  'clearbut(9,1);clearbut(9,2);clearbut(9,3);clearbut(6,3)',
1.86      www       396: 			  2000);
                    397: 
1.87      www       398:       }
1.86      www       399: 
                    400: // END LON-CAPA Internal
                    401: </script>
                    402: ENDREGTHIS
                    403: 
                    404:     } else {
1.155     matthew   405:         $result = (<<ENDDONOTREGTHIS);
1.86      www       406: 
                    407: <script language="JavaScript">
                    408: // BEGIN LON-CAPA Internal
                    409: 
                    410:     function LONCAPAreg() {
1.158   ! matthew   411: 	  menu=window.open("","LONCAPAmenu","",false);
1.69      www       412:           menu.currentStale=1;
1.85      www       413:           menu.clearbut(2,1);
                    414:           menu.clearbut(2,3);
                    415:           menu.clearbut(8,1);
                    416:           menu.clearbut(8,2);
                    417:           menu.clearbut(8,3);
1.86      www       418:           if (menu.currentURL) {
                    419:              menu.switchbutton
                    420:               (3,1,'reload.gif','return','location','go(currentURL)');
                    421:  	  } else {
                    422: 	      menu.clearbut(3,1);
                    423:           }
                    424:     }
                    425: 
                    426:     function LONCAPAstale() {
1.68      www       427:     }
1.86      www       428: 
1.71      www       429: // END LON-CAPA Internal
1.68      www       430: </script>
1.86      www       431: ENDDONOTREGTHIS
                    432:     }
1.155     matthew   433:     if ($target eq 'edit') {
1.156     matthew   434: 	# Javascript routines for construction space:
                    435: 	# openbrowser and opensearcher will start the file browser
                    436: 	# (lonindexer) and searcher (lonsearchcat) respectively.
                    437: 	# Inputs are the name of the html form being used
                    438: 	# and the name of the element the selected URL should
                    439: 	# be placed in.
1.155     matthew   440:         $result .=<<"ENDBROWSERSCRIPT";
                    441: <script>
1.156     matthew   442:     var editbrowser;
1.155     matthew   443:     function openbrowser(formname,elementname) {
                    444:         var url = '/res/?';
1.156     matthew   445:         if (editbrowser == null) {
1.155     matthew   446:             url += 'launch=1&';
                    447:         }
                    448:         url += 'catalogmode=interactive&';
                    449:         url += 'mode=edit&';
                    450:         url += 'form=' + formname + '&';
                    451:         url += 'element=' + elementname + '';
                    452:         var title = 'Browser';
                    453:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    454:         options += ',width=700,height=600';
1.156     matthew   455:         editbrowser = open(url,title,options,'1');
                    456:         editbrowser.focus();
                    457:     }
                    458:     var editsearcher;
                    459:     function opensearcher(formname,elementname) {
                    460:         var url = '/adm/searchcat?';
                    461:         if (editsearcher == null) {
                    462:             url += 'launch=1&';
                    463:         }
                    464:         url += 'catalogmode=interactive&';
                    465:         url += 'mode=edit&';
                    466:         url += 'form=' + formname + '&';
                    467:         url += 'element=' + elementname + '';
                    468:         var title = 'Search';
                    469:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    470:         options += ',width=700,height=600';
                    471:         editsearcher = open(url,title,options,'1');
                    472:         editsearcher.focus();
1.155     matthew   473:     }
                    474: </script>
                    475: ENDBROWSERSCRIPT
                    476:     }
                    477:     return $result;
1.69      www       478: }
                    479: 
                    480: sub loadevents() {
                    481:     return 'LONCAPAreg();';
                    482: }
                    483: 
                    484: sub unloadevents() {
                    485:     return 'LONCAPAstale();';
1.68      www       486: }
                    487: 
1.48      albertel  488: sub printalltags {
                    489:   my $temp;
                    490:   foreach $temp (sort keys %Apache::lonxml::alltags) {
1.141     albertel  491:     &Apache::lonxml::debug("$temp -- ".
                    492: 		  join(',',@{ $Apache::lonxml::alltags{$temp} }));
1.48      albertel  493:   }
                    494: }
1.31      sakharuk  495: 
1.3       sakharuk  496: sub xmlparse {
1.18      albertel  497:  my ($target,$content_file_string,$safeinit,%style_for_target) = @_;
1.96      albertel  498: 
                    499:  &setup_globals($target);
1.48      albertel  500:  #&printalltags();
1.16      albertel  501:  my @pars = ();
1.23      albertel  502:  my $pwd=$ENV{'request.filename'};
                    503:  $pwd =~ s:/[^/]*$::;
                    504:  &newparser(\@pars,\$content_file_string,$pwd);
1.24      sakharuk  505: 
1.3       sakharuk  506:  my $safeeval = new Safe;
1.40      albertel  507:  my $safehole = new Safe::Hole;
1.82      ng        508:  &init_safespace($target,$safeeval,$safehole,$safeinit);
1.3       sakharuk  509: #-------------------- Redefinition of the target in the case of compound target
                    510: 
                    511:  ($target, my @tenta) = split('&&',$target);
                    512: 
1.150     albertel  513:  my @stack = ();
1.3       sakharuk  514:  my @parstack = ();
1.17      albertel  515:  &initdepth;
1.67      www       516: 
1.101     albertel  517:  my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
                    518: 				   $safeeval,\%style_for_target);
1.125     www       519:  if ($ENV{'request.uri'}) {
                    520:     &writeallows($ENV{'request.uri'});
                    521:  }
1.3       sakharuk  522:  return $finaloutput;
1.106     www       523: }
                    524: 
                    525: sub htmlclean {
1.107     www       526:     my ($raw,$full)=@_;
1.106     www       527: 
                    528:     my $tree = HTML::TreeBuilder->new;
                    529:     $tree->ignore_unknown(0);
1.140     albertel  530: 
1.106     www       531:     $tree->parse($raw);
                    532: 
1.107     www       533:     my $output= $tree->as_HTML(undef,' ');
1.140     albertel  534: 
1.111     www       535:     $output=~s/\<(br|hr|img|meta|allow)([^\>\/]*)\>/\<$1$2 \/\>/gis;
                    536:     $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
1.107     www       537:     unless ($full) {
                    538:        $output=~s/\<[\/]*(body|head|html)\>//gis;
                    539:     }
1.106     www       540: 
                    541:     $tree = $tree->delete;
                    542: 
                    543:     return $output;
1.15      albertel  544: }
                    545: 
1.101     albertel  546: sub inner_xmlparse {
                    547:   my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
                    548:   my $finaloutput = '';
                    549:   my $result;
                    550:   my $token;
                    551:   while ( $#$pars > -1 ) {
                    552:     while ($token = $$pars['-1']->get_token) {
                    553:       if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
                    554: 	if ($metamode<1) {
                    555: 	  $result=$token->[1];
                    556: 	}
                    557:       } elsif ($token->[0] eq 'PI') {
                    558: 	if ($metamode<1) {
                    559: 	  $result=$token->[2];
                    560: 	}
                    561:       } elsif ($token->[0] eq 'S') {
1.140     albertel  562: 	# add tag to stack
1.101     albertel  563: 	push (@$stack,$token->[1]);
                    564: 	# add parameters list to another stack
                    565: 	push (@$parstack,&parstring($token));
1.140     albertel  566: 	&increasedepth($token);
1.101     albertel  567: 	if (exists $$style_for_target{$token->[1]}) {
                    568: 	  if ($Apache::lonxml::redirection) {
1.140     albertel  569: 	    $Apache::lonxml::outputstack['-1'] .=
1.101     albertel  570: 	      &recurse($$style_for_target{$token->[1]},$target,$safeeval,
                    571: 		       $style_for_target,@$parstack);
                    572: 	  } else {
                    573: 	    $finaloutput .= &recurse($$style_for_target{$token->[1]},$target,
                    574: 				     $safeeval,$style_for_target,@$parstack);
                    575: 	  }
                    576: 	} else {
                    577: 	  $result = &callsub("start_$token->[1]", $target, $token, $stack,
                    578: 			     $parstack, $pars, $safeeval, $style_for_target);
1.140     albertel  579: 	}
1.101     albertel  580:       } elsif ($token->[0] eq 'E') {
                    581: 	#clear out any tags that didn't end
                    582: 	while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
1.150     albertel  583: 	  my $lasttag=$$stack[-1];
                    584: 	  if ($token->[1] =~ /^$lasttag$/i) {
                    585: 	    &Apache::lonxml::warning('Using tag &lt;/'.$token->[1].'&gt; as end tag to &lt;'.$$stack[-1].'&gt;');
                    586: 	    last;
                    587: 	  } else {
1.152     albertel  588: 	    &Apache::lonxml::warning('Found tag &lt;/'.$token->[1].'&gt; when looking for &lt;/'.$$stack[-1].'&gt; in file');
1.150     albertel  589: 	    &end_tag($stack,$parstack,$token);
                    590: 	  }
1.101     albertel  591: 	}
1.140     albertel  592: 
                    593: 	if (exists($$style_for_target{'/'."$token->[1]"})) {
1.101     albertel  594: 	  if ($Apache::lonxml::redirection) {
                    595: 	    $Apache::lonxml::outputstack['-1'] .=  
                    596: 	      &recurse($$style_for_target{'/'."$token->[1]"},
                    597: 		       $target,$safeeval,$style_for_target,@$parstack);
                    598: 	  } else {
                    599: 	    $finaloutput .= &recurse($$style_for_target{'/'."$token->[1]"},
                    600: 				     $target,$safeeval,$style_for_target,
                    601: 				     @$parstack);
                    602: 	  }
                    603: 	} else {
                    604: 	  $result = &callsub("end_$token->[1]", $target, $token, $stack,
                    605: 			     $parstack, $pars,$safeeval, $style_for_target);
                    606: 	}
                    607:       } else {
                    608: 	&Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
                    609:       }
                    610:       #evaluate variable refs in result
                    611:       if ($result ne "") {
                    612: 	if ( $#$parstack > -1 ) {
                    613: 	  if ($Apache::lonxml::redirection) {
                    614: 	    $Apache::lonxml::outputstack['-1'] .= 
                    615: 	      &Apache::run::evaluate($result,$safeeval,$$parstack['-1']);
                    616: 	  } else {
                    617: 	    $finaloutput .= &Apache::run::evaluate($result,$safeeval,
                    618: 						   $$parstack['-1']);
                    619: 	  }
                    620: 	} else {
                    621: 	  $finaloutput .= &Apache::run::evaluate($result,$safeeval,'');
                    622: 	}
                    623: 	$result = '';
                    624:       } 
                    625:       if ($token->[0] eq 'E') { 
                    626: 	&end_tag($stack,$parstack,$token);
                    627:       }
                    628:     }
                    629:     pop @$pars;
                    630:     pop @Apache::lonxml::pwd;
                    631:   }
                    632: 
                    633:   # if ($target eq 'meta') {
                    634:   #   $finaloutput.=&endredirection;
                    635:   # }
                    636: 
                    637:   if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
                    638:     $finaloutput=&afterburn($finaloutput);
                    639:   }
                    640:   return $finaloutput;
                    641: }
1.67      www       642: 
1.15      albertel  643: sub recurse {
                    644:   my @innerstack = (); 
                    645:   my @innerparstack = ();
                    646:   my ($newarg,$target,$safeeval,$style_for_target,@parstack) = @_;
1.16      albertel  647:   my @pat = ();
1.23      albertel  648:   &newparser(\@pat,\$newarg);
1.15      albertel  649:   my $tokenpat;
                    650:   my $partstring = '';
                    651:   my $output='';
1.16      albertel  652:   my $decls='';
1.140     albertel  653:   &Apache::lonxml::debug("Recursing");
1.16      albertel  654:   while ( $#pat > -1 ) {
                    655:     while  ($tokenpat = $pat[$#pat]->get_token) {
1.57      albertel  656:       if (($tokenpat->[0] eq 'T') || ($tokenpat->[0] eq 'C') || ($tokenpat->[0] eq 'D') ) {
1.61      albertel  657: 	if ($metamode<1) { $partstring=$tokenpat->[1]; }
1.57      albertel  658:       } elsif ($tokenpat->[0] eq 'PI') {
1.61      albertel  659: 	if ($metamode<1) { $partstring=$tokenpat->[2]; }
1.16      albertel  660:       } elsif ($tokenpat->[0] eq 'S') {
                    661: 	push (@innerstack,$tokenpat->[1]);
                    662: 	push (@innerparstack,&parstring($tokenpat));
1.19      albertel  663: 	&increasedepth($tokenpat);
1.84      albertel  664: 	$partstring = &callsub("start_$tokenpat->[1]", $target, $tokenpat,
                    665: 			       \@innerstack, \@innerparstack, \@pat,
                    666: 			       $safeeval, $style_for_target);
1.16      albertel  667:       } elsif ($tokenpat->[0] eq 'E') {
                    668: 	#clear out any tags that didn't end
1.150     albertel  669: 	while ($tokenpat->[1] ne $innerstack[$#innerstack]
1.43      albertel  670: 	       && ($#innerstack > -1)) {
1.150     albertel  671: 	  my $lasttag=$innerstack[-1];
                    672: 	  if ($tokenpat->[1] =~ /^$lasttag$/i) {
                    673: 	    &Apache::lonxml::warning('Using tag &lt;/'.$tokenpat->[1].'&gt; as end tag to &lt;'.$innerstack[-1].'&gt;');
                    674: 	    last;
                    675: 	  } else {
1.152     albertel  676: 	    &Apache::lonxml::warning('Found tag &lt;/'.$tokenpat->[1].'&gt; when looking for &lt;/'.$innerstack[-1].'&gt; in file');
1.150     albertel  677: 	    &end_tag(\@innerstack,\@innerparstack,$tokenpat);
                    678: 	  }
1.43      albertel  679: 	}
1.84      albertel  680: 	$partstring = &callsub("end_$tokenpat->[1]", $target, $tokenpat,
                    681: 			       \@innerstack, \@innerparstack, \@pat,
                    682: 			       $safeeval, $style_for_target);
1.57      albertel  683:       } else {
                    684: 	&Apache::lonxml::error("Unknown token event :$tokenpat->[0]:$tokenpat->[1]:");
1.16      albertel  685:       }
                    686:       #pass both the variable to the style tag, and the tag we 
                    687:       #are processing inside the <definedtag>
                    688:       if ( $partstring ne "" ) {
                    689: 	if ( $#parstack > -1 ) { 
                    690: 	  if ( $#innerparstack > -1 ) { 
                    691: 	    $decls= $parstack[$#parstack].$innerparstack[$#innerparstack];
                    692: 	  } else {
                    693: 	    $decls= $parstack[$#parstack];
                    694: 	  }
                    695: 	} else {
                    696: 	  if ( $#innerparstack > -1 ) { 
                    697: 	    $decls=$innerparstack[$#innerparstack];
                    698: 	  } else {
                    699: 	    $decls='';
                    700: 	  }
                    701: 	}
                    702: 	$output .= &Apache::run::evaluate($partstring,$safeeval,$decls);
                    703: 	$partstring = '';
                    704:       }
1.17      albertel  705:       if ($tokenpat->[0] eq 'E') { pop @innerstack;pop @innerparstack;
1.19      albertel  706: 				 &decreasedepth($tokenpat);}
1.15      albertel  707:     }
1.16      albertel  708:     pop @pat;
1.23      albertel  709:     pop @Apache::lonxml::pwd;
1.15      albertel  710:   }
1.140     albertel  711:   &Apache::lonxml::debug("Exiting Recursing");
1.15      albertel  712:   return $output;
1.7       albertel  713: }
                    714: 
                    715: sub callsub {
1.84      albertel  716:   my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
1.7       albertel  717:   my $currentstring='';
1.72      albertel  718:   my $nodefault;
1.7       albertel  719:   {
1.59      albertel  720:     my $sub1;
1.7       albertel  721:     no strict 'refs';
1.68      www       722:     my $tag=$token->[1];
1.141     albertel  723:     my $space=$Apache::lonxml::alltags{$tag}[-1];
1.68      www       724:     if (!$space) {
1.141     albertel  725:      	$tag=~tr/A-Z/a-z/;
1.68      www       726: 	$sub=~tr/A-Z/a-z/;
1.141     albertel  727: 	$space=$Apache::lonxml::alltags{$tag}[-1]
1.68      www       728:     }
1.97      albertel  729: 
                    730:     my $deleted=0;
                    731:     $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
                    732:     if (($token->[0] eq 'S') && ($target eq 'modified')) {
                    733:       $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
                    734: 					     $parstack,$parser,$safeeval,
                    735: 					     $style);
                    736:     }
                    737:     if (!$deleted) {
                    738:       if ($space) {
1.152     albertel  739: 	#&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
1.97      albertel  740: 	$sub1="$space\:\:$sub";
                    741: 	($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
                    742: 					     $parstack,$parser,$safeeval,
                    743: 					     $style);
                    744:       } else {
1.152     albertel  745: 	#&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
1.97      albertel  746: 	if ($metamode <1) {
                    747: 	  if (defined($token->[4]) && ($metamode < 1)) {
                    748: 	    $currentstring = $token->[4];
                    749: 	  } else {
                    750: 	    $currentstring = $token->[2];
                    751: 	  }
1.62      sakharuk  752: 	}
1.7       albertel  753:       }
1.97      albertel  754:       #    &Apache::lonxml::debug("nodefalt:$nodefault:");
                    755:       if ($currentstring eq '' && $nodefault eq '') {
                    756: 	if ($target eq 'edit') {
                    757: 	  &Apache::lonxml::debug("doing default edit for $token->[1]");
                    758: 	  if ($token->[0] eq 'S') {
                    759: 	    $currentstring = &Apache::edit::tag_start($target,$token);
                    760: 	  } elsif ($token->[0] eq 'E') {
                    761: 	    $currentstring = &Apache::edit::tag_end($target,$token);
                    762: 	  }
                    763: 	} elsif ($target eq 'modified') {
                    764: 	  if ($token->[0] eq 'S') {
                    765: 	    $currentstring = $token->[4];
                    766: 	    $currentstring.=&Apache::edit::handle_insert();
                    767: 	  } else {
                    768: 	    $currentstring = $token->[2];
                    769: 	  }
1.72      albertel  770: 	}
                    771:       }
1.7       albertel  772:     }
                    773:     use strict 'refs';
                    774:   }
                    775:   return $currentstring;
1.82      ng        776: }
                    777: 
1.96      albertel  778: sub setup_globals {
                    779:   my ($target)=@_;
1.99      albertel  780:   $Apache::lonxml::registered = 0;
1.101     albertel  781:   @Apache::lonxml::pwd=();
1.124     albertel  782:   @Apache::lonxml::extlinks=();
1.96      albertel  783:   if ($target eq 'meta') {
                    784:     $Apache::lonxml::redirection = 0;
                    785:     $Apache::lonxml::metamode = 1;
                    786:     $Apache::lonxml::evaluate = 1;
                    787:     $Apache::lonxml::import = 0;
1.129     albertel  788:   } elsif ($target eq 'answer') {
                    789:     $Apache::lonxml::redirection = 0;
                    790:     $Apache::lonxml::metamode = 1;
                    791:     $Apache::lonxml::evaluate = 1;
                    792:     $Apache::lonxml::import = 1;
1.96      albertel  793:   } elsif ($target eq 'grade') {
                    794:     &startredirection;
                    795:     $Apache::lonxml::metamode = 0;
                    796:     $Apache::lonxml::evaluate = 1;
                    797:     $Apache::lonxml::import = 1;
                    798:   } elsif ($target eq 'modified') {
                    799:     $Apache::lonxml::redirection = 0;
                    800:     $Apache::lonxml::metamode = 0;
                    801:     $Apache::lonxml::evaluate = 0;
                    802:     $Apache::lonxml::import = 0;
                    803:   } elsif ($target eq 'edit') {
                    804:     $Apache::lonxml::redirection = 0;
                    805:     $Apache::lonxml::metamode = 0;
                    806:     $Apache::lonxml::evaluate = 0;
                    807:     $Apache::lonxml::import = 0;
                    808:   } else {
                    809:     $Apache::lonxml::redirection = 0;
                    810:     $Apache::lonxml::metamode = 0;
                    811:     $Apache::lonxml::evaluate = 1;
                    812:     $Apache::lonxml::import = 1;
                    813:   }
                    814: }
                    815: 
1.82      ng        816: sub init_safespace {
                    817:   my ($target,$safeeval,$safehole,$safeinit) = @_;
                    818:   $safeeval->permit("entereval");
                    819:   $safeeval->permit(":base_math");
                    820:   $safeeval->permit("sort");
                    821:   $safeeval->deny(":base_io");
1.102     albertel  822:   $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
1.82      ng        823:   $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
                    824:   
                    825:   $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
                    826:   $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
                    827:   $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
                    828:   $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
                    829:   $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
                    830:   $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
                    831:   $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
                    832:   $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
                    833:   $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
                    834:   $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
                    835:   $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
                    836:   $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
                    837:   $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
                    838:   $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
                    839:   $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
                    840:   $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
                    841:   $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
                    842:   $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
                    843:   $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
1.91      ng        844:   $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
                    845:   $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
                    846:   $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
                    847:   $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
                    848:   $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
                    849:   $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
                    850:   $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
                    851:   $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
                    852:   $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
                    853:   $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
                    854:   $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
1.93      ng        855:   $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
1.91      ng        856:   $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
                    857:   $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
                    858:   $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
                    859:   $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
                    860:   $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
                    861:   $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
                    862:   $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
                    863:   $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
                    864:   $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
                    865: 
1.82      ng        866: #need to inspect this class of ops
                    867: # $safeeval->deny(":base_orig");
1.91      ng        868:   $safeinit .= ';$external::target="'.$target.'";';
1.121     albertel  869:   my $rndseed;
1.123     albertel  870:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                    871:   $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
1.121     albertel  872:   $safeinit .= ';$external::randomseed='.$rndseed.';';
1.82      ng        873:   &Apache::run::run($safeinit,$safeeval);
1.17      albertel  874: }
                    875: 
1.55      albertel  876: sub startredirection {
                    877:   $Apache::lonxml::redirection++;
                    878:   push (@Apache::lonxml::outputstack, '');
                    879: }
                    880: 
                    881: sub endredirection {
                    882:   if (!$Apache::lonxml::redirection) {
1.72      albertel  883:     &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
1.55      albertel  884:     return '';
                    885:   }
                    886:   $Apache::lonxml::redirection--;
                    887:   pop @Apache::lonxml::outputstack;
1.97      albertel  888: }
                    889: 
                    890: sub end_tag {
                    891:   my ($tagstack,$parstack,$token)=@_;
                    892:   pop(@$tagstack);
                    893:   pop(@$parstack);
                    894:   &decreasedepth($token);
1.55      albertel  895: }
                    896: 
1.17      albertel  897: sub initdepth {
                    898:   @Apache::lonxml::depthcounter=();
                    899:   $Apache::lonxml::depth=-1;
                    900:   $Apache::lonxml::olddepth=-1;
                    901: }
                    902: 
                    903: sub increasedepth {
1.19      albertel  904:   my ($token) = @_;
1.17      albertel  905:   $Apache::lonxml::depth++;
                    906:   $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
                    907:   if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
                    908:     $Apache::lonxml::olddepth=$Apache::lonxml::depth;
                    909:   }
1.42      albertel  910:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
1.64      albertel  911:   &Apache::lonxml::debug("s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n");
1.54      albertel  912: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
1.17      albertel  913: }
                    914: 
                    915: sub decreasedepth {
1.19      albertel  916:   my ($token) = @_;
1.17      albertel  917:   $Apache::lonxml::depth--;
1.36      albertel  918:   if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
                    919:     $#Apache::lonxml::depthcounter--;
                    920:     $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
                    921:   }
1.43      albertel  922:   if (  $Apache::lonxml::depth < -1) {
1.140     albertel  923:     &Apache::lonxml::warning("Missing tags, unable to properly run file.");
1.43      albertel  924:     $Apache::lonxml::depth='-1';
                    925:   }
1.42      albertel  926:   my $curdepth=join('_',@Apache::lonxml::depthcounter);
1.64      albertel  927:   &Apache::lonxml::debug("e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n");
1.54      albertel  928: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
1.1       sakharuk  929: }
1.19      albertel  930: 
                    931: sub get_all_text {
                    932: 
                    933:  my($tag,$pars)= @_;
                    934:  my $depth=0;
                    935:  my $token;
                    936:  my $result='';
1.57      albertel  937:  if ( $tag =~ m:^/: ) { 
                    938:    my $tag=substr($tag,1); 
                    939: #   &Apache::lonxml::debug("have:$tag:");
                    940:    while (($depth >=0) && ($token = $pars->get_token)) {
                    941: #     &Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]");
                    942:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
                    943:        $result.=$token->[1];
                    944:      } elsif ($token->[0] eq 'PI') {
                    945:        $result.=$token->[2];
                    946:      } elsif ($token->[0] eq 'S') {
1.151     albertel  947:        if ($token->[1] =~ /^$tag$/i) { $depth++; }
1.57      albertel  948:        $result.=$token->[4];
                    949:      } elsif ($token->[0] eq 'E')  {
1.151     albertel  950:        if ( $token->[1] =~ /^$tag$/i) { $depth--; }
1.57      albertel  951:        #skip sending back the last end tag
                    952:        if ($depth > -1) { $result.=$token->[2]; } else {
                    953: 	 $pars->unget_token($token);
                    954:        }
                    955:      }
                    956:    }
                    957:  } else {
                    958:    while ($token = $pars->get_token) {
                    959: #     &Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
                    960:      if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
                    961:        $result.=$token->[1];
                    962:      } elsif ($token->[0] eq 'PI') {
                    963:        $result.=$token->[2];
                    964:      } elsif ($token->[0] eq 'S') {
1.151     albertel  965:        if ( $token->[1] =~ /^$tag$/i) {
1.57      albertel  966: 	 $pars->unget_token($token); last;
                    967:        } else {
                    968: 	 $result.=$token->[4];
                    969:        }
                    970:      } elsif ($token->[0] eq 'E')  {
                    971:        $result.=$token->[2];
1.36      albertel  972:      }
1.19      albertel  973:    }
                    974:  }
1.49      albertel  975: # &Apache::lonxml::debug("Exit:$result:");
1.19      albertel  976:  return $result
                    977: }
                    978: 
1.23      albertel  979: sub newparser {
                    980:   my ($parser,$contentref,$dir) = @_;
                    981:   push (@$parser,HTML::TokeParser->new($contentref));
1.56      albertel  982:   $$parser['-1']->xml_mode('1');
1.23      albertel  983:   if ( $dir eq '' ) {
                    984:     push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
                    985:   } else {
                    986:     push (@Apache::lonxml::pwd, $dir);
                    987:   } 
                    988: #  &Apache::lonxml::debug("pwd:$#Apache::lonxml::pwd");
                    989: #  &Apache::lonxml::debug("pwd:$Apache::lonxml::pwd[$#Apache::lonxml::pwd]");
                    990: }
1.1       sakharuk  991: 
1.8       albertel  992: sub parstring {
                    993:   my ($token) = @_;
                    994:   my $temp='';
1.142     albertel  995:   foreach (@{$token->[3]}) {
1.35      www       996:     unless ($_=~/\W/) {
1.42      albertel  997:       my $val=$token->[2]->{$_};
1.150     albertel  998:       $val =~ s/([\%\@\\\"])/\\$1/g;
1.51      albertel  999:       #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
1.42      albertel 1000:       $temp .= "my \$$_=\"$val\";"
1.20      albertel 1001:     }
1.142     albertel 1002:   }
1.8       albertel 1003:   return $temp;
                   1004: }
1.22      albertel 1005: 
1.34      www      1006: sub writeallows {
1.126     www      1007:     unless ($#extlinks>=0) { return; }
1.34      www      1008:     my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
1.111     www      1009:     if ($ENV{'httpref.'.$thisurl}) {
                   1010: 	$thisurl=$ENV{'httpref.'.$thisurl};
                   1011:     }
1.34      www      1012:     my $thisdir=$thisurl;
                   1013:     $thisdir=~s/\/[^\/]+$//;
                   1014:     my %httpref=();
1.142     albertel 1015:     foreach (@extlinks) {
1.34      www      1016:        $httpref{'httpref.'.
1.125     www      1017:  	        &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
1.142     albertel 1018:     }
1.126     www      1019:     @extlinks=();
1.34      www      1020:     &Apache::lonnet::appenv(%httpref);
                   1021: }
                   1022: 
1.66      www      1023: #
                   1024: # Afterburner handles anchors, highlights and links
                   1025: #
                   1026: sub afterburn {
                   1027:     my $result=shift;
1.154     albertel 1028:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1029: 					    ['highlight','anchor','link']);
1.66      www      1030:     if ($ENV{'form.highlight'}) {
1.142     albertel 1031:        foreach (split(/\,/,$ENV{'form.highlight'})) {
1.66      www      1032:            my $anchorname=$_;
                   1033: 	   my $matchthis=$anchorname;
                   1034:            $matchthis=~s/\_+/\\s\+/g;
                   1035:            $result=~s/($matchthis)/\<font color=\"red\"\>$1\<\/font\>/gs;
1.142     albertel 1036:        }
1.66      www      1037:     }
                   1038:     if ($ENV{'form.link'}) {
1.142     albertel 1039:        foreach (split(/\,/,$ENV{'form.link'})) {
1.66      www      1040:            my ($anchorname,$linkurl)=split(/\>/,$_);
                   1041: 	   my $matchthis=$anchorname;
                   1042:            $matchthis=~s/\_+/\\s\+/g;
                   1043:            $result=~s/($matchthis)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1.142     albertel 1044:        }
1.66      www      1045:     }
                   1046:     if ($ENV{'form.anchor'}) {
                   1047:         my $anchorname=$ENV{'form.anchor'};
                   1048: 	my $matchthis=$anchorname;
                   1049:         $matchthis=~s/\_+/\\s\+/g;
                   1050:         $result=~s/($matchthis)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
                   1051:         $result.=(<<"ENDSCRIPT");
                   1052: <script>
                   1053:     document.location.hash='$anchorname';
                   1054: </script>
                   1055: ENDSCRIPT
                   1056:     }
                   1057:     return $result;
                   1058: }
                   1059: 
1.79      www      1060: sub storefile {
                   1061:     my ($file,$contents)=@_;
                   1062:     if (my $fh=Apache::File->new('>'.$file)) {
                   1063: 	print $fh $contents;
                   1064:         $fh->close();
1.147     albertel 1065:     } else {
                   1066:       &warning("Unable to save file $file");
1.79      www      1067:     }
                   1068: }
                   1069: 
1.151     albertel 1070: sub createnewhtml {
                   1071:   my $filecontents=(<<SIMPLECONTENT);
1.78      www      1072: <html>
                   1073: <head>
                   1074: <title>
                   1075:                            Title of Document Goes Here
                   1076: </title>
                   1077: </head>
                   1078: <body bgcolor="#FFFFFF">
                   1079: 
                   1080:                            Body of Document Goes Here
                   1081: 
                   1082: </body>
                   1083: </html>
                   1084: SIMPLECONTENT
1.151     albertel 1085:   return $filecontents;
                   1086: }
                   1087: 
1.147     albertel 1088: 
1.151     albertel 1089: sub inserteditinfo {
                   1090:       my ($result,$filecontents)=@_;
1.157     albertel 1091:       $filecontents = &HTML::Entities::encode($filecontents);
1.147     albertel 1092: #      my $editheader='<a href="#editsection">Edit below</a><hr />';
1.78      www      1093:       my $editfooter=(<<ENDFOOTER);
                   1094: <hr />
                   1095: <a name="editsection" />
                   1096: <form method="post">
                   1097: <textarea cols="80" rows="40" name="filecont">$filecontents</textarea>
                   1098: <br />
1.147     albertel 1099: <input type="hidden" name="showmode" value="Edit" />
1.107     www      1100: <input type="submit" name="attemptclean" 
                   1101:        value="Save and then attempt to clean HTML" />
                   1102: <input type="submit" name="savethisfile" value="Save this" />
1.147     albertel 1103: <input type="submit" name="showmode" value="View" />
1.78      www      1104: </form>
                   1105: ENDFOOTER
1.147     albertel 1106: #      $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
1.78      www      1107:       $result=~s/(\<\/body\>)/$editfooter/is;
                   1108:       return $result;
                   1109: }
                   1110: 
1.152     albertel 1111: sub get_target {
                   1112:   my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
                   1113:   if ( $ENV{'request.state'} eq 'published') {
                   1114:     if ( defined($ENV{'form.grade_target'})
                   1115: 	 && ($viewgrades == 'F' )) {
                   1116:       return ($ENV{'form.grade_target'});
1.153     albertel 1117:     } elsif (defined($ENV{'form.grade_target'})) {
                   1118:       if (($ENV{'form.grade_target'} eq 'web') ||
                   1119: 	  ($ENV{'form.grade_target'} eq 'tex') ) {
                   1120: 	return $ENV{'form.grade_target'}
                   1121:       } else {
                   1122: 	return 'web';
                   1123:       }
1.152     albertel 1124:     } else {
                   1125:       return 'web';
                   1126:     }
                   1127:   } elsif ($ENV{'request.state'} eq 'construct') {
                   1128:     if ( defined($ENV{'form.grade_target'})) {
                   1129:       return ($ENV{'form.grade_target'});
                   1130:     } else {
                   1131:       return 'web';
                   1132:     }
                   1133:   } else {
                   1134:     return 'web';
                   1135:   }
                   1136: }
                   1137: 
1.24      sakharuk 1138: sub handler {
                   1139:   my $request=shift;
1.68      www      1140: 
1.152     albertel 1141:   my $target=&get_target();
1.68      www      1142: 
1.65      albertel 1143:   $Apache::lonxml::debug=0;
1.68      www      1144: 
1.25      sakharuk 1145:   if ($ENV{'browser.mathml'}) {
1.27      albertel 1146:     $request->content_type('text/xml');
                   1147:   } else {
                   1148:     $request->content_type('text/html');
1.25      sakharuk 1149:   }
1.141     albertel 1150:   &Apache::loncommon::no_cache($request);
1.27      albertel 1151:   $request->send_http_header;
1.141     albertel 1152: 
1.45      www      1153:   return OK if $request->header_only;
1.27      albertel 1154: 
1.79      www      1155: 
                   1156:   my $file=&Apache::lonnet::filelocation("",$request->uri);
1.78      www      1157: #
                   1158: # Edit action? Save file.
                   1159: #
                   1160:   unless ($ENV{'request.state'} eq 'published') {
1.107     www      1161:       if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
1.79      www      1162: 	  &storefile($file,$ENV{'form.filecont'});
1.78      www      1163:       }
                   1164:   }
1.24      sakharuk 1165:   my %mystyle;
1.147     albertel 1166:   my $result = '';
1.50      albertel 1167:   my $filecontents=&Apache::lonnet::getfile($file);
                   1168:   if ($filecontents == -1) {
1.78      www      1169:     $result=(<<ENDNOTFOUND);
                   1170: <html>
                   1171: <head>
                   1172: <title>File not found</title>
                   1173: </head>
                   1174: <body bgcolor="#FFFFFF">
                   1175: <b>File not found: $file</b>
                   1176: </body>
                   1177: </html>
                   1178: ENDNOTFOUND
1.50      albertel 1179:     $filecontents='';
1.151     albertel 1180:     if ($ENV{'request.state'} ne 'published') {
                   1181:       $filecontents=&createnewhtml();
                   1182:       $ENV{'form.showmode'}='Edit'; #force edit mode
                   1183:     }
1.50      albertel 1184:   } else {
1.147     albertel 1185:     unless ($ENV{'request.state'} eq 'published') {
                   1186:       if ($ENV{'form.attemptclean'}) {
                   1187: 	$filecontents=&htmlclean($filecontents,1);
1.107     www      1188:       }
1.147     albertel 1189:     }
                   1190:     if ($ENV{'form.showmode'} ne 'Edit') {
                   1191:       $result = &Apache::lonxml::xmlparse($target,$filecontents,'',%mystyle);
                   1192:     }
1.78      www      1193:   }
                   1194: 
                   1195: #
                   1196: # Edit action? Insert editing commands
                   1197: #
                   1198:   unless ($ENV{'request.state'} eq 'published') {
1.147     albertel 1199:     if ($ENV{'form.showmode'} eq 'Edit') {
                   1200:       $result='<html><body bgcolor="#FFFFFF"></body></html>';
1.78      www      1201:       $result=&inserteditinfo($result,$filecontents);
1.147     albertel 1202:     }
1.66      www      1203:   }
1.147     albertel 1204: 
1.126     www      1205:   writeallows($request->uri);
1.50      albertel 1206: 
1.67      www      1207:   $request->print($result);
1.64      albertel 1208: 
1.45      www      1209:   return OK;
1.24      sakharuk 1210: }
1.147     albertel 1211: 
1.22      albertel 1212: sub debug {
                   1213:   if ($Apache::lonxml::debug eq 1) {
1.146     albertel 1214:     $|=1;
                   1215:     print("DEBUG:".join('<br />',@_)."<br />\n");
1.22      albertel 1216:   }
                   1217: }
1.49      albertel 1218: 
1.22      albertel 1219: sub error {
1.74      albertel 1220:   if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
1.146     albertel 1221:     print "<b>ERROR:</b>".join('<br />',@_)."<br />\n";
1.52      albertel 1222:   } else {
                   1223:     print "<b>An Error occured while processing this resource. The instructor has been notified.</b> <br />";
                   1224:     #notify author
1.146     albertel 1225:     &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
1.52      albertel 1226:     #notify course
                   1227:     if ( $ENV{'request.course.id'} ) {
                   1228:       my $users=$ENV{'course.'.$ENV{'request.course.id'}.'.comment.email'};
1.143     www      1229:       my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
1.52      albertel 1230:       foreach my $user (split /\,/, $users) {
                   1231: 	($user,my $domain) = split /:/, $user;
1.143     www      1232: 	&Apache::lonmsg::user_normal_msg($user,$domain,
1.146     albertel 1233:         "Error [$declutter]",join('<br />',@_));
1.52      albertel 1234:       }
                   1235:     }
1.74      albertel 1236: 
1.52      albertel 1237:     #FIXME probably shouldn't have me get everything forever.
1.146     albertel 1238:     &Apache::lonmsg::user_normal_msg('albertel','msu',"Error in $ENV{'request.filename'}",join('<br />',@_));
1.74      albertel 1239:     #&Apache::lonmsg::user_normal_msg('albertel','103',"Error in $ENV{'request.filename'}",$_[0]);
1.52      albertel 1240:   }
1.22      albertel 1241: }
1.49      albertel 1242: 
1.22      albertel 1243: sub warning {
1.73      harris41 1244:   if ($ENV{'request.state'} eq 'construct') {
1.146     albertel 1245:     print "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n";
1.73      harris41 1246:   }
1.83      albertel 1247: }
                   1248: 
                   1249: sub get_param {
                   1250:   my ($param,$parstack,$safeeval,$context) = @_;
                   1251:   if ( ! $context ) { $context = -1; }
                   1252:   my $args ='';
                   1253:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1.157     albertel 1254:   if ( ! $args ) { return undef; }
1.131     albertel 1255:   if ( $args =~ /my \$$param=\"/ ) {
                   1256:     return &Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
                   1257:   } else {
                   1258:     return undef;
                   1259:   }
1.22      albertel 1260: }
                   1261: 
1.132     albertel 1262: sub get_param_var {
                   1263:   my ($param,$parstack,$safeeval,$context) = @_;
                   1264:   if ( ! $context ) { $context = -1; }
                   1265:   my $args ='';
                   1266:   if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
                   1267:   if ( $args !~ /my \$$param=\"/ ) { return undef; }
                   1268:   my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
                   1269:   if ($value =~ /^[\$\@\%]/) {
                   1270:     return &Apache::run::run("return $value",$safeeval,1);
                   1271:   } else {
                   1272:     return $value;
                   1273:   }
                   1274: }
                   1275: 
1.74      albertel 1276: sub register_insert {
1.75      albertel 1277:   my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
1.74      albertel 1278:   my $i;
1.76      albertel 1279:   my $tagnum=0;
1.74      albertel 1280:   my @order;
                   1281:   for ($i=0;$i < $#data; $i++) {
                   1282:     my $line = $data[$i];
                   1283:     if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
                   1284:     if ( $line =~ /TABLE/ ) { last; }
1.92      albertel 1285:     my ($tag,$descrip,$color,$function,$show) = split(/,/, $line);
1.135     albertel 1286:     if ($tag) {
                   1287:       $insertlist{"$tagnum.tag"} = $tag;
                   1288:       $insertlist{"$tagnum.description"} = $descrip;
                   1289:       $insertlist{"$tagnum.color"} = $color;
                   1290:       $insertlist{"$tagnum.function"} = $function;
                   1291:       if (!defined($show)) { $show='yes'; }
                   1292:       $insertlist{"$tagnum.show"}= $show;
                   1293:       $insertlist{"$tag.num"}=$tagnum;
                   1294:       $tagnum++;
                   1295:     }
1.74      albertel 1296:   }
1.76      albertel 1297:   $i++; #skipping TABLE line
                   1298:   $tagnum = 0;
1.74      albertel 1299:   for (;$i < $#data;$i++) {
                   1300:     my $line = $data[$i];
1.76      albertel 1301:     my ($mnemonic,@which) = split(/ +/,$line);
                   1302:     my $tag = $insertlist{"$tagnum.tag"};
1.144     matthew  1303:     for (my $j=0;$j <=$#which;$j++) {
1.74      albertel 1304:       if ( $which[$j] eq 'Y' ) {
1.76      albertel 1305: 	if ($insertlist{"$j.show"} ne 'no') {
                   1306: 	  push(@{ $insertlist{"$tag.which"} },$j);
                   1307: 	}
1.74      albertel 1308:       }
                   1309:     }
1.76      albertel 1310:     $tagnum++;
1.74      albertel 1311:   }
                   1312: }
1.98      albertel 1313: 
                   1314: sub description {
                   1315:   my ($token)=@_;
1.138     albertel 1316:   my $tagnum;
                   1317:   my $tag=$token->[1];
                   1318:   foreach my $namespace (reverse @Apache::lonxml::namespace) {
                   1319:     my $testtag=$namespace.'::'.$tag;
                   1320:     $tagnum=$insertlist{"$testtag.num"};
                   1321:     if (defined($tagnum)) { last; }
                   1322:   }
                   1323:   if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
                   1324:   return $insertlist{$tagnum.'.description'};
1.98      albertel 1325: }
1.123     albertel 1326: 
                   1327: # ----------------------------------------------------------------- whichuser
                   1328: # returns a list of $symb, $courseid, $domain, $name that is correct for
                   1329: # calls to lonnet functions for this setup.
                   1330: # - looks for form.grade_ parameters
                   1331: sub whichuser {
1.134     albertel 1332:   my ($symb,$courseid,$domain,$name);
1.123     albertel 1333:   if (defined($ENV{'form.grade_symb'})) {
                   1334:     my $tmp_courseid=$ENV{'form.grade_courseid'};
                   1335:     my $allowed=&Apache::lonnet::allowed('mgr',$tmp_courseid);
                   1336:     if ($allowed) {
                   1337:       $symb=$ENV{'form.grade_symb'};
                   1338:       $courseid=$ENV{'form.grade_courseid'};
                   1339:       $domain=$ENV{'form.grade_domain'};
                   1340:       $name=$ENV{'form.grade_username'};
                   1341:     }
1.134     albertel 1342:   } else {
                   1343:     $symb=&Apache::lonnet::symbread();
                   1344:     $courseid=$ENV{'request.course.id'};
                   1345:     $domain=$ENV{'user.domain'};
                   1346:     $name=$ENV{'user.name'};
1.123     albertel 1347:   }
                   1348:   return ($symb,$courseid,$domain,$name);
                   1349: }
                   1350: 
1.1       sakharuk 1351: 1;
                   1352: __END__
1.68      www      1353: 
                   1354: 

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