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