1: # The LearningOnline Network with CAPA
2: # XML Parser Module
3: #
4: # $Id: lonxml.pm,v 1.527 2011/12/09 21:21:43 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: =pod
41:
42: =head1 NAME
43:
44: Apache::lonxml
45:
46: =head1 SYNOPSIS
47:
48: XML Parsing Module
49:
50: This is part of the LearningOnline Network with CAPA project
51: described at http://www.lon-capa.org.
52:
53:
54: =head1 SUBROUTINES
55:
56: =cut
57:
58:
59:
60: package Apache::lonxml;
61: use vars
62: qw(@pwd @outputstack $redirection $import @extlinks $metamode $evaluate %insertlist @namespace $errorcount $warningcount);
63: use strict;
64: use LONCAPA;
65: use HTML::LCParser();
66: use HTML::TreeBuilder();
67: use HTML::Entities();
68: use Safe();
69: use Safe::Hole();
70: use Math::Cephes();
71: use Math::Random();
72: use Opcode();
73: use POSIX qw(strftime);
74: use Time::HiRes qw( gettimeofday tv_interval );
75: use Symbol();
76:
77: sub register {
78: my ($space,@taglist) = @_;
79: foreach my $temptag (@taglist) {
80: push(@{ $Apache::lonxml::alltags{$temptag} },$space);
81: }
82: }
83:
84: sub deregister {
85: my ($space,@taglist) = @_;
86: foreach my $temptag (@taglist) {
87: my $tempspace = $Apache::lonxml::alltags{$temptag}[-1];
88: if ($tempspace eq $space) {
89: pop(@{ $Apache::lonxml::alltags{$temptag} });
90: }
91: }
92: #&printalltags();
93: }
94:
95: use Apache::Constants qw(:common);
96: use Apache::lontexconvert();
97: use Apache::style();
98: use Apache::run();
99: use Apache::londefdef();
100: use Apache::scripttag();
101: use Apache::languagetags();
102: use Apache::edit();
103: use Apache::inputtags();
104: use Apache::outputtags();
105: use Apache::lonnet;
106: use Apache::File();
107: use Apache::loncommon();
108: use Apache::lonfeedback();
109: use Apache::lonmsg();
110: use Apache::loncacc();
111: use Apache::lonmaxima();
112: use Apache::lonr();
113: use Apache::lonlocal;
114: use Apache::lonhtmlcommon();
115: use Apache::functionplotresponse();
116:
117: #==================================== Main subroutine: xmlparse
118:
119: #debugging control, to turn on debugging modify the correct handler
120:
121: $Apache::lonxml::debug=0;
122:
123: # keeps count of the number of warnings and errors generated in a parse
124: $warningcount=0;
125: $errorcount=0;
126:
127: #path to the directory containing the file currently being processed
128: @pwd=();
129:
130: #these two are used for capturing a subset of the output for later processing,
131: #don't touch them directly use &startredirection and &endredirection
132: @outputstack = ();
133: $redirection = 0;
134:
135: #controls wheter the <import> tag actually does
136: $import = 1;
137: @extlinks=();
138:
139: # meta mode is a bit weird only some output is to be turned off
140: #<output> tag turns metamode off (defined in londefdef.pm)
141: $metamode = 0;
142:
143: # turns on and of run::evaluate actually derefencing var refs
144: $evaluate = 1;
145:
146: # data structure for eidt mode, determines what tags can go into what other tags
147: %insertlist=();
148:
149: # stores the list of active tag namespaces
150: @namespace=();
151:
152: # stores all Scrit Vars displays for later showing
153: my @script_var_displays=();
154:
155: # a pointer the the Apache request object
156: $Apache::lonxml::request='';
157:
158: # a problem number counter, and check on ether it is used
159: $Apache::lonxml::counter=1;
160: $Apache::lonxml::counter_changed=0;
161:
162: # Part counter hash. In analysis mode, the
163: # problems can use this to record which parts increment the counter
164: # by how much. The counter subs will maintain this hash via
165: # their optional part parameters. Note that the assumption is that
166: # analysis is done in one request and therefore it is not necessary to
167: # save this information request-to-request.
168:
169:
170: %Apache::lonxml::counters_per_part = ();
171:
172: #internal check on whether to look at style defs
173: $Apache::lonxml::usestyle=1;
174:
175: #locations used to store the parameter string for style substitutions
176: $Apache::lonxml::style_values='';
177: $Apache::lonxml::style_end_values='';
178:
179: #array of ssi calls that need to occur after we are done parsing
180: @Apache::lonxml::ssi_info=();
181:
182: #should we do the postag variable interpolation
183: $Apache::lonxml::post_evaluate=1;
184:
185: #a header message to emit in the case of any generated warning or errors
186: $Apache::lonxml::warnings_error_header='';
187:
188: # Control whether or not LaTeX symbols should be substituted for their
189: # \ style equivalents...this may be turned off e.g. in an verbatim
190: # environment.
191:
192: $Apache::lonxml::substitute_LaTeX_symbols = 1; # Starts out on.
193:
194: sub enable_LaTeX_substitutions {
195: $Apache::lonxml::substitute_LaTeX_symbols = 1;
196: }
197: sub disable_LaTeX_substitutions {
198: $Apache::lonxml::substitute_LaTeX_symbols = 0;
199: }
200:
201: sub xmlend {
202: my ($target,$parser)=@_;
203: my $mode='xml';
204: my $status='OPEN';
205: if ($Apache::lonhomework::parsing_a_problem ||
206: $Apache::lonhomework::parsing_a_task ) {
207: $mode='problem';
208: $status=$Apache::inputtags::status[-1];
209: }
210: my $discussion;
211: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
212: ['LONCAPA_INTERNAL_no_discussion']);
213: if (! exists($env{'form.LONCAPA_INTERNAL_no_discussion'}) ||
214: $env{'form.LONCAPA_INTERNAL_no_discussion'} ne 'true') {
215: $discussion=&Apache::lonfeedback::list_discussion($mode,$status);
216: }
217: if ($target eq 'tex') {
218: $discussion.='<tex>\keephidden{ENDOFPROBLEM}\vskip 0.5mm\noindent\makebox[\textwidth/$number_of_columns][b]{\hrulefill}\end{document}</tex>';
219: &Apache::lonxml::newparser($parser,\$discussion,'');
220: return '';
221: }
222:
223: return $discussion;
224: }
225:
226: sub printalltags {
227: my $temp;
228: foreach $temp (sort keys %Apache::lonxml::alltags) {
229: &Apache::lonxml::debug("$temp -- ".
230: join(',',@{ $Apache::lonxml::alltags{$temp} }));
231: }
232: }
233:
234: sub xmlparse {
235: my ($request,$target,$content_file_string,$safeinit,%style_for_target) = @_;
236:
237: &setup_globals($request,$target);
238: &Apache::inputtags::initialize_inputtags();
239: &Apache::bridgetask::initialize_bridgetask();
240: &Apache::outputtags::initialize_outputtags();
241: &Apache::edit::initialize_edit();
242: &Apache::londefdef::initialize_londefdef();
243:
244: #
245: # do we have a course style file?
246: #
247:
248: if ($env{'request.course.id'} && $env{'request.state'} ne 'construct') {
249: my $bodytext=
250: $env{'course.'.$env{'request.course.id'}.'.default_xml_style'};
251: if ($bodytext) {
252: foreach my $file (split(',',$bodytext)) {
253: my $location=&Apache::lonnet::filelocation('',$file);
254: my $styletext=&Apache::lonnet::getfile($location);
255: if ($styletext ne '-1') {
256: %style_for_target = (%style_for_target,
257: &Apache::style::styleparser($target,$styletext));
258: }
259: }
260: }
261: } elsif ($env{'construct.style'}
262: && ($env{'request.state'} eq 'construct')) {
263: my $location=&Apache::lonnet::filelocation('',$env{'construct.style'});
264: my $styletext=&Apache::lonnet::getfile($location);
265: if ($styletext ne '-1') {
266: %style_for_target = (%style_for_target,
267: &Apache::style::styleparser($target,$styletext));
268: }
269: }
270: #&printalltags();
271: my @pars = ();
272: my $pwd=$env{'request.filename'};
273: $pwd =~ s:/[^/]*$::;
274: &newparser(\@pars,\$content_file_string,$pwd);
275:
276: my $safeeval = new Safe;
277: my $safehole = new Safe::Hole;
278: &init_safespace($target,$safeeval,$safehole,$safeinit);
279: #-------------------- Redefinition of the target in the case of compound target
280:
281: ($target, my @tenta) = split('&&',$target);
282:
283: my @stack = ();
284: my @parstack = ();
285: &initdepth();
286: &init_alarm();
287: my $finaloutput = &inner_xmlparse($target,\@stack,\@parstack,\@pars,
288: $safeeval,\%style_for_target,1);
289:
290: if (@stack) {
291: &warning(&mt('At end of file some tags were still left unclosed:').
292: ' <tt><'.join('></tt>, <tt><',reverse(@stack)).
293: '></tt>');
294: }
295: if ($env{'request.uri'}) {
296: &writeallows($env{'request.uri'});
297: }
298: &do_registered_ssi();
299: if ($Apache::lonxml::counter_changed) { &store_counter() }
300:
301: &clean_safespace($safeeval);
302:
303: if (@script_var_displays) {
304: my $scriptoutput = join('',@script_var_displays);
305: $finaloutput=~s{(</body>\s*</html>)\s*$}{$scriptoutput$1}s;
306: undef(@script_var_displays);
307: }
308: &init_state();
309: if ($env{'form.return_only_error_and_warning_counts'}) {
310: if ($env{'request.filename'}=~/\.(html|htm|xml)$/i) {
311: my $error=&verify_html($content_file_string);
312: if ($error) { $errorcount++; }
313: }
314: return "$errorcount:$warningcount";
315: }
316: return $finaloutput;
317: }
318:
319: sub latex_special_symbols {
320: my ($string,$where)=@_;
321: #
322: # If e.g. in verbatim mode, then don't substitute.
323: # but return original string.
324: #
325: if (!($Apache::lonxml::substitute_LaTeX_symbols)) {
326: return $string;
327: }
328: if ($where eq 'header') {
329: $string =~ s/\\/\$\\backslash\$/g; # \ -> $\backslash$ per LaTex line by line pg 10.
330: $string =~ s/(\$|%|\{|\})/\\$1/g;
331: $string=&Apache::lonprintout::character_chart($string);
332: # any & or # leftover should be safe to just escape
333: $string=~s/([^\\])\&/$1\\\&/g;
334: $string=~s/([^\\])\#/$1\\\#/g;
335: $string =~ s/_/\\_/g; # _ -> \_
336: $string =~ s/\^/\\\^{}/g; # ^ -> \^{}
337: } else {
338: $string=~s/\\/\\ensuremath{\\backslash}/g;
339: $string=~s/\\\%|\%/\\\%/g;
340: $string=~s/\\{|{/\\{/g;
341: $string=~s/\\}|}/\\}/g;
342: $string=~s/\\ensuremath\\{\\backslash\\}/\\ensuremath{\\backslash}/g;
343: $string=~s/\\\$|\$/\\\$/g;
344: $string=~s/\\\_|\_/\\\_/g;
345: $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
346: $string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
347: $string=&Apache::lonprintout::character_chart($string);
348: # any & or # leftover should be safe to just escape
349: $string=~s/\\\&|\&/\\\&/g;
350: $string=~s/\\\#|\#/\\\#/g;
351: $string=~s/\|/\$\\mid\$/g;
352: #single { or } How to escape?
353: }
354: return $string;
355: }
356:
357: sub inner_xmlparse {
358: my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target,$start)=@_;
359: my $finaloutput = '';
360: my $result;
361: my $token;
362: my $dontpop=0;
363: my $startredirection = $Apache::lonxml::redirection;
364: while ( $#$pars > -1 ) {
365: while ($token = $$pars['-1']->get_token) {
366: if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
367: if ($metamode<1) {
368: my $text=$token->[1];
369: if ($token->[0] eq 'C' && $target eq 'tex') {
370: $text = '';
371: # $text = '%'.$text."\n";
372: }
373: $result.=$text;
374: }
375: } elsif (($token->[0] eq 'D')) {
376: if ($metamode<1 && $target eq 'web') {
377: my $text=$token->[1];
378: $result.=$text;
379: }
380: } elsif ($token->[0] eq 'PI') {
381: if ($metamode<1 && $target eq 'web') {
382: $result=$token->[2];
383: }
384: } elsif ($token->[0] eq 'S') {
385: # add tag to stack
386: push (@$stack,$token->[1]);
387: # add parameters list to another stack
388: push (@$parstack,&parstring($token));
389: &increasedepth($token);
390: if ($Apache::lonxml::usestyle &&
391: exists($$style_for_target{$token->[1]})) {
392: $Apache::lonxml::usestyle=0;
393: my $string=$$style_for_target{$token->[1]}.
394: '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
395: &Apache::lonxml::newparser($pars,\$string);
396: $Apache::lonxml::style_values=$$parstack[-1];
397: $Apache::lonxml::style_end_values=$$parstack[-1];
398: } else {
399: $result = &callsub("start_$token->[1]", $target, $token, $stack,
400: $parstack, $pars, $safeeval, $style_for_target);
401: }
402: } elsif ($token->[0] eq 'E') {
403: if ($Apache::lonxml::usestyle &&
404: exists($$style_for_target{'/'."$token->[1]"})) {
405: $Apache::lonxml::usestyle=0;
406: my $string=$$style_for_target{'/'.$token->[1]}.
407: '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
408: &Apache::lonxml::newparser($pars,\$string);
409: $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
410: $Apache::lonxml::style_end_values='';
411: $dontpop=1;
412: } else {
413: #clear out any tags that didn't end
414: while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
415: my $lasttag=$$stack[-1];
416: if ($token->[1] =~ /^\Q$lasttag\E$/i) {
417: &Apache::lonxml::warning(&mt('Using tag [_1] on line [_2] as end tag to [_3]','</'.$token->[1].'>','.$token->[3].','<'.$$stack[-1].'>'));
418: last;
419: } else {
420: &Apache::lonxml::warning(&mt('Found tag [_1] on line [_2] when looking for [_3] in file.','</'.$token->[1].'>',$token->[3],'</'.$$stack[-1].'>'));
421: &end_tag($stack,$parstack,$token);
422: }
423: }
424: $result = &callsub("end_$token->[1]", $target, $token, $stack,
425: $parstack, $pars,$safeeval, $style_for_target);
426: }
427: } else {
428: &Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
429: }
430: #evaluate variable refs in result
431: if ($Apache::lonxml::post_evaluate &&$result ne "") {
432: my $extras;
433: if (!$Apache::lonxml::usestyle) {
434: $extras=$Apache::lonxml::style_values;
435: }
436: if ( $#$parstack > -1 ) {
437: $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
438: } else {
439: $result= &Apache::run::evaluate($result,$safeeval,$extras);
440: }
441: }
442: $Apache::lonxml::post_evaluate=1;
443:
444: if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
445: #Style file definitions should be correct
446: if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
447: $result=&latex_special_symbols($result);
448: }
449: }
450:
451: if ($Apache::lonxml::redirection) {
452: $Apache::lonxml::outputstack['-1'] .= $result;
453: } else {
454: $finaloutput.=$result;
455: }
456: $result = '';
457:
458: if ($token->[0] eq 'E' && !$dontpop) {
459: &end_tag($stack,$parstack,$token);
460: }
461: $dontpop=0;
462: }
463: if ($#$pars > -1) {
464: pop @$pars;
465: pop @Apache::lonxml::pwd;
466: }
467: }
468:
469: # if ($target eq 'meta') {
470: # $finaloutput.=&endredirection;
471: # }
472:
473: if ( $start && $target eq 'grade') { &endredirection(); }
474: if ( $Apache::lonxml::redirection > $startredirection) {
475: while ($Apache::lonxml::redirection > $startredirection) {
476: $finaloutput .= &endredirection();
477: }
478: }
479: if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
480: $finaloutput=&afterburn($finaloutput);
481: }
482: if ($target eq 'modified') {
483: # if modfied, handle startpart and endpart
484: $finaloutput=~s/\<startpartmarker[^\>]*\>(.*)\<endpartmarker[^\>]*\>/<part>$1<\/part>/gs;
485: }
486: return $finaloutput;
487: }
488:
489: ##
490: ## Looks to see if there is a subroutine defined for this tag. If so, call it,
491: ## otherwise do not call it as we do not know what it is.
492: ##
493: sub callsub {
494: my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
495: my $currentstring='';
496: my $nodefault;
497: {
498: my $sub1;
499: no strict 'refs';
500: my $tag=$token->[1];
501: # get utterly rid of extended html tags
502: if ($tag=~/^x\-/i) { return ''; }
503: my $space=$Apache::lonxml::alltags{$tag}[-1];
504: if (!$space) {
505: $tag=~tr/A-Z/a-z/;
506: $sub=~tr/A-Z/a-z/;
507: $space=$Apache::lonxml::alltags{$tag}[-1]
508: }
509:
510: my $deleted=0;
511: if (($token->[0] eq 'S') && ($target eq 'modified')) {
512: $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
513: $parstack,$parser,$safeeval,
514: $style);
515: }
516: if (!$deleted) {
517: if ($space) {
518: #&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
519: $sub1="$space\:\:$sub";
520: ($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
521: $parstack,$parser,$safeeval,
522: $style);
523: } else {
524: if ($target eq 'tex') {
525: # throw away tag name
526: return '';
527: }
528: #&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
529: if ($metamode <1) {
530: if (defined($token->[4]) && ($metamode < 1)) {
531: $currentstring = $token->[4];
532: } else {
533: $currentstring = $token->[2];
534: }
535: }
536: }
537: # &Apache::lonxml::debug("nodefalt:$nodefault:");
538: if ($currentstring eq '' && $nodefault eq '') {
539: if ($target eq 'edit') {
540: #&Apache::lonxml::debug("doing default edit for $token->[1]");
541: if ($token->[0] eq 'S') {
542: $currentstring = &Apache::edit::tag_start($target,$token);
543: } elsif ($token->[0] eq 'E') {
544: $currentstring = &Apache::edit::tag_end($target,$token);
545: }
546: }
547: }
548: if ($target eq 'modified' && $nodefault eq '') {
549: if ($currentstring eq '') {
550: if ($token->[0] eq 'S') {
551: $currentstring = $token->[4];
552: } elsif ($token->[0] eq 'E') {
553: $currentstring = $token->[2];
554: } else {
555: $currentstring = $token->[2];
556: }
557: }
558: if ($token->[0] eq 'S') {
559: $currentstring.=&Apache::edit::handle_insert();
560: } elsif ($token->[0] eq 'E') {
561: $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
562: }
563: }
564: }
565: use strict 'refs';
566: }
567: return $currentstring;
568: }
569:
570: {
571: my %state;
572:
573: sub init_state {
574: undef(%state);
575: }
576:
577: sub set_state {
578: my ($key,$value) = @_;
579: $state{$key} = $value;
580: return $value;
581: }
582: sub get_state {
583: my ($key) = @_;
584: return $state{$key};
585: }
586: }
587:
588: sub setup_globals {
589: my ($request,$target)=@_;
590: $Apache::lonxml::request=$request;
591: $errorcount=0;
592: $warningcount=0;
593: $Apache::lonxml::internal_error=0;
594: $Apache::lonxml::default_homework_loaded=0;
595: $Apache::lonxml::usestyle=1;
596: &init_counter();
597: &clear_bubble_lines_for_part();
598: &init_state();
599: &set_state('target',$target);
600: @Apache::lonxml::pwd=();
601: @Apache::lonxml::extlinks=();
602: @script_var_displays=();
603: @Apache::lonxml::ssi_info=();
604: $Apache::lonxml::post_evaluate=1;
605: $Apache::lonxml::warnings_error_header='';
606: $Apache::lonxml::substitute_LaTeX_symbols = 1;
607: if ($target eq 'meta') {
608: $Apache::lonxml::redirection = 0;
609: $Apache::lonxml::metamode = 1;
610: $Apache::lonxml::evaluate = 1;
611: $Apache::lonxml::import = 0;
612: } elsif ($target eq 'answer') {
613: $Apache::lonxml::redirection = 0;
614: $Apache::lonxml::metamode = 1;
615: $Apache::lonxml::evaluate = 1;
616: $Apache::lonxml::import = 1;
617: } elsif ($target eq 'grade') {
618: &startredirection(); #ended in inner_xmlparse on exit
619: $Apache::lonxml::metamode = 0;
620: $Apache::lonxml::evaluate = 1;
621: $Apache::lonxml::import = 1;
622: } elsif ($target eq 'modified') {
623: $Apache::lonxml::redirection = 0;
624: $Apache::lonxml::metamode = 0;
625: $Apache::lonxml::evaluate = 0;
626: $Apache::lonxml::import = 0;
627: } elsif ($target eq 'edit') {
628: $Apache::lonxml::redirection = 0;
629: $Apache::lonxml::metamode = 0;
630: $Apache::lonxml::evaluate = 0;
631: $Apache::lonxml::import = 0;
632: } elsif ($target eq 'analyze') {
633: $Apache::lonxml::redirection = 0;
634: $Apache::lonxml::metamode = 0;
635: $Apache::lonxml::evaluate = 1;
636: $Apache::lonxml::import = 1;
637: } else {
638: $Apache::lonxml::redirection = 0;
639: $Apache::lonxml::metamode = 0;
640: $Apache::lonxml::evaluate = 1;
641: $Apache::lonxml::import = 1;
642: }
643: }
644:
645: sub init_safespace {
646: my ($target,$safeeval,$safehole,$safeinit) = @_;
647: $safeeval->reval('use Math::Complex;');
648: $safeeval->reval('use LaTeX::Table;');
649: $safeeval->deny_only(':dangerous');
650: $safeeval->permit_only(":default");
651: $safeeval->permit("entereval");
652: $safeeval->permit(":base_math");
653: $safeeval->permit("sort");
654: $safeeval->permit("time");
655: $safeeval->permit("caller");
656: $safeeval->deny("rand");
657: $safeeval->deny("srand");
658: $safeeval->deny(":base_io");
659: $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
660: $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
661: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
662: $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
663: '&chem_standard_order');
664: $safehole->wrap(\&Apache::response::check_status,$safeeval,'&check_status');
665: $safehole->wrap(\&Apache::response::implicit_multiplication,$safeeval,'&implicit_multiplication');
666:
667: $safehole->wrap(\&Apache::lonmaxima::maxima_eval,$safeeval,'&maxima_eval');
668: $safehole->wrap(\&Apache::lonmaxima::maxima_check,$safeeval,'&maxima_check');
669: $safehole->wrap(\&Apache::lonmaxima::maxima_cas_formula_fix,$safeeval,
670: '&maxima_cas_formula_fix');
671:
672: $safehole->wrap(\&Apache::lonr::r_eval,$safeeval,'&r_eval');
673: $safehole->wrap(\&Apache::lonr::Rentry,$safeeval,'&Rentry');
674: $safehole->wrap(\&Apache::lonr::Rarray,$safeeval,'&Rarray');
675: $safehole->wrap(\&Apache::lonr::r_check,$safeeval,'&r_check');
676: $safehole->wrap(\&Apache::lonr::r_cas_formula_fix,$safeeval,
677: '&r_cas_formula_fix');
678:
679: $safehole->wrap(\&Apache::caparesponse::capa_formula_fix,$safeeval,
680: '&capa_formula_fix');
681:
682: $safehole->wrap(\&Apache::lonlocal::locallocaltime,$safeeval,
683: '&locallocaltime');
684:
685: $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
686: $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
687: $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
688: $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
689: $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
690: $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
691: $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
692: $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
693: $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
694: $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
695: $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
696: $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
697: $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
698: $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
699: $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
700: $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
701: $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
702: $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
703: $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
704:
705: $safehole->wrap(\&Math::Cephes::bdtr ,$safeeval,'&bdtr' );
706: $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
707: $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
708: $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
709: $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
710: $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
711: $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
712: $safehole->wrap(\&Math::Cephes::fdtr ,$safeeval,'&fdtr' );
713: $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
714: $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
715: $safehole->wrap(\&Math::Cephes::gdtr ,$safeeval,'&gdtr' );
716: $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
717: $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
718: $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
719: $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
720: $safehole->wrap(\&Math::Cephes::ndtr ,$safeeval,'&ndtr' );
721: $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
722: $safehole->wrap(\&Math::Cephes::pdtr ,$safeeval,'&pdtr' );
723: $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
724: $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
725: $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
726: $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
727:
728: $safehole->wrap(\&Math::Cephes::Matrix::mat,$safeeval,'&mat');
729: $safehole->wrap(\&Math::Cephes::Matrix::new,$safeeval,
730: '&Math::Cephes::Matrix::new');
731: $safehole->wrap(\&Math::Cephes::Matrix::coef,$safeeval,
732: '&Math::Cephes::Matrix::coef');
733: $safehole->wrap(\&Math::Cephes::Matrix::clr,$safeeval,
734: '&Math::Cephes::Matrix::clr');
735: $safehole->wrap(\&Math::Cephes::Matrix::add,$safeeval,
736: '&Math::Cephes::Matrix::add');
737: $safehole->wrap(\&Math::Cephes::Matrix::sub,$safeeval,
738: '&Math::Cephes::Matrix::sub');
739: $safehole->wrap(\&Math::Cephes::Matrix::mul,$safeeval,
740: '&Math::Cephes::Matrix::mul');
741: $safehole->wrap(\&Math::Cephes::Matrix::div,$safeeval,
742: '&Math::Cephes::Matrix::div');
743: $safehole->wrap(\&Math::Cephes::Matrix::inv,$safeeval,
744: '&Math::Cephes::Matrix::inv');
745: $safehole->wrap(\&Math::Cephes::Matrix::transp,$safeeval,
746: '&Math::Cephes::Matrix::transp');
747: $safehole->wrap(\&Math::Cephes::Matrix::simq,$safeeval,
748: '&Math::Cephes::Matrix::simq');
749: $safehole->wrap(\&Math::Cephes::Matrix::mat_to_vec,$safeeval,
750: '&Math::Cephes::Matrix::mat_to_vec');
751: $safehole->wrap(\&Math::Cephes::Matrix::vec_to_mat,$safeeval,
752: '&Math::Cephes::Matrix::vec_to_mat');
753: $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
754: '&Math::Cephes::Matrix::check');
755: $safehole->wrap(\&Math::Cephes::Matrix::check,$safeeval,
756: '&Math::Cephes::Matrix::check');
757:
758: # $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
759: # $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
760: # $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
761: # $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
762: # $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
763: # $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
764:
765: $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
766: $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
767: $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
768: $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
769: $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
770: $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
771: $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
772: $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
773: $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
774: $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
775: $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
776: $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
777: $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
778: $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
779: $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
780: $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
781: $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
782: $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
783: $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
784: $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
785: $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
786: $safehole->wrap(\&Apache::loncommon::languages,$safeeval,'&languages');
787: $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
788: $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
789: $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&LONCAPA_INTERNAL_LOGTHIS');
790: $safehole->wrap(\&Apache::inputtags::finalizeawards,$safeeval,'&LONCAPA_INTERNAL_FINALIZEAWARDS');
791: $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
792: $safehole->wrap(\&Apache::functionplotresponse::fpr_val,$safeeval,'&fpr_val');
793: $safehole->wrap(\&Apache::functionplotresponse::fpr_f,$safeeval,'&fpr_f');
794: $safehole->wrap(\&Apache::functionplotresponse::fpr_dfdx,$safeeval,'&fpr_dfdx');
795: $safehole->wrap(\&Apache::functionplotresponse::fpr_d2fdx2,$safeeval,'&fpr_d2fdx2');
796: $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorcoords,$safeeval,'&fpr_vectorcoords');
797: $safehole->wrap(\&Apache::functionplotresponse::fpr_objectcoords,$safeeval,'&fpr_objectcoords');
798: $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorlength,$safeeval,'&fpr_vectorlength');
799: $safehole->wrap(\&Apache::functionplotresponse::fpr_vectorangle,$safeeval,'&fpr_vectorangle');
800:
801: # use Data::Dumper;
802: # $safehole->wrap(\&Data::Dumper::Dumper,$safeeval,'&LONCAPA_INTERNAL_Dumper');
803: #need to inspect this class of ops
804: # $safeeval->deny(":base_orig");
805: $safeeval->permit("require");
806: $safeinit .= ';$external::target="'.$target.'";';
807: &Apache::run::run($safeinit,$safeeval);
808: &initialize_rndseed($safeeval);
809: }
810:
811: sub clean_safespace {
812: my ($safeeval) = @_;
813: delete_package_recurse($safeeval->{Root});
814: }
815:
816: sub delete_package_recurse {
817: my ($package) = @_;
818: my @subp;
819: {
820: no strict 'refs';
821: while (my ($key,$val) = each(%{*{"$package\::"}})) {
822: if (!defined($val)) { next; }
823: local (*ENTRY) = $val;
824: if (defined *ENTRY{HASH} && $key =~ /::$/ &&
825: $key ne "main::" && $key ne "<none>::")
826: {
827: my ($p) = $package ne "main" ? "$package\::" : "";
828: ($p .= $key) =~ s/::$//;
829: push(@subp,$p);
830: }
831: }
832: }
833: foreach my $p (@subp) {
834: delete_package_recurse($p);
835: }
836: Symbol::delete_package($package);
837: }
838:
839: sub initialize_rndseed {
840: my ($safeeval)=@_;
841: my $rndseed;
842: my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
843: $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
844: my $safeinit = '$external::randomseed="'.$rndseed.'";';
845: &Apache::lonxml::debug("Setting rndseed to $rndseed");
846: &Apache::run::run($safeinit,$safeeval);
847: }
848:
849: sub default_homework_load {
850: my ($safeeval)=@_;
851: &Apache::lonxml::debug('Loading default_homework');
852: my $default=&Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonIncludes'}.
853: '/default_homework.lcpm');
854: if ($default eq -1) {
855: &Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
856: } else {
857: &Apache::run::run($default,$safeeval);
858: $Apache::lonxml::default_homework_loaded=1;
859: }
860: }
861:
862: {
863: my $alarm_depth;
864: sub init_alarm {
865: alarm(0);
866: $alarm_depth=0;
867: }
868:
869: sub start_alarm {
870: if ($alarm_depth<1) {
871: my $old=alarm($Apache::lonnet::perlvar{'lonScriptTimeout'});
872: if ($old) {
873: &Apache::lonxml::error("Cancelled an alarm of $old, this shouldn't occur.");
874: }
875: }
876: $alarm_depth++;
877: }
878:
879: sub end_alarm {
880: $alarm_depth--;
881: if ($alarm_depth<1) { alarm(0); }
882: }
883: }
884: my $metamode_was;
885: sub startredirection {
886: if (!$Apache::lonxml::redirection) {
887: $metamode_was=$Apache::lonxml::metamode;
888: }
889: $Apache::lonxml::metamode=0;
890: $Apache::lonxml::redirection++;
891: push (@Apache::lonxml::outputstack, '');
892: }
893:
894: sub endredirection {
895: if (!$Apache::lonxml::redirection) {
896: &Apache::lonxml::error("Endredirection was called before a startredirection, perhaps you have unbalanced tags. Some debugging information:".join ":",caller);
897: return '';
898: }
899: $Apache::lonxml::redirection--;
900: if (!$Apache::lonxml::redirection) {
901: $Apache::lonxml::metamode=$metamode_was;
902: }
903: pop @Apache::lonxml::outputstack;
904: }
905: sub in_redirection {
906: return ($Apache::lonxml::redirection > 0)
907: }
908:
909: sub end_tag {
910: my ($tagstack,$parstack,$token)=@_;
911: pop(@$tagstack);
912: pop(@$parstack);
913: &decreasedepth($token);
914: }
915:
916: sub initdepth {
917: @Apache::lonxml::depthcounter=();
918: undef($Apache::lonxml::last_depth_count);
919: }
920:
921:
922: my @timers;
923: my $lasttime;
924: # @Apache::lonxml::depthcounter -> count of tags that exist so
925: # far at each level
926: # $Apache::lonxml::last_depth_count -> when ascending, need to
927: # remember the count for the level below the current level (for
928: # example going from 1_2 -> 1 -> 1_3 need to remember the 2 )
929:
930: sub increasedepth {
931: my ($token) = @_;
932: push(@Apache::lonxml::depthcounter,$Apache::lonxml::last_depth_count+1);
933: undef($Apache::lonxml::last_depth_count);
934: my $time;
935: if ($Apache::lonxml::debug eq "1") {
936: push(@timers,[&gettimeofday()]);
937: $time=&tv_interval($lasttime);
938: $lasttime=[&gettimeofday()];
939: }
940: my $spacing=' 'x($#Apache::lonxml::depthcounter);
941: $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
942: # &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time");
943: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
944: }
945:
946: sub decreasedepth {
947: my ($token) = @_;
948: if ( $#Apache::lonxml::depthcounter == -1) {
949: &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
950: }
951: $Apache::lonxml::last_depth_count = pop(@Apache::lonxml::depthcounter);
952:
953: my ($timer,$time);
954: if ($Apache::lonxml::debug eq "1") {
955: $timer=pop(@timers);
956: $time=&tv_interval($lasttime);
957: $lasttime=[&gettimeofday()];
958: }
959: my $spacing=' 'x($#Apache::lonxml::depthcounter);
960: $Apache::lonxml::curdepth = join('_',@Apache::lonxml::depthcounter);
961: # &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $Apache::lonxml::curdepth : $token->[1] : $time : ".&tv_interval($timer));
962: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
963: }
964:
965: sub get_id {
966: my ($parstack,$safeeval)=@_;
967: my $id= &Apache::lonxml::get_param('id',$parstack,$safeeval);
968: if ($env{'request.state'} eq 'construct' && $id =~ /([._]|[^\w\d\s[:punct:]])/) {
969: &error(&mt('ID [_1] contains invalid characters. IDs are only allowed to contain letters, numbers, spaces and -','"<tt>'.$id.'</tt>"'));
970: }
971: if ($id =~ /^\s*$/) { $id = $Apache::lonxml::curdepth; }
972: return $id;
973: }
974:
975: sub get_all_text_unbalanced {
976: #there is a copy of this in lonpublisher.pm
977: my($tag,$pars)= @_;
978: my $token;
979: my $result='';
980: $tag='<'.$tag.'>';
981: while ($token = $$pars[-1]->get_token) {
982: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
983: if ($token->[0] eq 'T' && $token->[2]) {
984: $result.='<![CDATA['.$token->[1].']]>';
985: } else {
986: $result.=$token->[1];
987: }
988: } elsif ($token->[0] eq 'PI') {
989: $result.=$token->[2];
990: } elsif ($token->[0] eq 'S') {
991: $result.=$token->[4];
992: } elsif ($token->[0] eq 'E') {
993: $result.=$token->[2];
994: }
995: if ($result =~ /\Q$tag\E/is) {
996: ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
997: #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
998: #&Apache::lonxml::debug('Result is :'.$1);
999: $redo=$tag.$redo;
1000: &Apache::lonxml::newparser($pars,\$redo);
1001: last;
1002: }
1003: }
1004: return $result
1005:
1006: }
1007:
1008: #########################################################################
1009: # #
1010: # bubble line counter management #
1011: # #
1012: #########################################################################
1013:
1014: =pod
1015:
1016: For bubble grading mode and exam bubble printing mode, the tracking of
1017: the current 'bubble line number' is stored in the %env element
1018: 'form.counter', and is modifed and handled by the following routines.
1019:
1020: The value of it is stored in $Apache:lonxml::counter when live and
1021: stored back to env after done.
1022:
1023: =item &increment_counter($increment, $part_response);
1024:
1025: Increments the internal counter environment variable a specified amount
1026:
1027: Optional Arguments:
1028: $increment - amount to increment by (defaults to 1)
1029: Also 1 if the value is negative or zero.
1030: $part_response - A concatenation of the part and response id
1031: identifying exactly what is being 'answered'.
1032:
1033:
1034: =cut
1035:
1036: sub increment_counter {
1037: my ($increment, $part_response) = @_;
1038: if ($env{'form.grade_noincrement'}) { return; }
1039: if (!defined($increment) || $increment le 0) {
1040: $increment = 1;
1041: }
1042: $Apache::lonxml::counter += $increment;
1043:
1044: # If the caller supplied the response_id parameter,
1045: # Maintain its counter.. creating if necessary.
1046:
1047: if (defined($part_response)) {
1048: if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
1049: $Apache::lonxml::counters_per_part{$part_response} = 0;
1050: }
1051: $Apache::lonxml::counters_per_part{$part_response} += $increment;
1052: my $new_value = $Apache::lonxml::counters_per_part{$part_response};
1053: }
1054:
1055: $Apache::lonxml::counter_changed=1;
1056: }
1057:
1058: =pod
1059:
1060: =item &init_counter($increment);
1061:
1062: Initialize the internal counter environment variable
1063:
1064: =cut
1065:
1066: sub init_counter {
1067: if ($env{'request.state'} eq 'construct') {
1068: $Apache::lonxml::counter=1;
1069: $Apache::lonxml::counter_changed=1;
1070: } elsif (defined($env{'form.counter'})) {
1071: $Apache::lonxml::counter=$env{'form.counter'};
1072: $Apache::lonxml::counter_changed=0;
1073: } else {
1074: $Apache::lonxml::counter=1;
1075: $Apache::lonxml::counter_changed=1;
1076: }
1077: }
1078:
1079: sub store_counter {
1080: &Apache::lonnet::appenv({'form.counter' => $Apache::lonxml::counter});
1081: $Apache::lonxml::counter_changed=0;
1082: return '';
1083: }
1084:
1085: {
1086: my $state;
1087: sub clear_problem_counter {
1088: undef($state);
1089: &Apache::lonnet::delenv('form.counter');
1090: &Apache::lonxml::init_counter();
1091: &Apache::lonxml::store_counter();
1092: }
1093:
1094: sub remember_problem_counter {
1095: &Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1096: $state = $env{'form.counter'};
1097: }
1098:
1099: sub restore_problem_counter {
1100: if (defined($state)) {
1101: &Apache::lonnet::appenv({'form.counter' => $state});
1102: }
1103: }
1104: sub get_problem_counter {
1105: if ($Apache::lonxml::counter_changed) { &store_counter() }
1106: &Apache::lonnet::transfer_profile_to_env(undef,undef,1);
1107: return $env{'form.counter'};
1108: }
1109: }
1110:
1111: =pod
1112:
1113: =item bubble_lines_for_part(part_response)
1114:
1115: Returns the number of lines required to get a response for
1116: $part_response (this is just $Apache::lonxml::counters_per_part{$part_response}
1117:
1118: =cut
1119:
1120: sub bubble_lines_for_part {
1121: my ($part_response) = @_;
1122:
1123: if (!defined($Apache::lonxml::counters_per_part{$part_response})) {
1124: return 0;
1125: } else {
1126: return $Apache::lonxml::counters_per_part{$part_response};
1127: }
1128: }
1129:
1130: =pod
1131:
1132: =item clear_bubble_lines_for_part
1133:
1134: Clears the hash of bubble lines per part. If a caller
1135: needs to analyze several resources this should be called between
1136: resources to reset the hash for each problem being analyzed.
1137:
1138: =cut
1139:
1140: sub clear_bubble_lines_for_part {
1141: undef(%Apache::lonxml::counters_per_part);
1142: }
1143:
1144: =pod
1145:
1146: =item set_bubble_lines(part_response, value)
1147:
1148: If there is a problem part, that for whatever reason
1149: requires bubble lines that are not
1150: the same as the counter increment, it can call this sub during
1151: analysis to set its hash value explicitly.
1152:
1153: =cut
1154:
1155: sub set_bubble_lines {
1156: my ($part_response, $value) = @_;
1157:
1158: $Apache::lonxml::counters_per_part{$part_response} = $value;
1159: }
1160:
1161: =pod
1162:
1163: =item get_bubble_line_hash
1164:
1165: Returns the current bubble line hash. This is assumed to
1166: be small so we return a copy
1167:
1168:
1169: =cut
1170:
1171: sub get_bubble_line_hash {
1172: return %Apache::lonxml::counters_per_part;
1173: }
1174:
1175:
1176: #--------------------------------------------------
1177:
1178: sub get_all_text {
1179: my($tag,$pars,$style)= @_;
1180: my $gotfullstack=1;
1181: if (ref($pars) ne 'ARRAY') {
1182: $gotfullstack=0;
1183: $pars=[$pars];
1184: }
1185: if (ref($style) ne 'HASH') {
1186: $style={};
1187: }
1188: my $depth=0;
1189: my $token;
1190: my $result='';
1191: if ( $tag =~ m:^/: ) {
1192: my $tag=substr($tag,1);
1193: #&Apache::lonxml::debug("have:$tag:");
1194: my $top_empty=0;
1195: while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
1196: while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
1197: #&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
1198: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
1199: if ($token->[2]) {
1200: $result.='<![CDATA['.$token->[1].']]>';
1201: } else {
1202: $result.=$token->[1];
1203: }
1204: } elsif ($token->[0] eq 'PI') {
1205: $result.=$token->[2];
1206: } elsif ($token->[0] eq 'S') {
1207: if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
1208: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
1209: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1210: $result.=$token->[4];
1211: } elsif ($token->[0] eq 'E') {
1212: if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
1213: #skip sending back the last end tag
1214: if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
1215: my $string=
1216: '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
1217: $$style{'/'.$token->[1]}.
1218: $token->[2].
1219: '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
1220: &Apache::lonxml::newparser($pars,\$string);
1221: #&Apache::lonxml::debug("reParsing $string");
1222: next;
1223: }
1224: if ($depth > -1) {
1225: $result.=$token->[2];
1226: } else {
1227: $$pars[-1]->unget_token($token);
1228: }
1229: }
1230: }
1231: if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
1232: if (($depth >=0) && ($#$pars > 0) ) {
1233: pop(@$pars);
1234: pop(@Apache::lonxml::pwd);
1235: }
1236: }
1237: if ($top_empty && $depth >= 0) {
1238: #never found the end tag ran out of text, throw error send back blank
1239: &error('Never found end tag for <'.$tag.
1240: '> current string <pre>'.
1241: &HTML::Entities::encode($result,'<>&"').
1242: '</pre>');
1243: if ($gotfullstack) {
1244: my $newstring='</'.$tag.'>'.$result;
1245: &Apache::lonxml::newparser($pars,\$newstring);
1246: }
1247: $result='';
1248: }
1249: } else {
1250: while ($#$pars > -1) {
1251: while ($token = $$pars[-1]->get_token) {
1252: #&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
1253: if (($token->[0] eq 'T')||($token->[0] eq 'C')||
1254: ($token->[0] eq 'D')) {
1255: if ($token->[2]) {
1256: $result.='<![CDATA['.$token->[1].']]>';
1257: } else {
1258: $result.=$token->[1];
1259: }
1260: } elsif ($token->[0] eq 'PI') {
1261: $result.=$token->[2];
1262: } elsif ($token->[0] eq 'S') {
1263: if ( $token->[1] =~ /^\Q$tag\E$/i) {
1264: $$pars[-1]->unget_token($token); last;
1265: } else {
1266: $result.=$token->[4];
1267: }
1268: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
1269: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1270: } elsif ($token->[0] eq 'E') {
1271: $result.=$token->[2];
1272: }
1273: }
1274: if (($#$pars > 0) ) {
1275: pop(@$pars);
1276: pop(@Apache::lonxml::pwd);
1277: } else { last; }
1278: }
1279: }
1280: #&Apache::lonxml::debug("Exit:$result:");
1281: return $result
1282: }
1283:
1284: sub newparser {
1285: my ($parser,$contentref,$dir) = @_;
1286: push (@$parser,HTML::LCParser->new($contentref));
1287: $$parser[-1]->xml_mode(1);
1288: $$parser[-1]->marked_sections(1);
1289: if ( $dir eq '' ) {
1290: push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
1291: } else {
1292: push (@Apache::lonxml::pwd, $dir);
1293: }
1294: }
1295:
1296: sub parstring {
1297: my ($token) = @_;
1298: my (@vars,@values);
1299: foreach my $attr (@{$token->[3]}) {
1300: if ($attr!~/\W/) {
1301: my $val=$token->[2]->{$attr};
1302: $val =~ s/([\%\@\\\"\'])/\\$1/g;
1303: $val =~ s/(\$[^\{a-zA-Z_])/\\$1/g;
1304: $val =~ s/(\$)$/\\$1/;
1305: #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
1306: push(@vars,"\$$attr");
1307: push(@values,"\"$val\"");
1308: }
1309: }
1310: my $var_init =
1311: (@vars) ? 'my ('.join(',',@vars).') = ('.join(',',@values).');'
1312: : '';
1313: return $var_init;
1314: }
1315:
1316: sub extlink {
1317: my ($res,$exact)=@_;
1318: if (!$exact) {
1319: $res=&Apache::lonnet::hreflocation($Apache::lonxml::pwd[-1],$res);
1320: }
1321: push(@Apache::lonxml::extlinks,$res)
1322: }
1323:
1324: sub writeallows {
1325: unless ($#extlinks>=0) { return; }
1326: my $thisurl = &Apache::lonnet::clutter(shift);
1327: if ($env{'httpref.'.$thisurl}) {
1328: $thisurl=$env{'httpref.'.$thisurl};
1329: }
1330: my $thisdir=$thisurl;
1331: $thisdir=~s/\/[^\/]+$//;
1332: my %httpref=();
1333: foreach (@extlinks) {
1334: $httpref{'httpref.'.
1335: &Apache::lonnet::hreflocation($thisdir,&unescape($_))}=$thisurl;
1336: }
1337: @extlinks=();
1338: &Apache::lonnet::appenv(\%httpref);
1339: }
1340:
1341: sub register_ssi {
1342: my ($url,%form)=@_;
1343: push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
1344: return '';
1345: }
1346:
1347: sub do_registered_ssi {
1348: foreach my $info (@Apache::lonxml::ssi_info) {
1349: my %form=%{ $info->{'form'}};
1350: my $url=$info->{'url'};
1351: &Apache::lonnet::ssi($url,%form);
1352: }
1353: }
1354:
1355: sub add_script_result {
1356: my ($display) = @_;
1357: push(@script_var_displays, $display);
1358: }
1359:
1360: #
1361: # Afterburner handles anchors, highlights and links
1362: #
1363: sub afterburn {
1364: my $result=shift;
1365: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1366: ['highlight','anchor','link']);
1367: if ($env{'form.highlight'}) {
1368: foreach (split(/\,/,$env{'form.highlight'})) {
1369: my $anchorname=$_;
1370: my $matchthis=$anchorname;
1371: $matchthis=~s/\_+/\\s\+/g;
1372: $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
1373: }
1374: }
1375: if ($env{'form.link'}) {
1376: foreach (split(/\,/,$env{'form.link'})) {
1377: my ($anchorname,$linkurl)=split(/\>/,$_);
1378: my $matchthis=$anchorname;
1379: $matchthis=~s/\_+/\\s\+/g;
1380: $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1381: }
1382: }
1383: if ($env{'form.anchor'}) {
1384: my $anchorname=$env{'form.anchor'};
1385: my $matchthis=$anchorname;
1386: $matchthis=~s/\_+/\\s\+/g;
1387: $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
1388: $result.=(<<"ENDSCRIPT");
1389: <script type="text/javascript">
1390: document.location.hash='$anchorname';
1391: </script>
1392: ENDSCRIPT
1393: }
1394: return $result;
1395: }
1396:
1397: sub storefile {
1398: my ($file,$contents)=@_;
1399: &Apache::lonnet::correct_line_ends(\$contents);
1400: if (my $fh=Apache::File->new('>'.$file)) {
1401: print $fh $contents;
1402: $fh->close();
1403: return 1;
1404: } else {
1405: &warning(&mt('Unable to save file [_1]','<tt>'.$file.'</tt>'));
1406: return 0;
1407: }
1408: }
1409:
1410: sub createnewhtml {
1411: my $title=&mt('Title of document goes here');
1412: my $body=&mt('Body of document goes here');
1413: my $filecontents=(<<SIMPLECONTENT);
1414: <html>
1415: <head>
1416: <title>$title</title>
1417: </head>
1418: <body bgcolor="#FFFFFF">
1419: $body
1420: </body>
1421: </html>
1422: SIMPLECONTENT
1423: return $filecontents;
1424: }
1425:
1426: sub createnewsty {
1427: my $filecontents=(<<SIMPLECONTENT);
1428: <definetag name="">
1429: <render>
1430: <web></web>
1431: <tex></tex>
1432: </render>
1433: </definetag>
1434: SIMPLECONTENT
1435: return $filecontents;
1436: }
1437:
1438: sub createnewjs {
1439: my $filecontents=(<<SIMPLECONTENT);
1440: <script type="text/javascript" language="Javascript">
1441:
1442: </script>
1443: SIMPLECONTENT
1444: return $filecontents;
1445: }
1446:
1447: sub verify_html {
1448: my ($filecontents)=@_;
1449: my ($is_html,$is_xml);
1450: if ($filecontents =~/(?:\<|\<\;)\?xml[^\<]*\?(?:\>|\>\;)/is) {
1451: $is_xml = 1;
1452: } elsif ($filecontents =~/(?:\<|\<\;)html(?:\s+[^\<]+|\s*)(?:\>|\>\;)/is) {
1453: $is_html = 1;
1454: }
1455: unless ($is_xml || $is_html) {
1456: return &mt('File does not have [_1] or [_2] starting tag','<html>','<?xml ?>');
1457: }
1458: if ($is_html) {
1459: if ($filecontents!~/(?:\<|\<\;)\/html(?:\>|\>\;)/is) {
1460: return &mt('File does not have [_1] ending tag','<html>');
1461: }
1462: if ($filecontents!~/(?:\<|\<\;)(?:body|frameset)[^\<]*(?:\>|\>\;)/is) {
1463: return &mt('File does not have [_1] or [_2] starting tag','<body>','<frameset>');
1464: }
1465: if ($filecontents!~/(?:\<|\<\;)\/(?:body|frameset)[^\<]*(?:\>|\>\;)/is) {
1466: return &mt('File does not have [_1] or [_2] ending tag','<body>','<frameset>');
1467: }
1468: }
1469: return '';
1470: }
1471:
1472: sub renderingoptions {
1473: my %langchoices=('' => '');
1474: foreach (&Apache::loncommon::languageids()) {
1475: if (&Apache::loncommon::supportedlanguagecode($_)) {
1476: $langchoices{&Apache::loncommon::supportedlanguagecode($_)}
1477: = &Apache::loncommon::plainlanguagedescription($_);
1478: }
1479: }
1480: my $output;
1481: unless ($env{'form.forceedit'}) {
1482: $output .=
1483: '<span class="LC_nobreak">'.
1484: &mt('Language:').' '.
1485: &Apache::loncommon::select_form(
1486: $env{'form.languages'},
1487: 'languages',
1488: {&Apache::lonlocal::texthash(%langchoices)}).
1489: '</span>';
1490: }
1491: $output .=
1492: ' <span class="LC_nobreak">'.
1493: &mt('Math Rendering:').' '.
1494: &Apache::loncommon::select_form(
1495: $env{'form.texengine'},
1496: 'texengine',
1497: {&Apache::lonlocal::texthash
1498: ('' => '',
1499: 'tth' => 'tth (TeX to HTML)',
1500: 'MathJax' => 'MathJax',
1501: 'jsMath' => 'jsMath',
1502: 'mimetex' => 'mimetex (Convert to Images)')}).
1503: '</span>';
1504: return $output;
1505: }
1506:
1507: sub inserteditinfo {
1508: my ($filecontents, $filetype, $filename)=@_;
1509: $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
1510: my $xml_help = '';
1511: my $initialize='';
1512: my $textarea_id = 'filecont';
1513: my $dragmath_button;
1514: my ($add_to_onload, $add_to_onresize);
1515: $initialize=&Apache::lonhtmlcommon::spellheader();
1516: if (($filetype eq 'html') && (&Apache::lonhtmlcommon::htmlareabrowser())) {
1517: my $lang = &Apache::lonhtmlcommon::htmlarea_lang();
1518: my %textarea_args = (
1519: fullpage => 'true',
1520: dragmath => 'math',
1521: );
1522: $initialize .= &Apache::lonhtmlcommon::htmlareaselectactive(\%textarea_args);
1523: }
1524: $initialize .= (<<FULLPAGE);
1525: <script type="text/javascript">
1526: // <![CDATA[
1527: function initDocument() {
1528: resize_textarea('$textarea_id','LC_aftertextarea');
1529: }
1530: // ]]>
1531: </script>
1532: FULLPAGE
1533: if ($filetype eq 'html') {
1534: $dragmath_button = '<span id="math_filecont">'.&Apache::lonhtmlcommon::dragmath_button('filecont',1).'</span>';
1535: $initialize .= "\n".&Apache::lonhtmlcommon::dragmath_js('EditMathPopup');
1536: }
1537: $add_to_onload = 'initDocument();';
1538: $add_to_onresize = "resize_textarea('$textarea_id','LC_aftertextarea');";
1539:
1540: if ($filetype eq 'html') {
1541: $xml_help=&Apache::loncommon::helpLatexCheatsheet();
1542: }
1543:
1544: my $titledisplay=&display_title();
1545: my $textareaclass;
1546: my %lt=&Apache::lonlocal::texthash('st' => 'Save and Edit',
1547: 'vi' => 'Save and View',
1548: 'dv' => 'Discard Edits and View',
1549: 'un' => 'undo',
1550: 'ed' => 'Edit');
1551: my $spelllink = &Apache::lonhtmlcommon::spelllink('xmledit','filecont');
1552: my $textarea_events = &Apache::edit::element_change_detection();
1553: my $form_events = &Apache::edit::form_change_detection();
1554: my $htmlerror;
1555: if ($filetype eq 'html') {
1556: $htmlerror=&verify_html($filecontents);
1557: if ($htmlerror) {
1558: $htmlerror='<span class="LC_error">'.$htmlerror.'</span>';
1559: }
1560: if (&Apache::lonhtmlcommon::htmlareabrowser()) {
1561: $textareaclass = 'class="LC_richDefaultOff"';
1562: }
1563: }
1564: my $editfooter=(<<ENDFOOTER);
1565: $initialize
1566: <a name="editsection" />
1567: <form $form_events method="post" name="xmledit">
1568: <div class="LC_edit_problem_editxml_header">
1569: <table class="LC_edit_problem_header_title"><tr><td>
1570: $filename
1571: </td><td align="right">
1572: $xml_help
1573: </td></tr>
1574: </table>
1575: <div class="LC_edit_problem_discards">
1576: <input type="submit" name="discardview" accesskey="d" value="$lt{'dv'}" />
1577: <input type="submit" name="Undo" accesskey="u" value="$lt{'un'}" />
1578: $htmlerror $dragmath_button
1579: </div>
1580: <div class="LC_edit_problem_saves">
1581: <input type="submit" name="savethisfile" accesskey="s" value="$lt{'st'}" />
1582: <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
1583: </div>
1584: </div>
1585: <textarea $textarea_events style="width:100%" cols="80" rows="44" name="filecont" id="filecont" $textareaclass>$filecontents</textarea><br />$spelllink
1586: <div id="LC_aftertextarea">
1587: <br />
1588: $titledisplay
1589: </div>
1590: </form>
1591: </body>
1592: ENDFOOTER
1593: return ($editfooter,$add_to_onload,$add_to_onresize);;
1594: }
1595:
1596: sub get_target {
1597: my $viewgrades=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
1598: if ( $env{'request.state'} eq 'published') {
1599: if ( defined($env{'form.grade_target'})
1600: && ($viewgrades == 'F' )) {
1601: return ($env{'form.grade_target'});
1602: } elsif (defined($env{'form.grade_target'})) {
1603: if (($env{'form.grade_target'} eq 'web') ||
1604: ($env{'form.grade_target'} eq 'tex') ) {
1605: return $env{'form.grade_target'}
1606: } else {
1607: return 'web';
1608: }
1609: } else {
1610: return 'web';
1611: }
1612: } elsif ($env{'request.state'} eq 'construct') {
1613: if ( defined($env{'form.grade_target'})) {
1614: return ($env{'form.grade_target'});
1615: } else {
1616: return 'web';
1617: }
1618: } else {
1619: return 'web';
1620: }
1621: }
1622:
1623: sub handler {
1624: my $request=shift;
1625:
1626: my $target=&get_target();
1627: $Apache::lonxml::debug=$env{'user.debug'};
1628:
1629: &Apache::loncommon::content_type($request,'text/html');
1630: &Apache::loncommon::no_cache($request);
1631: if ($env{'request.state'} eq 'published') {
1632: $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
1633: 'lastrevisiondate'));
1634: }
1635: # Embedded Flash movies from Camtasia served from https will not display in IE
1636: # if XML config file has expired from cache.
1637: if ($ENV{'SERVER_PORT'} == 443) {
1638: if ($request->uri =~ /\.xml$/) {
1639: my ($httpbrowser,$clientbrowser) =
1640: &Apache::loncommon::decode_user_agent($request);
1641: if ($clientbrowser =~ /^explorer$/i) {
1642: delete $request->headers_out->{'Cache-control'};
1643: delete $request->headers_out->{'Pragma'};
1644: my $expiration = time + 60;
1645: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime($expiration));
1646: $request->headers_out->set("Expires" => $date);
1647: }
1648: }
1649: }
1650: $request->send_http_header;
1651:
1652: return OK if $request->header_only;
1653:
1654:
1655: my $file=&Apache::lonnet::filelocation("",$request->uri);
1656: my ($filetype,$breadcrumbtext);
1657: if ($file =~ /\.(sty|css|js|txt|tex)$/) {
1658: $filetype=$1;
1659: } else {
1660: $filetype='html';
1661: }
1662: if ($filetype eq 'sty') {
1663: $breadcrumbtext = 'Style File Editor';
1664: } elsif ($filetype eq 'js') {
1665: $breadcrumbtext = 'Javascript Editor';
1666: } elsif ($filetype eq 'css') {
1667: $breadcrumbtext = 'CSS Editor';
1668: } elsif ($filetype eq 'txt') {
1669: $breadcrumbtext = 'Text Editor';
1670: } elsif ($filetype eq 'tex') {
1671: $breadcrumbtext = 'TeX Editor';
1672: } else {
1673: $breadcrumbtext = 'HTML Editor';
1674: }
1675:
1676: #
1677: # Edit action? Save file.
1678: #
1679: if (!($env{'request.state'} eq 'published')) {
1680: if ($env{'form.savethisfile'} || $env{'form.viewmode'} || $env{'form.Undo'}) {
1681: my $html_file=&Apache::lonnet::getfile($file);
1682: my $error = &Apache::lonhomework::handle_save_or_undo($request, \$html_file, \$env{'form.filecont'});
1683: if ($env{'form.savethisfile'}) {
1684: $env{'form.editmode'}='Edit'; #force edit mode
1685: }
1686: }
1687: }
1688: my %mystyle;
1689: my $result = '';
1690: my $filecontents=&Apache::lonnet::getfile($file);
1691: if ($filecontents eq -1) {
1692: my $start_page=&Apache::loncommon::start_page('File Error');
1693: my $end_page=&Apache::loncommon::end_page();
1694: my $errormsg='<p class="LC_error">'
1695: .&mt('File not found: [_1]'
1696: ,'<span class="LC_filename">'.$file.'</span>')
1697: .'</p>';
1698: $result=(<<ENDNOTFOUND);
1699: $start_page
1700: $errormsg
1701: $end_page
1702: ENDNOTFOUND
1703: $filecontents='';
1704: if ($env{'request.state'} ne 'published') {
1705: if ($filetype eq 'sty') {
1706: $filecontents=&createnewsty();
1707: } elsif ($filetype eq 'js') {
1708: $filecontents=&createnewjs();
1709: } elsif ($filetype ne 'css' && $filetype ne 'txt' && $filetype ne 'tex') {
1710: $filecontents=&createnewhtml();
1711: }
1712: $env{'form.editmode'}='Edit'; #force edit mode
1713: }
1714: } else {
1715: unless ($env{'request.state'} eq 'published') {
1716: if ($filecontents=~/BEGIN LON-CAPA Internal/) {
1717: &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.'));
1718: }
1719: #
1720: # we are in construction space, see if edit mode forced
1721: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1722: ['editmode']);
1723: }
1724: if (!$env{'form.editmode'} || $env{'form.viewmode'} || $env{'form.discardview'}) {
1725: if ($filetype eq 'html' || $filetype eq 'sty') {
1726: &Apache::structuretags::reset_problem_globals();
1727: $result = &Apache::lonxml::xmlparse($request,$target,
1728: $filecontents,'',%mystyle);
1729: # .html files may contain <problem> or <Task> need to clean
1730: # up if it did
1731: &Apache::structuretags::reset_problem_globals();
1732: &Apache::lonhomework::finished_parsing();
1733: } elsif ($filetype eq 'tex') {
1734: $result = &Apache::lontexconvert::converted(\$filecontents,
1735: $env{'form.texengine'});
1736: if ($env{'form.return_only_error_and_warning_counts'}) {
1737: $result = "$errorcount:$warningcount";
1738: }
1739: } else {
1740: $result = $filecontents;
1741: }
1742: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1743: ['rawmode']);
1744: if ($env{'form.rawmode'}) { $result = $filecontents; }
1745: if (($filetype ne 'html') &&
1746: (!$env{'form.return_only_error_and_warning_counts'})) {
1747: my $nochgview = 1;
1748: my $controls = '';
1749: if ($env{'request.state'} eq 'construct') {
1750: $controls = &Apache::loncommon::head_subbox(
1751: &Apache::loncommon::CSTR_pageheader()
1752: .&Apache::londefdef::edit_controls($nochgview));
1753: }
1754: if ($filetype ne 'sty' && $filetype ne 'tex') {
1755: $result =~ s/</</g;
1756: $result =~ s/>/>/g;
1757: $result = '<table class="LC_sty_begin">'.
1758: '<tr><td><b><pre>'.$result.
1759: '</pre></b></td></tr></table>';
1760: }
1761: my $brcrum;
1762: if ($env{'request.state'} eq 'construct') {
1763: $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1764: 'text' => 'Construction Space'},
1765: {'href' => '',
1766: 'text' => $breadcrumbtext}];
1767: } else {
1768: $brcrum = ''; # FIXME: Where are we?
1769: }
1770: my %options = ('bread_crumbs' => $brcrum,
1771: 'bgcolor' => '#FFFFFF');
1772: $result =
1773: &Apache::loncommon::start_page(undef,undef,\%options)
1774: .$controls
1775: .$result
1776: .&Apache::loncommon::end_page();
1777: }
1778: }
1779: }
1780:
1781: #
1782: # Edit action? Insert editing commands
1783: #
1784: unless ($env{'request.state'} eq 'published') {
1785: if ($env{'form.editmode'} && (!($env{'form.viewmode'})) && (!($env{'form.discardview'})))
1786: {
1787: my $displayfile=$request->uri;
1788: $displayfile=~s/^\/[^\/]*//;
1789:
1790: my ($edit_info, $add_to_onload, $add_to_onresize)=
1791: &inserteditinfo($filecontents,$filetype,$displayfile);
1792:
1793: my %options =
1794: ('add_entries' =>
1795: {'onresize' => $add_to_onresize,
1796: 'onload' => $add_to_onload, });
1797: my $header;
1798: if ($env{'request.state'} eq 'construct') {
1799: $options{'bread_crumbs'} = [{
1800: 'href' => &Apache::loncommon::authorspace($request->uri),
1801: 'text' => 'Construction Space'},
1802: {'href' => '',
1803: 'text' => $breadcrumbtext}];
1804: $header = &Apache::loncommon::head_subbox(
1805: &Apache::loncommon::CSTR_pageheader());
1806: }
1807: my $js =
1808: &Apache::edit::js_change_detection().
1809: &Apache::loncommon::resize_textarea_js();
1810: my $start_page = &Apache::loncommon::start_page(undef,$js,
1811: \%options);
1812: $result = $start_page
1813: .$header
1814: .&Apache::lonxml::message_location()
1815: .$edit_info
1816: .&Apache::loncommon::end_page();
1817: }
1818: }
1819: if ($filetype eq 'html') { &writeallows($request->uri); }
1820:
1821: &Apache::lonxml::add_messages(\$result);
1822: $request->print($result);
1823:
1824: return OK;
1825: }
1826:
1827: sub display_title {
1828: my $result;
1829: if ($env{'request.state'} eq 'construct') {
1830: my $title=&Apache::lonnet::gettitle();
1831: if (!defined($title) || $title eq '') {
1832: $title = $env{'request.filename'};
1833: $title = substr($title, rindex($title, '/') + 1);
1834: }
1835: $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA "
1836: .&mt('Construction Space')."';</script>";
1837: }
1838: return $result;
1839: }
1840:
1841: sub debug {
1842: if ($Apache::lonxml::debug eq "1") {
1843: $|=1;
1844: my $request=$Apache::lonxml::request;
1845: if (!$request) {
1846: eval { $request=Apache->request; };
1847: }
1848: if (!$request) {
1849: eval { $request=Apache2::RequestUtil->request; };
1850: }
1851: $request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
1852: #&Apache::lonnet::logthis($_[0]);
1853: }
1854: }
1855:
1856: sub show_error_warn_msg {
1857: if (($env{'request.filename'} eq
1858: $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/lib/templates/simpleproblem.problem') &&
1859: (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
1860: return 1;
1861: }
1862: return (($Apache::lonxml::debug eq 1) ||
1863: ($env{'request.state'} eq 'construct') ||
1864: ($Apache::lonhomework::browse eq 'F'
1865: &&
1866: $env{'form.show_errors'} eq 'on'));
1867: }
1868:
1869: sub error {
1870: my @errors = @_;
1871:
1872: $errorcount++;
1873:
1874: $Apache::lonxml::internal_error=1;
1875:
1876: if (defined($Apache::inputtags::part)) {
1877: if ( @Apache::inputtags::response ) {
1878: push(@errors,
1879: &mt("This error occurred while processing response [_1] in part [_2]",
1880: $Apache::inputtags::response[-1],
1881: $Apache::inputtags::part));
1882: } else {
1883: push(@errors,
1884: &mt("This error occurred while processing part [_1]",
1885: $Apache::inputtags::part));
1886: }
1887: }
1888:
1889: if ( &show_error_warn_msg() ) {
1890: # If printing in construction space, put the error inside <pre></pre>
1891: push(@Apache::lonxml::error_messages,
1892: $Apache::lonxml::warnings_error_header
1893: .'<div class="LC_error">'
1894: .'<b>'.&mt('ERROR:').' </b>'.join("<br />\n",@errors)
1895: ."</div>\n");
1896: $Apache::lonxml::warnings_error_header='';
1897: } else {
1898: my $errormsg;
1899: my ($symb)=&Apache::lonnet::symbread();
1900: if ( !$symb ) {
1901: #public or browsers
1902: $errormsg=&mt("An error occurred while processing this resource. The author has been notified.");
1903: }
1904: my $host=$Apache::lonnet::perlvar{'lonHostID'};
1905: push(@errors,
1906: &mt("The error occurred on host [_1]",
1907: "<tt>$host</tt>"));
1908:
1909: my $msg = join('<br />', @errors);
1910:
1911: #notify author
1912: &Apache::lonmsg::author_res_msg($env{'request.filename'},$msg);
1913: #notify course
1914: if ( $symb && $env{'request.course.id'} ) {
1915: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1916: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1917: my (undef,%users)=&Apache::lonmsg::decide_receiver(undef,0,1,1,1);
1918: my $declutter=&Apache::lonnet::declutter($env{'request.filename'});
1919: my $baseurl = &Apache::lonnet::clutter($declutter);
1920: my @userlist;
1921: foreach (keys %users) {
1922: my ($user,$domain) = split(/:/, $_);
1923: push(@userlist,"$user\@$domain");
1924: my $key=$declutter.'_'.$user.'_'.$domain;
1925: my %lastnotified=&Apache::lonnet::get('nohist_xmlerrornotifications',
1926: [$key],
1927: $cdom,$cnum);
1928: my $now=time;
1929: if ($now-$lastnotified{$key}>86400) {
1930: my $title = &Apache::lonnet::gettitle($symb);
1931: my $sentmessage;
1932: &Apache::lonmsg::user_normal_msg($user,$domain,
1933: "Error [$title]",$msg,'',$baseurl,'','',
1934: \$sentmessage,$symb,$title,1);
1935: &Apache::lonnet::put('nohist_xmlerrornotifications',
1936: {$key => $now},
1937: $cdom,$cnum);
1938: }
1939: }
1940: if ($env{'request.role.adv'}) {
1941: $errormsg=&mt("An error occurred while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
1942: } else {
1943: $errormsg=&mt("An error occurred while processing this resource. The instructor has been notified.");
1944: }
1945: }
1946: push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
1947: }
1948: }
1949:
1950: sub warning {
1951: $warningcount++;
1952:
1953: if ($env{'form.grade_target'} ne 'tex') {
1954: if ( &show_error_warn_msg() ) {
1955: push(@Apache::lonxml::warning_messages,
1956: $Apache::lonxml::warnings_error_header
1957: .'<div class="LC_warning">'
1958: .&mt('[_1]W[_2]ARNING','<b>','</b>')."<b>:</b> ".join('<br />',@_)
1959: ."</div>\n"
1960: );
1961: $Apache::lonxml::warnings_error_header='';
1962: }
1963: }
1964: }
1965:
1966: sub info {
1967: if ($env{'form.grade_target'} ne 'tex'
1968: && $env{'request.state'} eq 'construct') {
1969: push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
1970: }
1971: }
1972:
1973: sub message_location {
1974: return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
1975: }
1976:
1977: sub add_messages {
1978: my ($msg)=@_;
1979: my $result=join(' ',
1980: @Apache::lonxml::info_messages,
1981: @Apache::lonxml::error_messages,
1982: @Apache::lonxml::warning_messages);
1983: undef(@Apache::lonxml::info_messages);
1984: undef(@Apache::lonxml::error_messages);
1985: undef(@Apache::lonxml::warning_messages);
1986: $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
1987: $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
1988: }
1989:
1990: sub get_param {
1991: my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1992: if ( ! $context ) { $context = -1; }
1993: my $args ='';
1994: if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1995: if ( ! $Apache::lonxml::usestyle ) {
1996: $args=$Apache::lonxml::style_values.$args;
1997: }
1998: if ( ! $args ) { return undef; }
1999: if ( $case_insensitive ) {
2000: if ($args =~ s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei) {
2001: return &Apache::run::run("{$args;".'return $'.$param.'}',
2002: $safeeval); #'
2003: } else {
2004: return undef;
2005: }
2006: } else {
2007: if ( $args =~ /my .*\$\Q$param\E[,\)]/ ) {
2008: return &Apache::run::run("{$args;".'return $'.$param.'}',
2009: $safeeval); #'
2010: } else {
2011: return undef;
2012: }
2013: }
2014: }
2015:
2016: sub get_param_var {
2017: my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
2018: if ( ! $context ) { $context = -1; }
2019: my $args ='';
2020: if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
2021: if ( ! $Apache::lonxml::usestyle ) {
2022: $args=$Apache::lonxml::style_values.$args;
2023: }
2024: &Apache::lonxml::debug("Args are $args param is $param");
2025: if ($case_insensitive) {
2026: if (! ($args=~s/(my (?:.*))(\$\Q$param\E[,\)])/$1.lc($2)/ei)) {
2027: return undef;
2028: }
2029: } elsif ( $args !~ /my .*\$\Q$param\E[,\)]/ ) { return undef; }
2030: my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
2031: &Apache::lonxml::debug("first run is $value");
2032: if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
2033: &Apache::lonxml::debug("doing second");
2034: my @result=&Apache::run::run("return $value",$safeeval,1);
2035: if (!defined($result[0])) {
2036: return $value
2037: } else {
2038: if (wantarray) { return @result; } else { return $result[0]; }
2039: }
2040: } else {
2041: return $value;
2042: }
2043: }
2044:
2045: sub register_insert_xml {
2046: my $parser = HTML::LCParser->new($Apache::lonnet::perlvar{'lonTabDir'}
2047: .'/insertlist.xml');
2048: my ($tagnum,$in_help)=(0,0);
2049: my @alltags;
2050: my $tag;
2051: while (my $token = $parser->get_token()) {
2052: if ($token->[0] eq 'S') {
2053: my $key;
2054: if ($token->[1] eq 'tag') {
2055: $tag = $token->[2]{'name'};
2056: if (defined($tag)) {
2057: $insertlist{$tagnum.'.tag'} = $tag;
2058: $insertlist{$tag.'.num'} = $tagnum;
2059: push(@alltags,$tag);
2060: }
2061: } elsif ($in_help && $token->[1] eq 'file') {
2062: $key = $tag.'.helpfile';
2063: } elsif ($in_help && $token->[1] eq 'description') {
2064: $key = $tag.'.helpdesc';
2065: } elsif ($token->[1] eq 'description' ||
2066: $token->[1] eq 'color' ||
2067: $token->[1] eq 'show' ) {
2068: $key = $tag.'.'.$token->[1];
2069: } elsif ($token->[1] eq 'insert_sub') {
2070: $key = $tag.'.function';
2071: } elsif ($token->[1] eq 'help') {
2072: $in_help=1;
2073: } elsif ($token->[1] eq 'allow') {
2074: $key = $tag.'.allow';
2075: }
2076: if (defined($key)) {
2077: $insertlist{$key} = $parser->get_text();
2078: $insertlist{$key} =~ s/(^\s*|\s*$ )//gx;
2079: }
2080: } elsif ($token->[0] eq 'E') {
2081: if ($token->[1] eq 'tag') {
2082: undef($tag);
2083: $tagnum++;
2084: } elsif ($token->[1] eq 'help') {
2085: undef($in_help);
2086: }
2087: }
2088: }
2089:
2090: # parse the allows and ignore tags set to <show>no</show>
2091: foreach my $tag (@alltags) {
2092: next if (!exists($insertlist{$tag.'.allow'}));
2093: my $allow = $insertlist{$tag.'.allow'};
2094: foreach my $element (split(',',$allow)) {
2095: $element =~ s/(^\s*|\s*$ )//gx;
2096: if (!exists($insertlist{$element.'.show'})
2097: || $insertlist{$element.'.show'} ne 'no') {
2098: push(@{ $insertlist{$tag.'.which'} },$element);
2099: }
2100: }
2101: }
2102: }
2103:
2104: sub register_insert {
2105: return ®ister_insert_xml(@_);
2106: # &dump_insertlist('2');
2107: }
2108:
2109: sub dump_insertlist {
2110: my ($ext) = @_;
2111: open(XML,">/tmp/insertlist.xml.$ext");
2112: print XML ("<insertlist>");
2113: my $i=0;
2114:
2115: while (exists($insertlist{"$i.tag"})) {
2116: my $tag = $insertlist{"$i.tag"};
2117: print XML ("
2118: \t<tag name=\"$tag\">");
2119: if (defined($insertlist{"$tag.description"})) {
2120: print XML ("
2121: \t\t<description>".$insertlist{"$tag.description"}."</description>");
2122: }
2123: if (defined($insertlist{"$tag.color"})) {
2124: print XML ("
2125: \t\t<color>".$insertlist{"$tag.color"}."</color>");
2126: }
2127: if (defined($insertlist{"$tag.function"})) {
2128: print XML ("
2129: \t\t<insert_sub>".$insertlist{"$tag.function"}."</insert_sub>");
2130: }
2131: if (defined($insertlist{"$tag.show"})
2132: && $insertlist{"$tag.show"} ne 'yes') {
2133: print XML ("
2134: \t\t<show>".$insertlist{"$tag.show"}."</show>");
2135: }
2136: if (defined($insertlist{"$tag.helpfile"})) {
2137: print XML ("
2138: \t\t<help>
2139: \t\t\t<file>".$insertlist{"$tag.helpfile"}."</file>");
2140: if ($insertlist{"$tag.helpdesc"} ne '') {
2141: print XML ("
2142: \t\t\t<description>".$insertlist{"$tag.helpdesc"}."</description>");
2143: }
2144: print XML ("
2145: \t\t</help>");
2146: }
2147: if (defined($insertlist{"$tag.which"})) {
2148: print XML ("
2149: \t\t<allow>".join(',',sort(@{ $insertlist{"$tag.which"} }))."</allow>");
2150: }
2151: print XML ("
2152: \t</tag>");
2153: $i++;
2154: }
2155: print XML ("\n</insertlist>\n");
2156: close(XML);
2157: }
2158:
2159: sub description {
2160: my ($token)=@_;
2161: my $tag = &get_tag($token);
2162: return $insertlist{$tag.'.description'};
2163: }
2164:
2165: # Returns a list containing the help file, and the description
2166: sub helpinfo {
2167: my ($token)=@_;
2168: my $tag = &get_tag($token);
2169: return ($insertlist{$tag.'.helpfile'}, $insertlist{$tag.'.helpdesc'});
2170: }
2171:
2172: sub get_tag {
2173: my ($token)=@_;
2174: my $tagnum;
2175: my $tag=$token->[1];
2176: foreach my $namespace (reverse(@Apache::lonxml::namespace)) {
2177: my $testtag = $namespace.'::'.$tag;
2178: $tagnum = $insertlist{"$testtag.num"};
2179: last if (defined($tagnum));
2180: }
2181: if (!defined($tagnum)) {
2182: $tagnum = $Apache::lonxml::insertlist{"$tag.num"};
2183: }
2184: return $insertlist{"$tagnum.tag"};
2185: }
2186:
2187: ############################################################
2188: # PDF-FORM-METHODS
2189:
2190: =pod
2191:
2192: =item &print_pdf_radiobutton(fieldname, value)
2193:
2194: Returns a latexline to generate a PDF-Form-Radiobutton.
2195: Note: Radiobuttons with equal names are automaticly grouped
2196: in a selection-group.
2197:
2198: $fieldname: PDF internalname of the radiobutton(group)
2199: $value: Value of radiobutton
2200:
2201: =cut
2202: sub print_pdf_radiobutton {
2203: my ($fieldname, $value) = @_;
2204: return '\radioButton[\symbolchoice{circle}]{'
2205: .$fieldname.'}{10bp}{10bp}{'.$value.'}';
2206: }
2207:
2208:
2209: =pod
2210:
2211: =item &print_pdf_start_combobox(fieldname)
2212:
2213: Starts a latexline to generate a PDF-Form-Combobox with text.
2214:
2215: $fieldname: PDF internal name of the Combobox
2216:
2217: =cut
2218: sub print_pdf_start_combobox {
2219: my $result;
2220: my ($fieldName) = @_;
2221: $result .= '\begin{tabularx}{\textwidth}{p{2.5cm}X}'."\n";
2222: $result .= '\comboBox[]{'.$fieldName.'}{2.3cm}{14bp}{'; #
2223:
2224: return $result;
2225: }
2226:
2227:
2228: =pod
2229:
2230: =item &print_pdf_add_combobox_option(options)
2231:
2232: Generates a latexline to add Options to a PDF-Form-ComboBox.
2233:
2234: $option: PDF internal name of the Combobox-Option
2235:
2236: =cut
2237: sub print_pdf_add_combobox_option {
2238:
2239: my $result;
2240: my ($option) = @_;
2241:
2242: $result .= '('.$option.')';
2243:
2244: return $result;
2245: }
2246:
2247:
2248: =pod
2249:
2250: =item &print_pdf_end_combobox(text) {
2251:
2252: Returns latexcode to end a PDF-Form-Combobox with text.
2253:
2254: =cut
2255: sub print_pdf_end_combobox {
2256: my $result;
2257: my ($text) = @_;
2258:
2259: $result .= '}&'.$text."\\\\\n";
2260: $result .= '\end{tabularx}' . "\n";
2261: $result .= '\hspace{2mm}' . "\n";
2262: return $result;
2263: }
2264:
2265:
2266: =pod
2267:
2268: =item &print_pdf_hiddenField(fieldname, user, domain)
2269:
2270: Returns a latexline to generate a PDF-Form-hiddenField with userdata.
2271:
2272: $fieldname label for hiddentextfield
2273: $user: name of user
2274: $domain: domain of user
2275:
2276: =cut
2277: sub print_pdf_hiddenfield {
2278: my $result;
2279: my ($fieldname, $user, $domain) = @_;
2280:
2281: $result .= '\textField [\F{\FHidden}\F{-\FPrint}\V{'.$domain.'&'.$user.'}]{'.$fieldname.'}{0in}{0in}'."\n";
2282:
2283: return $result;
2284: }
2285:
2286: 1;
2287: __END__
2288:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>