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