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