1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Homework handler
3: #
4: # $Id: lonhomework.pm,v 1.165 2004/02/16 17:20:39 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:
29: package Apache::lonhomework;
30: use strict;
31: use Apache::style();
32: use Apache::lonxml();
33: use Apache::lonnet();
34: use Apache::lonplot();
35: use Apache::inputtags();
36: use Apache::structuretags();
37: use Apache::randomlabel();
38: use Apache::response();
39: use Apache::hint();
40: use Apache::outputtags();
41: use Apache::caparesponse();
42: use Apache::radiobuttonresponse();
43: use Apache::optionresponse();
44: use Apache::imageresponse();
45: use Apache::essayresponse();
46: use Apache::externalresponse();
47: use Apache::rankresponse();
48: use Apache::matchresponse();
49: use Apache::chemresponse();
50: use Apache::Constants qw(:common);
51: use HTML::Entities();
52: use Apache::loncommon();
53: use Apache::lonlocal;
54: #use Time::HiRes qw( gettimeofday tv_interval );
55:
56: BEGIN {
57: &Apache::lonxml::register_insert();
58: }
59:
60: sub get_target {
61: if (($ENV{'request.state'} eq "published") ||
62: ($ENV{'request.state'} eq "uploaded")) {
63: if ( defined($ENV{'form.grade_target'} )
64: && ($ENV{'form.grade_target'} eq 'tex')) {
65: return ($ENV{'form.grade_target'});
66: } elsif ( defined($ENV{'form.grade_target'} )
67: && ($Apache::lonhomework::viewgrades eq 'F' )) {
68: return ($ENV{'form.grade_target'});
69: }
70:
71: if ( defined($ENV{'form.submitted'}) &&
72: ( !defined($ENV{'form.resetdata'})) &&
73: ( !defined($ENV{'form.newrandomization'}))) {
74: return ('grade', 'web');
75: } else {
76: return ('web');
77: }
78: } elsif ($ENV{'request.state'} eq "construct") {
79: if ( defined($ENV{'form.grade_target'}) ) {
80: return ($ENV{'form.grade_target'});
81: }
82: if ( defined($ENV{'form.preview'})) {
83: if ( defined($ENV{'form.submitted'})) {
84: return ('grade', 'web');
85: } else {
86: return ('web');
87: }
88: } else {
89: if ( $ENV{'form.problemmode'} eq &mt('View') ||
90: $ENV{'form.problemmode'} eq &mt('Discard Edits and View')) {
91: if ( defined($ENV{'form.submitted'}) &&
92: (!defined($ENV{'form.resetdata'})) &&
93: (!defined($ENV{'form.newrandomization'}))) {
94: return ('grade', 'web','answer');
95: } else {
96: return ('web','answer');
97: }
98: } elsif ( $ENV{'form.problemmode'} eq &mt('Edit') ) {
99: if ( $ENV{'form.submitted'} eq 'edit' ) {
100: if ( $ENV{'form.submit'} eq &mt('Submit Changes and View') ) {
101: return ('modified','web','answer');
102: } else {
103: return ('modified','edit');
104: }
105: } else {
106: return ('edit');
107: }
108: } else {
109: return ('web');
110: }
111: }
112: }
113: return ();
114: }
115:
116: sub setup_vars {
117: my ($target) = @_;
118: return ';'
119: # return ';$external::target='.$target.';';
120: }
121:
122: sub send_header {
123: my ($request)= @_;
124: $request->print(&Apache::lontexconvert::header());
125: # $request->print('<form name='.$ENV{'form.request.prefix'}.'lonhomework method="POST" action="'.$request->uri.'">');
126: }
127:
128: sub createmenu {
129: my ($which,$request)=@_;
130: if ($which eq 'grade') {
131: $request->print('<script language="JavaScript">
132: hwkmenu=window.open("/res/adm/pages/homeworkmenu.html","homeworkremote",
133: "height=350,width=150,menubar=no");
134: </script>');
135: }
136: }
137:
138: sub send_footer {
139: my ($request)= @_;
140: # $request->print('</form>');
141: $request->print(&Apache::lontexconvert::footer());
142: }
143:
144: $Apache::lonxml::browse='';
145:
146: sub check_ip_acc {
147: my ($acc)=@_;
148: if (!defined($acc) || $acc =~ /^\s*$/) { return 1; }
149: my $allowed=0;
150: my $ip=$ENV{'REMOTE_ADDR'};
151: my $name;
152: foreach my $pattern (split(',',$acc)) {
153: if ($pattern =~ /\*$/) {
154: #35.8.*
155: $pattern=~s/\*//;
156: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
157: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
158: #35.8.3.[34-56]
159: my $low=$2;
160: my $high=$3;
161: $pattern=$1;
162: if ($ip =~ /^\Q$pattern\E/) {
163: my $last=(split(/\./,$ip))[3];
164: if ($last <=$high && $last >=$low) { $allowed=1; }
165: }
166: } elsif ($pattern =~ /^\*/) {
167: #*.msu.edu
168: $pattern=~s/\*//;
169: if (!defined($name)) {
170: use Socket;
171: my $netaddr=inet_aton($ip);
172: ($name)=gethostbyaddr($netaddr,AF_INET);
173: }
174: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
175: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
176: #127.0.0.1
177: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
178: } else {
179: #some.name.com
180: if (!defined($name)) {
181: use Socket;
182: my $netaddr=inet_aton($ip);
183: ($name)=gethostbyaddr($netaddr,AF_INET);
184: }
185: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
186: }
187: if ($allowed) { last; }
188: }
189: return $allowed;
190: }
191: # JB, 9/24/2002: Any changes in this function may require a change
192: # in lonnavmaps::resource::getDateStatus.
193: sub check_access {
194: my ($id) = @_;
195: my $date ='';
196: my $status;
197: my $datemsg = '';
198: my $lastdate = '';
199: my $temp;
200: my $type;
201: my $passed;
202:
203: if ($ENV{'request.state'} eq "construct") {
204: if (defined($ENV{'form.problemstatus'})) {
205: if ($ENV{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
206: return ('CANNOT_ANSWER','is in this state by royal decree.');
207: } else {
208: return ($ENV{'form.problemstate'},
209: 'is in this state by royal decree.');
210: }
211: }
212: &Apache::lonxml::debug("in construction ignoring dates");
213: $status='CAN_ANSWER';
214: $datemsg=&mt('is in under construction');
215: # return ($status,$datemsg);
216: }
217:
218: &Apache::lonxml::debug("checking for part :$id:");
219: &Apache::lonxml::debug("time:".time);
220:
221: if ($ENV{'request.state'} ne "construct") {
222: my $allowed=&check_ip_acc(&Apache::lonnet::EXT("resource.$id.acc"));
223: if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
224: $status='INVALID_ACCESS';
225: $date=&mt("can not be accessed from your location.");
226: return($status,$date);
227: }
228:
229: foreach $temp ("opendate","duedate","answerdate") {
230: $lastdate = $date;
231: $date = &Apache::lonnet::EXT("resource.$id.$temp");
232: my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
233: if ($thistype =~ /^(con_lost|no_such_host)/ ||
234: $date =~ /^(con_lost|no_such_host)/) {
235: $status='UNAVAILABLE';
236: $date=&mt("may open later.");
237: return($status,$date);
238: }
239: if ($thistype eq 'date_interval') {
240: if ($temp eq 'opendate') {
241: $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
242: }
243: if ($temp eq 'answerdate') {
244: $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
245: }
246: }
247: &Apache::lonxml::debug("found :$date: for :$temp:");
248: if ($date eq '') {
249: $date = &mt("an unknown date"); $passed = 0;
250: } elsif ($date eq 'con_lost') {
251: $date = &mt("an indeterminate date"); $passed = 0;
252: } else {
253: if (time < $date) { $passed = 0; } else { $passed = 1; }
254: $date = localtime $date;
255: }
256: if (!$passed) { $type=$temp; last; }
257: }
258: &Apache::lonxml::debug("have :$type:$passed:");
259: if ($passed) {
260: $status='SHOW_ANSWER';
261: $datemsg=$date;
262: } elsif ($type eq 'opendate') {
263: $status='CLOSED';
264: $datemsg = &mt("will open on")." $date";
265: } elsif ($type eq 'duedate') {
266: $status='CAN_ANSWER';
267: $datemsg = &mt("is due at")." $date";
268: } elsif ($type eq 'answerdate') {
269: $status='CLOSED';
270: $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
271: }
272: }
273: if ($status eq 'CAN_ANSWER') {
274: #check #tries, and if correct.
275: my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
276: my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
277: if ( $tries eq '' ) { $tries = '0'; }
278: if ( $maxtries eq '' &&
279: $ENV{'request.state'} ne 'construct') { $maxtries = '2'; }
280: if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
281: # if (correct and show prob status) or excused then CANNOT_ANSWER
282: if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
283: &&
284: lc($Apache::lonhomework::problemstatus) ne 'no')
285: ||
286: $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
287: $status = 'CANNOT_ANSWER';
288: }
289: }
290:
291: #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
292: # (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
293: # return ('UNCHECKEDOUT','needs to be checked out');
294: #}
295:
296:
297: &Apache::lonxml::debug("sending back :$status:$datemsg:");
298: if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
299: &Apache::lonxml::debug("should be allowed to browse a resource when closed");
300: $status='CAN_ANSWER';
301: $datemsg=&mt('is closed but you are allowed to view it');
302: }
303:
304: return ($status,$datemsg);
305: }
306:
307: sub showhash {
308: my (%hash) = @_;
309: &showhashsubset(\%hash,'.');
310: return '';
311: }
312:
313: sub showarray {
314: my ($array)=@_;
315: my $string="(";
316: foreach my $elm (@{ $array }) {
317: if (ref($elm)) {
318: if ($elm =~ /ARRAY/ ) {
319: $string.=&showarray($elm);
320: }
321: } else {
322: $string.="$elm,"
323: }
324: }
325: chop($string);
326: $string.=")";
327: return $string;
328: }
329:
330: sub showhashsubset {
331: my ($hash,$keyre) = @_;
332: my $resultkey;
333: foreach $resultkey (sort keys %$hash) {
334: if ($resultkey =~ /$keyre/) {
335: if (ref($$hash{$resultkey})) {
336: if ($$hash{$resultkey} =~ /ARRAY/ ) {
337: &Apache::lonxml::debug("$resultkey ---- ".
338: &showarray($$hash{$resultkey}));
339: } elsif ($$hash{$resultkey} =~ /HASH/ ) {
340: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
341: &showhashsubset($$hash{$resultkey},'.');
342: } else {
343: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
344: }
345: } else {
346: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
347: }
348: }
349: }
350: &Apache::lonxml::debug("\n<br />restored values^</br>\n");
351: return '';
352: }
353:
354: sub setuppermissions {
355: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
356: my $viewgrades = &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
357: if (! $viewgrades &&
358: exists($ENV{'request.course.sec'}) &&
359: $ENV{'request.course.sec'} !~ /^\s*$/) {
360: $viewgrades = &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'}.
361: '/'.$ENV{'request.course.sec'});
362: }
363: $Apache::lonhomework::viewgrades = $viewgrades;
364: return ''
365: }
366:
367: sub setupheader {
368: my $request=$_[0];
369: if ($ENV{'browser.mathml'}) {
370: &Apache::loncommon::content_type($request,'text/xml');
371: } else {
372: &Apache::loncommon::content_type($request,'text/html');
373: }
374: if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
375: &Apache::loncommon::no_cache($request);
376: }
377: $request->send_http_header;
378: return OK if $request->header_only;
379: return ''
380: }
381:
382: sub handle_save_or_undo {
383: my ($request,$problem,$result) = @_;
384: my $file = &Apache::lonnet::filelocation("",$request->uri);
385: my $filebak =$file.".bak";
386: my $filetmp =$file.".tmp";
387: my $error=0;
388:
389: &Apache::lonnet::correct_line_ends($result);
390:
391: if ($ENV{'form.Undo'} eq &mt('undo')) {
392: my $error=0;
393: if (!copy($file,$filetmp)) { $error=1; }
394: if ((!$error) && (!copy($filebak,$file))) { $error=1; }
395: if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
396: if (!$error) {
397: $request->print("<p><b>".&mt("Undid changes, Switched")." $filebak ".&mt("and")." $file</b></p>");
398: } else {
399: $request->print("<p><font color=\"red\" size=\"+1\"><b>".&mt("Unable to undo, unable to switch")." $filebak ".&mt("and")." $file</b></font></p>");
400: $error=1;
401: }
402: } else {
403: my $fs=Apache::File->new(">$filebak");
404: if (defined($fs)) {
405: print $fs $$problem;
406: $request->print("<b>".&mt("Making Backup to").
407: " $filebak</b><br />");
408: } else {
409: $request->print("<font color=\"red\" size=\"+1\"><b>".&mt("Unable to make backup")." $filebak</b></font>");
410: $error=2;
411: }
412: my $fh=Apache::File->new(">$file");
413: if (defined($fh)) {
414: print $fh $$result;
415: $request->print("<b>".&mt("Saving Modifications to").
416: " $file</b><br />");
417: } else {
418: $request->print("<font color=\"red\" size=\"+1\"><b>".
419: &mt("Unable to write to")." $file</b></font>");
420: $error|=4;
421: }
422: }
423: return $error;
424: }
425:
426: sub analyze_header {
427: my ($request) = @_;
428: my $result.='<html>
429: <head><title>'.&mt("Analyzing a problem").'</title></head>
430: <body bgcolor="#FFFFFF">
431: <form name="lonhomework" method="POST" action="'.
432: $ENV{'request.uri'}.'">
433: <input type="submit" name="problemmode" value="'.&mt("EditXML").'" />
434: <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
435: <hr />
436: <input type="submit" name="submit" value="'.&mt("View").'" />
437: <hr />
438: '.&mt('List of possible answers').':
439: </form>';
440: $request->print($result);
441: $request->rflush();
442: }
443:
444: sub analyze_footer {
445: my ($request) = @_;
446: my $result='</body></html>';
447: $request->print($result);
448: $request->rflush();
449: }
450:
451: sub analyze {
452: my ($request,$file) = @_;
453: &Apache::lonxml::debug("Analyze");
454: my $result;
455: my %overall;
456: my %allparts;
457: my $rndseed=$ENV{'form.rndseed'};
458: &analyze_header($request);
459: my %prog_state=
460: &Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
461: &mt('Getting Problem Variants'),
462: $ENV{'form.numtoanalyze'});
463: for(my $i=1;$i<$ENV{'form.numtoanalyze'}+1;$i++) {
464: &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
465: &mt('last problem'));
466: my $subresult=&Apache::lonnet::ssi($request->uri,
467: ('grade_target' => 'analyze'),
468: ('rndseed' => $i+$rndseed));
469: (my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
470: my %analyze=&Apache::lonnet::str2hash($subresult);
471: my @parts;
472: if (defined(@{ $analyze{'parts'} })) {
473: @parts=@{ $analyze{'parts'} };
474: }
475: foreach my $part (@parts) {
476: if (!exists($allparts{$part})) {$allparts{$part}=1;};
477: if ($analyze{$part.'.type'} eq 'numericalresponse' ||
478: $analyze{$part.'.type'} eq 'stringresponse' ||
479: $analyze{$part.'.type'} eq 'formularesponse' ) {
480: push( @{ $overall{$part.'.answer'} },
481: [@{ $analyze{$part.'.answer'} }]);
482: }
483: }
484: }
485: &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
486: &mt('Analyzing Results'));
487: foreach my $part (sort(keys(%allparts))) {
488: if (defined(@{ $overall{$part.'.answer'} })) {
489: my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
490: $request->print('<table><tr><td colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part.'</td></tr>');
491: my %frequency;
492: foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
493: $frequency{join("\0",@{ $answer })}++;
494: }
495: $request->print('<tr><td colspan="'.($num_cols).'">'.&mt('Answer').'</td><td>'.&mt('Frequency').'</td></tr>');
496: foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
497: $request->print('<tr><td align="right">'.
498: join('</td><td align="right">',split("\0",$answer)).
499: '</td><td>('.$frequency{$answer}.
500: ')</td></tr>');
501: }
502: $request->print('</table>');
503: } else {
504: $request->print('<p>'.&mt('Response').' '.$part.' '.
505: &mt('is not analyzable at this time').'</p>');
506: }
507: }
508: if (scalar(keys(%allparts)) == 0 ) {
509: $request->print('<p>'.&mt('Found no analyzable respones in this problem, currently only Numerical, Formula and String response styles are supported.').'</p>');
510: }
511: &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
512: &analyze_footer($request);
513: &Apache::lonhomework::showhash(%overall);
514: return $result;
515: }
516:
517: sub editxmlmode {
518: my ($request,$file) = @_;
519: my $result;
520: my $problem=&Apache::lonnet::getfile($file);
521: if ($problem eq -1) {
522: &Apache::lonxml::error("<b> ".&mt('Unable to find').
523: " <i>$file</i></b>");
524: $problem='';
525: }
526: if (defined($ENV{'form.editxmltext'}) || defined($ENV{'form.Undo'})) {
527: my $error=&handle_save_or_undo($request,\$problem,
528: \$ENV{'form.editxmltext'});
529: if (!$error) { $problem=&Apache::lonnet::getfile($file); }
530: }
531: &Apache::lonhomework::showhashsubset(\%ENV,'^form');
532: if ( $ENV{'form.submit'} eq &mt('Submit Changes and View') ) {
533: &Apache::lonhomework::showhashsubset(\%ENV,'^form');
534: $ENV{'form.problemmode'}='View';
535: &renderpage($request,$file);
536: } else {
537: my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
538: my $xml_help = '<table><tr><td>'.
539: &Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
540: "Problem Editing Help").
541: '</td><td>'.
542: &Apache::loncommon::help_open_faq(5).
543: &Apache::loncommon::help_open_bug('Authoring').'</td></tr></table>';
544: if ($cols > 80) { $cols = 80; }
545: if ($cols < 70) { $cols = 70; }
546: if ($rows < 20) { $rows = 20; }
547: $result.='<html><body bgcolor="#FFFFFF">
548: <form name="lonhomework" method="POST" action="'.
549: $ENV{'request.uri'}.'">
550: <input type="hidden" name="problemmode" value="'.&mt('EditXML').'" />
551: <input type="submit" name="problemmode" value="'.&mt('Discard Edits and View').'" />
552: <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
553: <hr />
554: <input type="submit" name="submit" value="'.&mt('Submit Changes').'" />
555: <input type="submit" name="submit" value="'.&mt('Submit Changes and View').'" />
556: <input type="submit" name="Undo" value="'.&mt('undo').'" />
557: <hr />
558: ' . $xml_help . '
559: <textarea rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
560: &HTML::Entities::encode($problem).'</textarea>
561: </form></body></html>';
562: $request->print($result);
563: }
564: return '';
565: }
566:
567: sub renderpage {
568: my ($request,$file) = @_;
569:
570: my (@targets) = &get_target();
571: &Apache::lonhomework::showhashsubset(\%ENV,'form.');
572: &Apache::lonxml::debug("Running targets ".join(':',@targets));
573: foreach my $target (@targets) {
574: #my $t0 = [&gettimeofday()];
575: my $problem=&Apache::lonnet::getfile($file);
576: if ($problem eq -1) {
577: &Apache::lonxml::error("<b> ".&mt('Unable to find')." <i>$file</i></b>");
578: $problem='';
579: }
580:
581: my %mystyle;
582: my $result = '';
583: if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
584: if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
585: if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%ENV,'^form');}
586:
587: &Apache::lonxml::debug("Should be parsing now");
588: $result = &Apache::lonxml::xmlparse($request, $target, $problem,
589: &setup_vars($target),%mystyle);
590: undef($Apache::lonhomework::parsing_a_problem);
591: #$request->print("Result follows:");
592: if ($target eq 'modified') {
593: &handle_save_or_undo($request,\$problem,\$result);
594: } else {
595: if ($target eq 'analyze') {
596: $result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
597: undef(%Apache::lonhomework::analyze);
598: }
599: #my $td=&tv_interval($t0);
600: #if ( $Apache::lonxml::debug) {
601: #$result =~ s:</body>::;
602: #$result.="<br />Spent $td seconds processing target $target\n</body>";
603: #}
604: $request->print($result);
605: $request->rflush();
606: }
607: #$request->print(":Result ends");
608: #my $td=&tv_interval($t0);
609: }
610: }
611:
612: # with no arg it returns a HTML <option> list of the template titles
613: # with one arg it returns the filename associated with the arg passed
614: sub get_template_list {
615: my ($namewanted,$extension) = @_;
616: my $result;
617: my @allnames;
618: &Apache::lonxml::debug("Looking for :$extension:");
619: foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
620: my $name=&Apache::lonnet::metadata($file,'title');
621: if ($namewanted && ($name eq $namewanted)) {
622: $result=$file;
623: last;
624: } else {
625: if ($name) { push (@allnames, $name); }
626: }
627: }
628: if (@allnames && !$result) {
629: $result="<option>".&mt("Select a")." $extension ".&mt('template')."</option>\n<option>".
630: join('</option><option>',sort(@allnames)).'</option>';
631: }
632: return $result;
633: }
634:
635: sub newproblem {
636: my ($request) = @_;
637: my $extension=$request->uri;
638: $extension=~s:^.*\.([\w]+)$:$1:;
639: &Apache::lonxml::debug("Looking for :$extension:");
640: my $templatelist=&get_template_list('',$extension);
641: if ($ENV{'form.template'} &&
642: $ENV{'form.template'} ne "Select a $extension template") {
643: use File::Copy;
644: my $file = &get_template_list($ENV{'form.template'},$extension);
645: my $dest = &Apache::lonnet::filelocation("",$request->uri);
646: copy($file,$dest);
647: &renderpage($request,$dest);
648: } elsif($ENV{'form.newfile'} && !$templatelist) {
649: # I don't like hard-coded filenames but for now, this will work.
650: use File::Copy;
651: my $templatefilename =
652: $request->dir_config('lonIncludes').'/templates/blank.problem';
653: &Apache::lonxml::debug("$templatefilename");
654: my $dest = &Apache::lonnet::filelocation("",$request->uri);
655: copy($templatefilename,$dest);
656: &renderpage($request,$dest);
657: } else {
658: my $url=$request->uri;
659: my $shownurl=$url;
660: $shownurl=~s-^/~-/priv/-;
661: my $dest = &Apache::lonnet::filelocation("",$request->uri);
662: my $errormsg;
663: if ($ENV{'form.newfile'}) {
664: $errormsg='<p><font color="red">'.&mt('You did not select a template.').'</font></p>'."\n";
665: }
666: my $instructions;
667: my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
668: if ($templatelist) { $instructions=&mt(", select a template from the pull-down menu below.").'<br />'.&mt("Then");}
669: my %lt=&Apache::lonlocal::texthash( 'create' => 'Creating a new',
670: 'resource' => 'resource',
671: 'requested' => 'The requested file',
672: 'not exist' => 'currently does not exist',
673: 'createnew' => 'To create a new',
674: 'click' => 'click on the',
675: 'Create' => 'Create',
676: 'button' => 'button');
677: $request->print(<<ENDNEWPROBLEM);
678: $bodytag
679: <h1>$lt{'create'} $extension $lt{'resource'}</h1>
680: $errormsg
681: $lt{'requested'} <tt>$shownurl</tt> $lt{'not exist'}.
682: <p>
683: <b>$lt{'createnew'} $extension$instructions $lt{'click'} "$lt{'Create'} $extension" $lt{'button'}.</b>
684: </p>
685: <p><form action="$url" method="POST">
686: ENDNEWPROBLEM
687: if (defined($templatelist)) {
688: $request->print("<select name=\"template\">$templatelist</select>");
689: }
690: $request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"".&mt('Create')." $extension\" />");
691: $request->print("</form></p></body>");
692: }
693: return '';
694: }
695:
696: sub view_or_edit_menu {
697: my ($request) = @_;
698: my $url=$request->uri;
699: my %lt=&Apache::lonlocal::texthash( 'would' => 'Would you like to',
700: 'view' => 'View',
701: 'Edit' => 'edit',
702: 'or' => 'or',
703: 'the problem' => 'the problem');
704: $request->print(<<EDITMENU);
705: <body bgcolor="#FFFFFF">
706: <form action="$url" method="POST">
707: $lt{'would'} <input type="submit" name="problemmode" value="<{'view'}">
708: <{'or'} <input type="submit" name="problemmode" value="<{'Edit'}">
709: <{'the problem'}.
710: </form>
711: </body>
712: EDITMENU
713: }
714:
715: sub handler {
716: #my $t0 = [&gettimeofday()];
717: my $request=$_[0];
718:
719: $Apache::lonxml::debug=$ENV{'user.debug'};
720: if (&setupheader($request)) { return OK; }
721: $ENV{'request.uri'}=$request->uri;
722:
723: #setup permissions
724: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
725: $Apache::lonhomework::viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
726: &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:");
727: # some times multiple problemmodes are submitted, need to select
728: # the last one
729: &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
730: if ( defined($ENV{'form.problemmode'}) &&
731: ref($ENV{'form.problemmode'}) ) {
732: &Apache::lonxml::debug("Problem Mode ".join(",",@$ENV{'form.problemmode'}));
733: my $mode=$ENV{'form.problemmode'}->[-1];
734: undef $ENV{'form.problemmode'};
735: $ENV{'form.problemmode'}=$mode;
736: }
737: &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
738: my $file=&Apache::lonnet::filelocation("",$request->uri);
739:
740: #check if we know where we are
741: if ($ENV{'request.course.fn'} && !&Apache::lonnet::symbread()) {
742: # if we are browsing we might not be able to know where we are
743: if ($Apache::lonhomework::browse ne 'F') {
744: #should know where we are, so ask
745: if ( &Apache::lonnet::mod_perl_version() == 2 ) {
746: &Apache::lonnet::cleanenv();
747: }
748: $request->internal_redirect('/adm/ambiguous'); return;
749: }
750: }
751:
752: my ($symb) = &Apache::lonxml::whichuser();
753: &Apache::lonxml::debug('symb is '.$symb);
754: if ($ENV{'request.state'} eq "construct" || $symb eq '') {
755: if ($ENV{'form.resetdata'} eq &mt('Reset Submissions') ||
756: $ENV{'form.resetdata'} eq &mt('New Problem Variation') ||
757: $ENV{'form.newrandomization'} eq &mt('New Randomization')) {
758: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
759: &Apache::lonnet::tmpreset($symb,'',$domain,$name);
760: &Apache::lonxml::debug("Attempt reset");
761: }
762: }
763: if ($ENV{'request.state'} eq "construct") {
764: if ( -e $file ) {
765: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
766: ['problemmode']);
767: if (!(defined $ENV{'form.problemmode'})) {
768: #first visit to problem in construction space
769: #&view_or_edit_menu($request);
770: $ENV{'form.problemmode'}='View';
771: &renderpage($request,$file);
772: } elsif ($ENV{'form.problemmode'} eq &mt('EditXML')) {
773: &editxmlmode($request,$file);
774: } elsif ($ENV{'form.problemmode'} eq &mt('Calculate answers')) {
775: &analyze($request,$file);
776: } else {
777: &renderpage($request,$file);
778: }
779: } else {
780: # requested file doesn't exist in contruction space
781: &newproblem($request);
782: }
783: } else {
784: # just render the page normally outside of construction space
785: &Apache::lonxml::debug("not construct");
786: &renderpage($request,$file);
787: }
788: #my $td=&tv_interval($t0);
789: #&Apache::lonxml::debug("Spent $td seconds processing");
790: # &Apache::lonhomework::send_footer($request);
791: # always turn off debug messages
792: $Apache::lonxml::debug=0;
793: return OK;
794:
795: }
796:
797: 1;
798: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>