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