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