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