1: # The LearningOnline Network with CAPA
2: # XML Parser Module
3: #
4: # $Id: lonxml.pm,v 1.345 2004/10/18 19:49:58 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson.
29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into
30: # binary executable programs or libraries distributed by the
31: # Michigan State University (the "Licensee"), but any binaries so
32: # distributed are hereby licensed only for use in the context
33: # of a program or computational system for which the Licensee is the
34: # primary author or distributor, and which performs substantial
35: # additional tasks beyond the translation of (La)TeX into HTML.
36: # The C source of the Code may not be distributed by the Licensee
37: # to any other parties under any circumstances.
38: #
39:
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:
372: my $tree = HTML::TreeBuilder->new;
373: $tree->ignore_unknown(0);
374:
375: $tree->parse($raw);
376:
377: my $output= $tree->as_HTML(undef,' ');
378:
379: $output=~s/\<(br|hr|img|meta|allow)(.*?)\>/\<$1$2 \/\>/gis;
380: $output=~s/\<\/(br|hr|img|meta|allow)\>//gis;
381: unless ($full) {
382: $output=~s/\<[\/]*(body|head|html)\>//gis;
383: }
384:
385: $tree = $tree->delete;
386:
387: return $output;
388: }
389:
390: sub latex_special_symbols {
391: my ($string,$where)=@_;
392: if ($where eq 'header') {
393: $string =~ s/(\\|_|\^)/ /g;
394: $string =~ s/(\$|%|\{|\})/\\$1/g;
395: $string =~ s/_/ /g;
396: $string=&Apache::lonprintout::character_chart($string);
397: # any & or # leftover should be safe to just escape
398: $string=~s/([^\\])\&/$1\\\&/g;
399: $string=~s/([^\\])\#/$1\\\#/g;
400: } else {
401: $string=~s/\\/\\ensuremath{\\backslash}/g;
402: $string=~s/([^\\]|^)\%/$1\\\%/g;
403: $string=~s/([^\\]|^)\$/$1\\\$/g;
404: $string=~s/([^\\])\_/$1\\_/g;
405: $string=~s/\$\$/\$\\\$/g;
406: $string=~s/\_\_/\_\\\_/g;
407: $string=~s/\#\#/\#\\\#/g;
408: $string=~s/([^\\]|^)(\~|\^)/$1\\$2\\strut /g;
409: $string=~s/(>|<)/\\ensuremath\{$1\}/g; #more or less
410: $string=&Apache::lonprintout::character_chart($string);
411: # any & or # leftover should be safe to just escape
412: $string=~s/([^\\]|^)\&/$1\\\&/g;
413: $string=~s/([^\\]|^)\#/$1\\\#/g;
414: $string=~s/\|/\$\\mid\$/g;
415: #single { or } How to escape?
416: }
417: return $string;
418: }
419:
420: sub inner_xmlparse {
421: my ($target,$stack,$parstack,$pars,$safeeval,$style_for_target)=@_;
422: my $finaloutput = '';
423: my $result;
424: my $token;
425: my $dontpop=0;
426: while ( $#$pars > -1 ) {
427: while ($token = $$pars['-1']->get_token) {
428: if (($token->[0] eq 'T') || ($token->[0] eq 'C') ) {
429: if ($metamode<1) {
430: my $text=$token->[1];
431: if ($token->[0] eq 'C' && $target eq 'tex') {
432: $text = '';
433: # $text = '%'.$text."\n";
434: }
435: $result.=$text;
436: }
437: } elsif (($token->[0] eq 'D')) {
438: if ($metamode<1 && $target eq 'web') {
439: my $text=$token->[1];
440: $result.=$text;
441: }
442: } elsif ($token->[0] eq 'PI') {
443: if ($metamode<1 && $target eq 'web') {
444: $result=$token->[2];
445: }
446: } elsif ($token->[0] eq 'S') {
447: # add tag to stack
448: push (@$stack,$token->[1]);
449: # add parameters list to another stack
450: push (@$parstack,&parstring($token));
451: &increasedepth($token);
452: if ($Apache::lonxml::usestyle &&
453: exists($$style_for_target{$token->[1]})) {
454: $Apache::lonxml::usestyle=0;
455: my $string=$$style_for_target{$token->[1]}.
456: '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
457: &Apache::lonxml::newparser($pars,\$string);
458: $Apache::lonxml::style_values=$$parstack[-1];
459: $Apache::lonxml::style_end_values=$$parstack[-1];
460: } else {
461: $result = &callsub("start_$token->[1]", $target, $token, $stack,
462: $parstack, $pars, $safeeval, $style_for_target);
463: }
464: } elsif ($token->[0] eq 'E') {
465: if ($Apache::lonxml::usestyle &&
466: exists($$style_for_target{'/'."$token->[1]"})) {
467: $Apache::lonxml::usestyle=0;
468: my $string=$$style_for_target{'/'.$token->[1]}.
469: '<LONCAPA_INTERNAL_TURN_STYLE_ON end="'.$token->[1].'" />';
470: &Apache::lonxml::newparser($pars,\$string);
471: $Apache::lonxml::style_values=$Apache::lonxml::style_end_values;
472: $Apache::lonxml::style_end_values='';
473: $dontpop=1;
474: } else {
475: #clear out any tags that didn't end
476: while ($token->[1] ne $$stack['-1'] && ($#$stack > -1)) {
477: my $lasttag=$$stack[-1];
478: if ($token->[1] =~ /^\Q$lasttag\E$/i) {
479: &Apache::lonxml::warning('Using tag </'.$token->[1].'> on line '.$token->[3].' as end tag to <'.$$stack[-1].'>');
480: last;
481: } else {
482: &Apache::lonxml::warning('Found tag </'.$token->[1].'> on line '.$token->[3].' when looking for </'.$$stack[-1].'> in file');
483: &end_tag($stack,$parstack,$token);
484: }
485: }
486: $result = &callsub("end_$token->[1]", $target, $token, $stack,
487: $parstack, $pars,$safeeval, $style_for_target);
488: }
489: } else {
490: &Apache::lonxml::error("Unknown token event :$token->[0]:$token->[1]:");
491: }
492: #evaluate variable refs in result
493: if ($Apache::lonxml::post_evaluate &&$result ne "") {
494: my $extras;
495: if (!$Apache::lonxml::usestyle) {
496: $extras=$Apache::lonxml::style_values;
497: }
498: if ( $#$parstack > -1 ) {
499: $result=&Apache::run::evaluate($result,$safeeval,$extras.$$parstack[-1]);
500: } else {
501: $result= &Apache::run::evaluate($result,$safeeval,$extras);
502: }
503: }
504: $Apache::lonxml::post_evaluate=1;
505:
506: if (($token->[0] eq 'T') || ($token->[0] eq 'C') || ($token->[0] eq 'D') ) {
507: #Style file definitions should be correct
508: if ($target eq 'tex' && ($Apache::lonxml::usestyle)) {
509: $result=&latex_special_symbols($result);
510: }
511: }
512:
513: if ($Apache::lonxml::redirection) {
514: $Apache::lonxml::outputstack['-1'] .= $result;
515: } else {
516: $finaloutput.=$result;
517: }
518: $result = '';
519:
520: if ($token->[0] eq 'E' && !$dontpop) {
521: &end_tag($stack,$parstack,$token);
522: }
523: $dontpop=0;
524: }
525: if ($#$pars > -1) {
526: pop @$pars;
527: pop @Apache::lonxml::pwd;
528: }
529: }
530:
531: # if ($target eq 'meta') {
532: # $finaloutput.=&endredirection;
533: # }
534:
535:
536: if (($ENV{'QUERY_STRING'}) && ($target eq 'web')) {
537: $finaloutput=&afterburn($finaloutput);
538: }
539: return $finaloutput;
540: }
541:
542: ##
543: ## Looks to see if there is a subroutine defined for this tag. If so, call it,
544: ## otherwise do not call it as we do not know what it is.
545: ##
546: sub callsub {
547: my ($sub,$target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
548: my $currentstring='';
549: my $nodefault;
550: {
551: my $sub1;
552: no strict 'refs';
553: my $tag=$token->[1];
554: # get utterly rid of extended html tags
555: if ($tag=~/^x\-/i) { return ''; }
556: my $space=$Apache::lonxml::alltags{$tag}[-1];
557: if (!$space) {
558: $tag=~tr/A-Z/a-z/;
559: $sub=~tr/A-Z/a-z/;
560: $space=$Apache::lonxml::alltags{$tag}[-1]
561: }
562:
563: my $deleted=0;
564: $Apache::lonxml::curdepth=join('_',@Apache::lonxml::depthcounter);
565: if (($token->[0] eq 'S') && ($target eq 'modified')) {
566: $deleted=&Apache::edit::handle_delete($space,$target,$token,$tagstack,
567: $parstack,$parser,$safeeval,
568: $style);
569: }
570: if (!$deleted) {
571: if ($space) {
572: #&Apache::lonxml::debug("Calling sub $sub in $space $metamode");
573: $sub1="$space\:\:$sub";
574: ($currentstring,$nodefault) = &$sub1($target,$token,$tagstack,
575: $parstack,$parser,$safeeval,
576: $style);
577: } else {
578: if ($target eq 'tex') {
579: # throw away tag name
580: return '';
581: }
582: #&Apache::lonxml::debug("NOT Calling sub $sub in $space $metamode");
583: if ($metamode <1) {
584: if (defined($token->[4]) && ($metamode < 1)) {
585: $currentstring = $token->[4];
586: } else {
587: $currentstring = $token->[2];
588: }
589: }
590: }
591: # &Apache::lonxml::debug("nodefalt:$nodefault:");
592: if ($currentstring eq '' && $nodefault eq '') {
593: if ($target eq 'edit') {
594: #&Apache::lonxml::debug("doing default edit for $token->[1]");
595: if ($token->[0] eq 'S') {
596: $currentstring = &Apache::edit::tag_start($target,$token);
597: } elsif ($token->[0] eq 'E') {
598: $currentstring = &Apache::edit::tag_end($target,$token);
599: }
600: } elsif ($target eq 'modified') {
601: if ($token->[0] eq 'S') {
602: $currentstring = $token->[4];
603: $currentstring.=&Apache::edit::handle_insert();
604: } elsif ($token->[0] eq 'E') {
605: $currentstring = $token->[2];
606: $currentstring.=&Apache::edit::handle_insertafter($token->[1]);
607: } else {
608: $currentstring = $token->[2];
609: }
610: }
611: }
612: }
613: use strict 'refs';
614: }
615: return $currentstring;
616: }
617:
618: sub setup_globals {
619: my ($request,$target)=@_;
620: $Apache::lonxml::request=$request;
621: $Apache::lonxml::registered = 0;
622: @Apache::lonxml::htmlareafields=();
623: $errorcount=0;
624: $warningcount=0;
625: $Apache::lonxml::default_homework_loaded=0;
626: $Apache::lonxml::usestyle=1;
627: &init_counter();
628: @Apache::lonxml::pwd=();
629: @Apache::lonxml::extlinks=();
630: @Apache::lonxml::ssi_info=();
631: $Apache::lonxml::post_evaluate=1;
632: $Apache::lonxml::warnings_error_header='';
633: if ($target eq 'meta') {
634: $Apache::lonxml::redirection = 0;
635: $Apache::lonxml::metamode = 1;
636: $Apache::lonxml::evaluate = 1;
637: $Apache::lonxml::import = 0;
638: } elsif ($target eq 'answer') {
639: $Apache::lonxml::redirection = 0;
640: $Apache::lonxml::metamode = 1;
641: $Apache::lonxml::evaluate = 1;
642: $Apache::lonxml::import = 1;
643: } elsif ($target eq 'grade') {
644: &startredirection;
645: $Apache::lonxml::metamode = 0;
646: $Apache::lonxml::evaluate = 1;
647: $Apache::lonxml::import = 1;
648: } elsif ($target eq 'modified') {
649: $Apache::lonxml::redirection = 0;
650: $Apache::lonxml::metamode = 0;
651: $Apache::lonxml::evaluate = 0;
652: $Apache::lonxml::import = 0;
653: } elsif ($target eq 'edit') {
654: $Apache::lonxml::redirection = 0;
655: $Apache::lonxml::metamode = 0;
656: $Apache::lonxml::evaluate = 0;
657: $Apache::lonxml::import = 0;
658: } elsif ($target eq 'analyze') {
659: $Apache::lonxml::redirection = 0;
660: $Apache::lonxml::metamode = 0;
661: $Apache::lonxml::evaluate = 1;
662: $Apache::lonxml::import = 1;
663: } else {
664: $Apache::lonxml::redirection = 0;
665: $Apache::lonxml::metamode = 0;
666: $Apache::lonxml::evaluate = 1;
667: $Apache::lonxml::import = 1;
668: }
669: }
670:
671: sub init_safespace {
672: my ($target,$safeeval,$safehole,$safeinit) = @_;
673: $safeeval->permit("entereval");
674: $safeeval->permit(":base_math");
675: $safeeval->permit("sort");
676: $safeeval->permit("time");
677: $safeeval->deny(":base_io");
678: $safehole->wrap(\&Apache::scripttag::xmlparse,$safeeval,'&xmlparse');
679: $safehole->wrap(\&Apache::outputtags::multipart,$safeeval,'&multipart');
680: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
681: $safehole->wrap(\&Apache::chemresponse::chem_standard_order,$safeeval,
682: '&chem_standard_order');
683:
684: $safehole->wrap(\&Math::Cephes::asin,$safeeval,'&asin');
685: $safehole->wrap(\&Math::Cephes::acos,$safeeval,'&acos');
686: $safehole->wrap(\&Math::Cephes::atan,$safeeval,'&atan');
687: $safehole->wrap(\&Math::Cephes::sinh,$safeeval,'&sinh');
688: $safehole->wrap(\&Math::Cephes::cosh,$safeeval,'&cosh');
689: $safehole->wrap(\&Math::Cephes::tanh,$safeeval,'&tanh');
690: $safehole->wrap(\&Math::Cephes::asinh,$safeeval,'&asinh');
691: $safehole->wrap(\&Math::Cephes::acosh,$safeeval,'&acosh');
692: $safehole->wrap(\&Math::Cephes::atanh,$safeeval,'&atanh');
693: $safehole->wrap(\&Math::Cephes::erf,$safeeval,'&erf');
694: $safehole->wrap(\&Math::Cephes::erfc,$safeeval,'&erfc');
695: $safehole->wrap(\&Math::Cephes::j0,$safeeval,'&j0');
696: $safehole->wrap(\&Math::Cephes::j1,$safeeval,'&j1');
697: $safehole->wrap(\&Math::Cephes::jn,$safeeval,'&jn');
698: $safehole->wrap(\&Math::Cephes::jv,$safeeval,'&jv');
699: $safehole->wrap(\&Math::Cephes::y0,$safeeval,'&y0');
700: $safehole->wrap(\&Math::Cephes::y1,$safeeval,'&y1');
701: $safehole->wrap(\&Math::Cephes::yn,$safeeval,'&yn');
702: $safehole->wrap(\&Math::Cephes::yv,$safeeval,'&yv');
703:
704: $safehole->wrap(\&Math::Cephes::bdtr ,$safeeval,'&bdtr' );
705: $safehole->wrap(\&Math::Cephes::bdtrc ,$safeeval,'&bdtrc' );
706: $safehole->wrap(\&Math::Cephes::bdtri ,$safeeval,'&bdtri' );
707: $safehole->wrap(\&Math::Cephes::btdtr ,$safeeval,'&btdtr' );
708: $safehole->wrap(\&Math::Cephes::chdtr ,$safeeval,'&chdtr' );
709: $safehole->wrap(\&Math::Cephes::chdtrc,$safeeval,'&chdtrc');
710: $safehole->wrap(\&Math::Cephes::chdtri,$safeeval,'&chdtri');
711: $safehole->wrap(\&Math::Cephes::fdtr ,$safeeval,'&fdtr' );
712: $safehole->wrap(\&Math::Cephes::fdtrc ,$safeeval,'&fdtrc' );
713: $safehole->wrap(\&Math::Cephes::fdtri ,$safeeval,'&fdtri' );
714: $safehole->wrap(\&Math::Cephes::gdtr ,$safeeval,'&gdtr' );
715: $safehole->wrap(\&Math::Cephes::gdtrc ,$safeeval,'&gdtrc' );
716: $safehole->wrap(\&Math::Cephes::nbdtr ,$safeeval,'&nbdtr' );
717: $safehole->wrap(\&Math::Cephes::nbdtrc,$safeeval,'&nbdtrc');
718: $safehole->wrap(\&Math::Cephes::nbdtri,$safeeval,'&nbdtri');
719: $safehole->wrap(\&Math::Cephes::ndtr ,$safeeval,'&ndtr' );
720: $safehole->wrap(\&Math::Cephes::ndtri ,$safeeval,'&ndtri' );
721: $safehole->wrap(\&Math::Cephes::pdtr ,$safeeval,'&pdtr' );
722: $safehole->wrap(\&Math::Cephes::pdtrc ,$safeeval,'&pdtrc' );
723: $safehole->wrap(\&Math::Cephes::pdtri ,$safeeval,'&pdtri' );
724: $safehole->wrap(\&Math::Cephes::stdtr ,$safeeval,'&stdtr' );
725: $safehole->wrap(\&Math::Cephes::stdtri,$safeeval,'&stdtri');
726:
727: # $safehole->wrap(\&Math::Cephes::new_fract,$safeeval,'&new_fract');
728: # $safehole->wrap(\&Math::Cephes::radd,$safeeval,'&radd');
729: # $safehole->wrap(\&Math::Cephes::rsub,$safeeval,'&rsub');
730: # $safehole->wrap(\&Math::Cephes::rmul,$safeeval,'&rmul');
731: # $safehole->wrap(\&Math::Cephes::rdiv,$safeeval,'&rdiv');
732: # $safehole->wrap(\&Math::Cephes::euclid,$safeeval,'&euclid');
733:
734: $safehole->wrap(\&Math::Random::random_beta,$safeeval,'&math_random_beta');
735: $safehole->wrap(\&Math::Random::random_chi_square,$safeeval,'&math_random_chi_square');
736: $safehole->wrap(\&Math::Random::random_exponential,$safeeval,'&math_random_exponential');
737: $safehole->wrap(\&Math::Random::random_f,$safeeval,'&math_random_f');
738: $safehole->wrap(\&Math::Random::random_gamma,$safeeval,'&math_random_gamma');
739: $safehole->wrap(\&Math::Random::random_multivariate_normal,$safeeval,'&math_random_multivariate_normal');
740: $safehole->wrap(\&Math::Random::random_multinomial,$safeeval,'&math_random_multinomial');
741: $safehole->wrap(\&Math::Random::random_noncentral_chi_square,$safeeval,'&math_random_noncentral_chi_square');
742: $safehole->wrap(\&Math::Random::random_noncentral_f,$safeeval,'&math_random_noncentral_f');
743: $safehole->wrap(\&Math::Random::random_normal,$safeeval,'&math_random_normal');
744: $safehole->wrap(\&Math::Random::random_permutation,$safeeval,'&math_random_permutation');
745: $safehole->wrap(\&Math::Random::random_permuted_index,$safeeval,'&math_random_permuted_index');
746: $safehole->wrap(\&Math::Random::random_uniform,$safeeval,'&math_random_uniform');
747: $safehole->wrap(\&Math::Random::random_poisson,$safeeval,'&math_random_poisson');
748: $safehole->wrap(\&Math::Random::random_uniform_integer,$safeeval,'&math_random_uniform_integer');
749: $safehole->wrap(\&Math::Random::random_negative_binomial,$safeeval,'&math_random_negative_binomial');
750: $safehole->wrap(\&Math::Random::random_binomial,$safeeval,'&math_random_binomial');
751: $safehole->wrap(\&Math::Random::random_seed_from_phrase,$safeeval,'&random_seed_from_phrase');
752: $safehole->wrap(\&Math::Random::random_set_seed_from_phrase,$safeeval,'&random_set_seed_from_phrase');
753: $safehole->wrap(\&Math::Random::random_get_seed,$safeeval,'&random_get_seed');
754: $safehole->wrap(\&Math::Random::random_set_seed,$safeeval,'&random_set_seed');
755: $safehole->wrap(\&Apache::lonxml::error,$safeeval,'&LONCAPA_INTERNAL_ERROR');
756: $safehole->wrap(\&Apache::lonxml::debug,$safeeval,'&LONCAPA_INTERNAL_DEBUG');
757: $safehole->wrap(\&Apache::caparesponse::get_sigrange,$safeeval,'&LONCAPA_INTERNAL_get_sigrange');
758:
759: #need to inspect this class of ops
760: # $safeeval->deny(":base_orig");
761: $safeeval->permit("require");
762: $safeinit .= ';$external::target="'.$target.'";';
763: my $rndseed;
764: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
765: $rndseed=&Apache::lonnet::rndseed($symb,$courseid,$domain,$name);
766: $safeinit .= ';$external::randomseed="'.$rndseed.'";';
767: &Apache::lonxml::debug("Setting rndseed to $rndseed");
768: &Apache::run::run($safeinit,$safeeval);
769:
770: }
771:
772: sub default_homework_load {
773: my ($safeeval)=@_;
774: &Apache::lonxml::debug('Loading default_homework');
775: my $default=&Apache::lonnet::getfile('/home/httpd/html/res/adm/includes/default_homework.lcpm');
776: if ($default eq -1) {
777: &Apache::lonxml::error("<b>Unable to find <i>default_homework.lcpm</i></b>");
778: } else {
779: &Apache::run::run($default,$safeeval);
780: $Apache::lonxml::default_homework_loaded=1;
781: }
782: }
783:
784: my $metamode_was;
785: sub startredirection {
786: if (!$Apache::lonxml::redirection) {
787: $metamode_was=$Apache::lonxml::metamode;
788: }
789: $Apache::lonxml::metamode=0;
790: $Apache::lonxml::redirection++;
791: push (@Apache::lonxml::outputstack, '');
792: }
793:
794: sub endredirection {
795: if (!$Apache::lonxml::redirection) {
796: &Apache::lonxml::error("Endredirection was called, before a startredirection, perhaps you have unbalanced tags. Some debuging information:".join ":",caller);
797: return '';
798: }
799: $Apache::lonxml::redirection--;
800: if (!$Apache::lonxml::redirection) {
801: $Apache::lonxml::metamode=$metamode_was;
802: }
803: pop @Apache::lonxml::outputstack;
804: }
805:
806: sub end_tag {
807: my ($tagstack,$parstack,$token)=@_;
808: pop(@$tagstack);
809: pop(@$parstack);
810: &decreasedepth($token);
811: }
812:
813: sub initdepth {
814: @Apache::lonxml::depthcounter=();
815: $Apache::lonxml::depth=-1;
816: $Apache::lonxml::olddepth=-1;
817: }
818:
819: my @timers;
820: my $lasttime;
821: sub increasedepth {
822: my ($token) = @_;
823: $Apache::lonxml::depth++;
824: $Apache::lonxml::depthcounter[$Apache::lonxml::depth]++;
825: if ($Apache::lonxml::depthcounter[$Apache::lonxml::depth]==1) {
826: $Apache::lonxml::olddepth=$Apache::lonxml::depth;
827: }
828: my $time;
829: if ($Apache::lonxml::debug eq "1") {
830: push(@timers,[&gettimeofday()]);
831: $time=&tv_interval($lasttime);
832: $lasttime=[&gettimeofday()];
833: }
834: my $spacing=' 'x($Apache::lonxml::depth-1);
835: my $curdepth=join('_',@Apache::lonxml::depthcounter);
836: &Apache::lonxml::debug("s$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1] : $time : \n");
837: #print "<br />s $Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1]\n";
838: }
839:
840: sub decreasedepth {
841: my ($token) = @_;
842: $Apache::lonxml::depth--;
843: if ($Apache::lonxml::depth<$Apache::lonxml::olddepth-1) {
844: $#Apache::lonxml::depthcounter--;
845: $Apache::lonxml::olddepth=$Apache::lonxml::depth+1;
846: }
847: if ( $Apache::lonxml::depth < -1) {
848: &Apache::lonxml::warning(&mt("Missing tags, unable to properly run file."));
849: $Apache::lonxml::depth='-1';
850: }
851: my ($timer,$time);
852: if ($Apache::lonxml::debug eq "1") {
853: $timer=pop(@timers);
854: $time=&tv_interval($lasttime);
855: $lasttime=[&gettimeofday()];
856: }
857: my $spacing=' 'x$Apache::lonxml::depth;
858: my $curdepth=join('_',@Apache::lonxml::depthcounter);
859: &Apache::lonxml::debug("e$spacing$Apache::lonxml::depth : $Apache::lonxml::olddepth : $curdepth : $token->[1] : $time : ".&tv_interval($timer)."\n");
860: #print "<br />e $Apache::lonxml::depth : $Apache::lonxml::olddepth : $token->[1] : $curdepth\n";
861: }
862:
863: sub get_all_text_unbalanced {
864: #there is a copy of this in lonpublisher.pm
865: my($tag,$pars)= @_;
866: my $token;
867: my $result='';
868: $tag='<'.$tag.'>';
869: while ($token = $$pars[-1]->get_token) {
870: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
871: $result.=$token->[1];
872: } elsif ($token->[0] eq 'PI') {
873: $result.=$token->[2];
874: } elsif ($token->[0] eq 'S') {
875: $result.=$token->[4];
876: } elsif ($token->[0] eq 'E') {
877: $result.=$token->[2];
878: }
879: if ($result =~ /\Q$tag\E/is) {
880: ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
881: #&Apache::lonxml::debug('Got a winner with leftovers ::'.$2);
882: #&Apache::lonxml::debug('Result is :'.$1);
883: $redo=$tag.$redo;
884: &Apache::lonxml::newparser($pars,\$redo);
885: last;
886: }
887: }
888: return $result
889: }
890:
891: sub increment_counter {
892: my ($increment) = @_;
893: if (defined($increment) && $increment gt 0) {
894: $Apache::lonxml::counter+=$increment;
895: } else {
896: $Apache::lonxml::counter++;
897: }
898: $Apache::lonxml::counter_changed=1;
899: }
900:
901: sub init_counter {
902: if (defined($ENV{'form.counter'})) {
903: $Apache::lonxml::counter=$ENV{'form.counter'};
904: $Apache::lonxml::counter_changed=0;
905: } else {
906: $Apache::lonxml::counter=1;
907: $Apache::lonxml::counter_changed=1;
908: }
909: }
910:
911: sub store_counter {
912: &Apache::lonnet::appenv(('form.counter' => $Apache::lonxml::counter));
913: return '';
914: }
915:
916: sub get_all_text {
917: my($tag,$pars,$style)= @_;
918: my $gotfullstack=1;
919: if (ref($pars) ne 'ARRAY') {
920: $gotfullstack=0;
921: $pars=[$pars];
922: }
923: if (ref($style) ne 'HASH') {
924: $style={};
925: }
926: my $depth=0;
927: my $token;
928: my $result='';
929: if ( $tag =~ m:^/: ) {
930: my $tag=substr($tag,1);
931: #&Apache::lonxml::debug("have:$tag:");
932: my $top_empty=0;
933: while (($depth >=0) && ($#$pars > -1) && (!$top_empty)) {
934: while (($depth >=0) && ($token = $$pars[-1]->get_token)) {
935: #&Apache::lonxml::debug("e token:$token->[0]:$depth:$token->[1]:".$#$pars.":".$#Apache::lonxml::pwd);
936: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
937: $result.=$token->[1];
938: } elsif ($token->[0] eq 'PI') {
939: $result.=$token->[2];
940: } elsif ($token->[0] eq 'S') {
941: if ($token->[1] =~ /^\Q$tag\E$/i) { $depth++; }
942: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
943: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
944: $result.=$token->[4];
945: } elsif ($token->[0] eq 'E') {
946: if ( $token->[1] =~ /^\Q$tag\E$/i) { $depth--; }
947: #skip sending back the last end tag
948: if ($depth == 0 && exists($$style{'/'.$token->[1]}) && $Apache::lonxml::usestyle) {
949: my $string=
950: '<LONCAPA_INTERNAL_TURN_STYLE_OFF end="yes" />'.
951: $$style{'/'.$token->[1]}.
952: $token->[2].
953: '<LONCAPA_INTERNAL_TURN_STYLE_ON />';
954: &Apache::lonxml::newparser($pars,\$string);
955: #&Apache::lonxml::debug("reParsing $string");
956: next;
957: }
958: if ($depth > -1) {
959: $result.=$token->[2];
960: } else {
961: $$pars[-1]->unget_token($token);
962: }
963: }
964: }
965: if (($depth >=0) && ($#$pars == 0) ) { $top_empty=1; }
966: if (($depth >=0) && ($#$pars > 0) ) {
967: pop(@$pars);
968: pop(@Apache::lonxml::pwd);
969: }
970: }
971: if ($top_empty && $depth >= 0) {
972: #never found the end tag ran out of text, throw error send back blank
973: &error('Never found end tag for <'.$tag.
974: '> current string <pre>'.
975: &HTML::Entities::encode($result,'<>&"').
976: '</pre>');
977: if ($gotfullstack) {
978: my $newstring='</'.$tag.'>'.$result;
979: &Apache::lonxml::newparser($pars,\$newstring);
980: }
981: $result='';
982: }
983: } else {
984: while ($#$pars > -1) {
985: while ($token = $$pars[-1]->get_token) {
986: #&Apache::lonxml::debug("s token:$token->[0]:$depth:$token->[1]");
987: if (($token->[0] eq 'T')||($token->[0] eq 'C')||
988: ($token->[0] eq 'D')) {
989: $result.=$token->[1];
990: } elsif ($token->[0] eq 'PI') {
991: $result.=$token->[2];
992: } elsif ($token->[0] eq 'S') {
993: if ( $token->[1] =~ /^\Q$tag\E$/i) {
994: $$pars[-1]->unget_token($token); last;
995: } else {
996: $result.=$token->[4];
997: }
998: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_ON$/) { $Apache::lonxml::usestyle=1; }
999: if ($token->[1] =~ /^LONCAPA_INTERNAL_TURN_STYLE_OFF$/) { $Apache::lonxml::usestyle=0; }
1000: } elsif ($token->[0] eq 'E') {
1001: $result.=$token->[2];
1002: }
1003: }
1004: if (($#$pars > 0) ) {
1005: pop(@$pars);
1006: pop(@Apache::lonxml::pwd);
1007: } else { last; }
1008: }
1009: }
1010: #&Apache::lonxml::debug("Exit:$result:");
1011: return $result
1012: }
1013:
1014: sub newparser {
1015: my ($parser,$contentref,$dir) = @_;
1016: push (@$parser,HTML::LCParser->new($contentref));
1017: $$parser['-1']->xml_mode('1');
1018: if ( $dir eq '' ) {
1019: push (@Apache::lonxml::pwd, $Apache::lonxml::pwd[$#Apache::lonxml::pwd]);
1020: } else {
1021: push (@Apache::lonxml::pwd, $dir);
1022: }
1023: }
1024:
1025: sub parstring {
1026: my ($token) = @_;
1027: my $temp='';
1028: foreach (@{$token->[3]}) {
1029: unless ($_=~/\W/) {
1030: my $val=$token->[2]->{$_};
1031: $val =~ s/([\%\@\\\"\'])/\\$1/g;
1032: $val =~ s/(\$[^{a-zA-Z_])/\\$1/g;
1033: #if ($val =~ m/^[\%\@]/) { $val="\\".$val; }
1034: $temp .= "my \$$_=\"$val\";";
1035: }
1036: }
1037: return $temp;
1038: }
1039:
1040: sub writeallows {
1041: unless ($#extlinks>=0) { return; }
1042: my $thisurl='/res/'.&Apache::lonnet::declutter(shift);
1043: if ($ENV{'httpref.'.$thisurl}) {
1044: $thisurl=$ENV{'httpref.'.$thisurl};
1045: }
1046: my $thisdir=$thisurl;
1047: $thisdir=~s/\/[^\/]+$//;
1048: my %httpref=();
1049: foreach (@extlinks) {
1050: $httpref{'httpref.'.
1051: &Apache::lonnet::hreflocation($thisdir,$_)}=$thisurl;
1052: }
1053: @extlinks=();
1054: &Apache::lonnet::appenv(%httpref);
1055: }
1056:
1057: sub register_ssi {
1058: my ($url,%form)=@_;
1059: push (@Apache::lonxml::ssi_info,{'url'=>$url,'form'=>\%form});
1060: return '';
1061: }
1062:
1063: sub do_registered_ssi {
1064: foreach my $info (@Apache::lonxml::ssi_info) {
1065: my %form=%{ $info->{'form'}};
1066: my $url=$info->{'url'};
1067: &Apache::lonnet::ssi($url,%form);
1068: }
1069: }
1070: #
1071: # Afterburner handles anchors, highlights and links
1072: #
1073: sub afterburn {
1074: my $result=shift;
1075: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1076: ['highlight','anchor','link']);
1077: if ($ENV{'form.highlight'}) {
1078: foreach (split(/\,/,$ENV{'form.highlight'})) {
1079: my $anchorname=$_;
1080: my $matchthis=$anchorname;
1081: $matchthis=~s/\_+/\\s\+/g;
1082: $result=~s/(\Q$matchthis\E)/\<font color=\"red\"\>$1\<\/font\>/gs;
1083: }
1084: }
1085: if ($ENV{'form.link'}) {
1086: foreach (split(/\,/,$ENV{'form.link'})) {
1087: my ($anchorname,$linkurl)=split(/\>/,$_);
1088: my $matchthis=$anchorname;
1089: $matchthis=~s/\_+/\\s\+/g;
1090: $result=~s/(\Q$matchthis\E)/\<a href=\"$linkurl\"\>$1\<\/a\>/gs;
1091: }
1092: }
1093: if ($ENV{'form.anchor'}) {
1094: my $anchorname=$ENV{'form.anchor'};
1095: my $matchthis=$anchorname;
1096: $matchthis=~s/\_+/\\s\+/g;
1097: $result=~s/(\Q$matchthis\E)/\<a name=\"$anchorname\"\>$1\<\/a\>/s;
1098: $result.=(<<"ENDSCRIPT");
1099: <script type="text/javascript">
1100: document.location.hash='$anchorname';
1101: </script>
1102: ENDSCRIPT
1103: }
1104: return $result;
1105: }
1106:
1107: sub storefile {
1108: my ($file,$contents)=@_;
1109: &Apache::lonnet::correct_line_ends(\$contents);
1110: if (my $fh=Apache::File->new('>'.$file)) {
1111: print $fh $contents;
1112: $fh->close();
1113: return 1;
1114: } else {
1115: &warning("Unable to save file $file");
1116: return 0;
1117: }
1118: }
1119:
1120: sub createnewhtml {
1121: my $title=&mt('Title of document goes here');
1122: my $body=&mt('Body of document goes here');
1123: my $filecontents=(<<SIMPLECONTENT);
1124: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml/11/DTD/xhtml11.dtd">
1125: <html>
1126: <head>
1127: <title>$title</title>
1128: </head>
1129: <body bgcolor="#FFFFFF">
1130: $body
1131: </body>
1132: </html>
1133: SIMPLECONTENT
1134: return $filecontents;
1135: }
1136:
1137: sub createnewsty {
1138: my $filecontents=(<<SIMPLECONTENT);
1139: <definetag name="">
1140: <render>
1141: <web></web>
1142: <tex></tex>
1143: </render>
1144: </definetag>
1145: SIMPLECONTENT
1146: return $filecontents;
1147: }
1148:
1149:
1150: sub inserteditinfo {
1151: my ($result,$filecontents,$filetype)=@_;
1152: $filecontents = &HTML::Entities::encode($filecontents,'<>&"');
1153: # my $editheader='<a href="#editsection">Edit below</a><hr />';
1154: my $xml_help = '';
1155: my $initialize='';
1156: if ($filetype eq 'html') {
1157: my $addbuttons=&Apache::lonhtmlcommon::htmlareaaddbuttons();
1158: $initialize=&Apache::lonhtmlcommon::htmlareaheaders().
1159: &Apache::lonhtmlcommon::spellheader().(<<FULLPAGE);
1160: <script type="text/javascript">
1161: $addbuttons
1162:
1163: HTMLArea.loadPlugin("FullPage");
1164:
1165: function initDocument() {
1166: var editor=new HTMLArea("filecont",config);
1167: editor.registerPlugin(FullPage);
1168: editor.generate();
1169: }
1170: </script>
1171: FULLPAGE
1172: $result=~s/\<body([^\>]*)\>/\<body onload="initDocument()" $1\>/i;
1173: $xml_help=&Apache::loncommon::helpLatexCheatsheet();
1174: }
1175: my $cleanbut = '';
1176: if ($filetype eq 'html') {
1177: $cleanbut='<input type="submit" name="attemptclean" value="'.
1178: &mt('Save and then attempt to clean HTML').'" />';
1179: }
1180: my $titledisplay=&display_title();
1181: my %lt=&Apache::lonlocal::texthash('st' => 'Save this',
1182: 'vi' => 'View',
1183: 'ed' => 'Edit');
1184: my $buttons=(<<BUTTONS);
1185: $cleanbut
1186: <input type="submit" name="savethisfile" accesskey="s" value="$lt{'st'}" />
1187: <input type="submit" name="viewmode" accesskey="v" value="$lt{'vi'}" />
1188: BUTTONS
1189: $buttons.=&Apache::lonhtmlcommon::spelllink('xmledit','filecont');
1190: $buttons.=&Apache::lonhtmlcommon::htmlareaselectactive('filecont');
1191: my $editfooter=(<<ENDFOOTER);
1192: $initialize
1193: <hr />
1194: <a name="editsection" />
1195: <form method="post" name="xmledit">
1196: $xml_help
1197: <input type="hidden" name="editmode" value="$lt{'ed'}" />
1198: $buttons<br />
1199: <textarea cols="80" rows="44" name="filecont" id="filecont">$filecontents</textarea>
1200: <br />$buttons
1201: <br />
1202: </form>
1203: $titledisplay
1204: </body>
1205: ENDFOOTER
1206: # $result=~s/(\<body[^\>]*\>)/$1$editheader/is;
1207: $result=~s/(\<\/body\>)/$editfooter/is;
1208: return $result;
1209: }
1210:
1211: sub get_target {
1212: my $viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
1213: if ( $ENV{'request.state'} eq 'published') {
1214: if ( defined($ENV{'form.grade_target'})
1215: && ($viewgrades == 'F' )) {
1216: return ($ENV{'form.grade_target'});
1217: } elsif (defined($ENV{'form.grade_target'})) {
1218: if (($ENV{'form.grade_target'} eq 'web') ||
1219: ($ENV{'form.grade_target'} eq 'tex') ) {
1220: return $ENV{'form.grade_target'}
1221: } else {
1222: return 'web';
1223: }
1224: } else {
1225: return 'web';
1226: }
1227: } elsif ($ENV{'request.state'} eq 'construct') {
1228: if ( defined($ENV{'form.grade_target'})) {
1229: return ($ENV{'form.grade_target'});
1230: } else {
1231: return 'web';
1232: }
1233: } else {
1234: return 'web';
1235: }
1236: }
1237:
1238: sub handler {
1239: my $request=shift;
1240:
1241: my $target=&get_target();
1242:
1243: $Apache::lonxml::debug=$ENV{'user.debug'};
1244:
1245: if ($ENV{'browser.mathml'}) {
1246: &Apache::loncommon::content_type($request,'text/xml');
1247: } else {
1248: &Apache::loncommon::content_type($request,'text/html');
1249: }
1250: &Apache::loncommon::no_cache($request);
1251: $request->send_http_header;
1252:
1253: return OK if $request->header_only;
1254:
1255:
1256: my $file=&Apache::lonnet::filelocation("",$request->uri);
1257: my $filetype;
1258: if ($file =~ /\.sty$/) {
1259: $filetype='sty';
1260: } else {
1261: $filetype='html';
1262: }
1263: #
1264: # Edit action? Save file.
1265: #
1266: unless ($ENV{'request.state'} eq 'published') {
1267: if (($ENV{'form.savethisfile'}) || ($ENV{'form.attemptclean'})) {
1268: if (&storefile($file,$ENV{'form.filecont'})) {
1269: &Apache::lonxml::info("<font COLOR=\"#0000FF\">".
1270: &mt('Updated').": ".
1271: &Apache::lonlocal::locallocaltime(time).
1272: " </font>");
1273: }
1274: }
1275: }
1276: my %mystyle;
1277: my $result = '';
1278: my $filecontents=&Apache::lonnet::getfile($file);
1279: if ($filecontents eq -1) {
1280: my $bodytag=&Apache::loncommon::bodytag('File Error');
1281: my $fnf=&mt('File not found');
1282: $result=(<<ENDNOTFOUND);
1283: <html>
1284: <head>
1285: <title>$fnf</title>
1286: </head>
1287: $bodytag
1288: <b>$fnf: $file</b>
1289: </body>
1290: </html>
1291: ENDNOTFOUND
1292: $filecontents='';
1293: if ($ENV{'request.state'} ne 'published') {
1294: if ($filetype eq 'sty') {
1295: $filecontents=&createnewsty();
1296: } else {
1297: $filecontents=&createnewhtml();
1298: }
1299: $ENV{'form.editmode'}='Edit'; #force edit mode
1300: }
1301: } else {
1302: unless ($ENV{'request.state'} eq 'published') {
1303: if ($filecontents=~/BEGIN LON-CAPA Internal/) {
1304: &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.'));
1305: }
1306:
1307: if ($ENV{'form.attemptclean'}) {
1308: $filecontents=&htmlclean($filecontents,1);
1309: }
1310: #
1311: # we are in construction space, see if edit mode forced
1312: &Apache::loncommon::get_unprocessed_cgi
1313: ($ENV{'QUERY_STRING'},['editmode']);
1314: }
1315: if (!$ENV{'form.editmode'} || $ENV{'form.viewmode'}) {
1316: $result = &Apache::lonxml::xmlparse($request,$target,$filecontents,
1317: '',%mystyle);
1318: }
1319: }
1320:
1321: #
1322: # Edit action? Insert editing commands
1323: #
1324: unless ($ENV{'request.state'} eq 'published') {
1325: if ($ENV{'form.editmode'} && (!($ENV{'form.viewmode'}))) {
1326: my $displayfile=$request->uri;
1327: $displayfile=~s/^\/[^\/]*//;
1328: $result='<html><body bgcolor="#FFFFFF">'.
1329: &Apache::lonxml::message_location().'<h3>'.
1330: $displayfile.
1331: '</h3></body></html>';
1332: $result=&inserteditinfo($result,$filecontents,$filetype);
1333: }
1334: }
1335: if ($filetype eq 'html') { writeallows($request->uri); }
1336:
1337:
1338: &Apache::lonxml::add_messages(\$result);
1339: $request->print($result);
1340:
1341: return OK;
1342: }
1343:
1344: sub display_title {
1345: my $result;
1346: if ($ENV{'request.state'} eq 'construct') {
1347: my $title=&Apache::lonnet::gettitle();
1348: if (!defined($title) || $title eq '') {
1349: $title = $ENV{'request.filename'};
1350: $title = substr($title, rindex($title, '/') + 1);
1351: }
1352: $result = "<script type='text/javascript'>top.document.title = '$title - LON-CAPA Construction Space';</script>";
1353: }
1354: return $result;
1355: }
1356:
1357: sub debug {
1358: if ($Apache::lonxml::debug eq "1") {
1359: $|=1;
1360: my $request=$Apache::lonxml::request;
1361: if (!$request) { $request=Apache->request; }
1362: $request->print('<font size="-2"><pre>DEBUG:'.&HTML::Entities::encode($_[0],'<>&"')."</pre></font>\n");
1363: # &Apache::lonnet::logthis($_[0]);
1364: }
1365: }
1366:
1367: sub error {
1368: $errorcount++;
1369: if (($Apache::lonxml::debug eq 1) || ($ENV{'request.state'} eq 'construct') ) {
1370: # If printing in construction space, put the error inside <pre></pre>
1371: push(@Apache::lonxml::error_messages,
1372: $Apache::lonxml::warnings_error_header.
1373: "<b>ERROR:</b>".join("<br />\n",@_)."<br />\n");
1374: $Apache::lonxml::warnings_error_header='';
1375: } else {
1376: my $errormsg;
1377: my ($symb)=&Apache::lonnet::symbread();
1378: if ( !$symb ) {
1379: #public or browsers
1380: $errormsg=&mt("An error occured while processing this resource. The author has been notified.");
1381: }
1382: #notify author
1383: &Apache::lonmsg::author_res_msg($ENV{'request.filename'},join('<br />',@_));
1384: #notify course
1385: if ( $symb && $ENV{'request.course.id'} ) {
1386: my (undef,%users)=&Apache::lonfeedback::decide_receiver(undef,0,1,1,1);
1387: my $declutter=&Apache::lonnet::declutter($ENV{'request.filename'});
1388: my @userlist;
1389: foreach (keys %users) {
1390: my ($user,$domain) = split(/:/, $_);
1391: push(@userlist,"$user\@$domain");
1392: &Apache::lonmsg::user_normal_msg($user,$domain,
1393: "Error [$declutter]",join('<br />',@_));
1394: }
1395: if ($ENV{'request.role.adv'}) {
1396: $errormsg=&mt("An error occured while processing this resource. The course personnel ([_1]) and the author have been notified.",join(', ',@userlist));
1397: } else {
1398: $errormsg=&mt("An error occured while processing this resource. The instructor has been notified.");
1399: }
1400: }
1401: push(@Apache::lonxml::error_messages,"<b>$errormsg</b> <br />");
1402: }
1403: }
1404:
1405: sub warning {
1406: $warningcount++;
1407:
1408: if ($ENV{'form.grade_target'} ne 'tex') {
1409: if ($ENV{'request.state'} eq 'construct' || $Apache::lonxml::debug) {
1410: my $request=$Apache::lonxml::request;
1411: if (!$request) { $request=Apache->request; }
1412: push(@Apache::lonxml::warning_messages,
1413: $Apache::lonxml::warnings_error_header.
1414: "<b>W</b>ARNING<b>:</b>".join('<br />',@_)."<br />\n");
1415: $Apache::lonxml::warnings_error_header='';
1416: }
1417: }
1418: }
1419:
1420: sub info {
1421: if ($ENV{'form.grade_target'} ne 'tex'
1422: && $ENV{'request.state'} eq 'construct') {
1423: push(@Apache::lonxml::info_messages,join('<br />',@_)."<br />\n");
1424: }
1425: }
1426:
1427: sub message_location {
1428: return '__LONCAPA_INTERNAL_MESSAGE_LOCATION__';
1429: }
1430:
1431: sub add_messages {
1432: my ($msg)=@_;
1433: my $result=join(' ',
1434: @Apache::lonxml::info_messages,
1435: @Apache::lonxml::error_messages,
1436: @Apache::lonxml::warning_messages);
1437: undef(@Apache::lonxml::info_messages);
1438: undef(@Apache::lonxml::error_messages);
1439: undef(@Apache::lonxml::warning_messages);
1440: $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__/$result/;
1441: $$msg=~s/__LONCAPA_INTERNAL_MESSAGE_LOCATION__//g;
1442: }
1443:
1444: sub get_param {
1445: my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1446: if ( ! $context ) { $context = -1; }
1447: my $args ='';
1448: if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1449: if ( ! $Apache::lonxml::usestyle ) {
1450: $args=$Apache::lonxml::style_values.$args;
1451: }
1452: if ( ! $args ) { return undef; }
1453: if ( $case_insensitive ) {
1454: if ($args =~ s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei) {
1455: return &Apache::run::run("{$args;".'return $'.$param.'}',
1456: $safeeval); #'
1457: } else {
1458: return undef;
1459: }
1460: } else {
1461: if ( $args =~ /my \$\Q$param\E=\"/ ) {
1462: return &Apache::run::run("{$args;".'return $'.$param.'}',
1463: $safeeval); #'
1464: } else {
1465: return undef;
1466: }
1467: }
1468: }
1469:
1470: sub get_param_var {
1471: my ($param,$parstack,$safeeval,$context,$case_insensitive) = @_;
1472: if ( ! $context ) { $context = -1; }
1473: my $args ='';
1474: if ( $#$parstack > (-2-$context) ) { $args=$$parstack[$context]; }
1475: if ( ! $Apache::lonxml::usestyle ) {
1476: $args=$Apache::lonxml::style_values.$args;
1477: }
1478: &Apache::lonxml::debug("Args are $args param is $param");
1479: if ($case_insensitive) {
1480: if (! ($args=~s/(my \$)(\Q$param\E)(=\")/$1.lc($2).$3/ei)) {
1481: return undef;
1482: }
1483: } elsif ( $args !~ /my \$\Q$param\E=\"/ ) { return undef; }
1484: my $value=&Apache::run::run("{$args;".'return $'.$param.'}',$safeeval); #'
1485: &Apache::lonxml::debug("first run is $value");
1486: if ($value =~ /^[\$\@\%][a-zA-Z_]\w*$/) {
1487: &Apache::lonxml::debug("doing second");
1488: my @result=&Apache::run::run("return $value",$safeeval,1);
1489: if (!defined($result[0])) {
1490: return $value
1491: } else {
1492: if (wantarray) { return @result; } else { return $result[0]; }
1493: }
1494: } else {
1495: return $value;
1496: }
1497: }
1498:
1499: sub register_insert {
1500: my @data = split /\n/, &Apache::lonnet::getfile('/home/httpd/lonTabs/insertlist.tab');
1501: my $i;
1502: my $tagnum=0;
1503: my @order;
1504: for ($i=0;$i < $#data; $i++) {
1505: my $line = $data[$i];
1506: if ( $line =~ /^\#/ || $line =~ /^\s*\n/) { next; }
1507: if ( $line =~ /TABLE/ ) { last; }
1508: my ($tag,$descrip,$color,$function,$show,$helpfile,$helpdesc) = split(/,/, $line);
1509: if ($tag) {
1510: $insertlist{"$tagnum.tag"} = $tag;
1511: $insertlist{"$tagnum.description"} = $descrip;
1512: $insertlist{"$tagnum.color"} = $color;
1513: $insertlist{"$tagnum.function"} = $function;
1514: if (!defined($show)) { $show='yes'; }
1515: $insertlist{"$tagnum.show"}= $show;
1516: $insertlist{"$tagnum.helpfile"} = $helpfile;
1517: $insertlist{"$tagnum.helpdesc"} = $helpdesc;
1518: $insertlist{"$tag.num"}=$tagnum;
1519: $tagnum++;
1520: }
1521: }
1522: $i++; #skipping TABLE line
1523: $tagnum = 0;
1524: for (;$i < $#data;$i++) {
1525: my $line = $data[$i];
1526: my ($mnemonic,@which) = split(/ +/,$line);
1527: my $tag = $insertlist{"$tagnum.tag"};
1528: for (my $j=0;$j <=$#which;$j++) {
1529: if ( $which[$j] eq 'Y' ) {
1530: if ($insertlist{"$j.show"} ne 'no') {
1531: push(@{ $insertlist{"$tag.which"} },$j);
1532: }
1533: }
1534: }
1535: $tagnum++;
1536: }
1537: }
1538:
1539: sub description {
1540: my ($token)=@_;
1541: my $tagnum;
1542: my $tag=$token->[1];
1543: foreach my $namespace (reverse @Apache::lonxml::namespace) {
1544: my $testtag=$namespace.'::'.$tag;
1545: $tagnum=$insertlist{"$testtag.num"};
1546: if (defined($tagnum)) { last; }
1547: }
1548: if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
1549: return $insertlist{$tagnum.'.description'};
1550: }
1551:
1552: # Returns a list containing the help file, and the description
1553: sub helpinfo {
1554: my ($token)=@_;
1555: my $tagnum;
1556: my $tag=$token->[1];
1557: foreach my $namespace (reverse @Apache::lonxml::namespace) {
1558: my $testtag=$namespace.'::'.$tag;
1559: $tagnum=$insertlist{"$testtag.num"};
1560: if (defined($tagnum)) { last; }
1561: }
1562: if (!defined ($tagnum)) { $tagnum=$Apache::lonxml::insertlist{"$tag.num"}; }
1563: return ($insertlist{$tagnum.'.helpfile'}, $insertlist{$tagnum.'.helpdesc'});
1564: }
1565:
1566: # ----------------------------------------------------------------- whichuser
1567: # returns a list of $symb, $courseid, $domain, $name that is correct for
1568: # calls to lonnet functions for this setup.
1569: # - looks for form.grade_ parameters
1570: sub whichuser {
1571: my ($passedsymb)=@_;
1572: my ($symb,$courseid,$domain,$name,$publicuser);
1573: if (defined($ENV{'form.grade_symb'})) {
1574: my $tmp_courseid=$ENV{'form.grade_courseid'};
1575: my $allowed=&Apache::lonnet::allowed('vgr',$tmp_courseid);
1576: if (!$allowed &&
1577: exists($ENV{'request.course.sec'}) &&
1578: $ENV{'request.course.sec'} !~ /^\s*$/) {
1579: $allowed=&Apache::lonnet::allowed('vgr',$ENV{'form.grade_courseid'}.
1580: '/'.$ENV{'request.course.sec'});
1581: }
1582: if ($allowed) {
1583: $symb=$ENV{'form.grade_symb'};
1584: $courseid=$ENV{'form.grade_courseid'};
1585: $domain=$ENV{'form.grade_domain'};
1586: $name=$ENV{'form.grade_username'};
1587: }
1588: } else {
1589: if (!$passedsymb) {
1590: $symb=&Apache::lonnet::symbread();
1591: } else {
1592: $symb=$passedsymb;
1593: }
1594: $courseid=$ENV{'request.course.id'};
1595: $domain=$ENV{'user.domain'};
1596: $name=$ENV{'user.name'};
1597: if ($name eq 'public' && $domain eq 'public') {
1598: if (!defined($ENV{'form.username'})) {
1599: $ENV{'form.username'}.=time.rand(10000000);
1600: }
1601: $name.=$ENV{'form.username'};
1602: }
1603: }
1604: return ($symb,$courseid,$domain,$name,$publicuser);
1605: }
1606:
1607: 1;
1608: __END__
1609:
1610:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>