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