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