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