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