1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Homework handler
3: #
4: # $Id: lonhomework.pm,v 1.258 2006/09/25 19:41:56 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27:
28:
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::drawimage();
51: use Apache::Constants qw(:common);
52: use HTML::Entities();
53: use Apache::loncommon();
54: use Apache::lonlocal;
55: use Time::HiRes qw( gettimeofday tv_interval );
56: use Apache::lonnet();
57:
58: # FIXME - improve commenting
59:
60:
61: BEGIN {
62: &Apache::lonxml::register_insert();
63: }
64:
65:
66: #
67: # Decides what targets to render for.
68: # Implicit inputs:
69: # Various session environment variables:
70: # request.state - published - is a /res/ resource
71: # uploaded - is a /uploaded/ resource
72: # contruct - is a /priv/ resource
73: # form.grade_target - a form parameter requesting a specific target
74: sub get_target {
75: &Apache::lonxml::debug("request.state = $env{'request.state'}");
76: if( defined($env{'form.grade_target'})) {
77: &Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
78: } else {
79: &Apache::lonxml::debug("form.grade_target <undefined>");
80: }
81: if (($env{'request.state'} eq "published") ||
82: ($env{'request.state'} eq "uploaded")) {
83: if ( defined($env{'form.grade_target'} )
84: && ($env{'form.grade_target'} eq 'tex')) {
85: return ($env{'form.grade_target'});
86: } elsif ( defined($env{'form.grade_target'} )
87: && ($Apache::lonhomework::viewgrades eq 'F' )) {
88: return ($env{'form.grade_target'});
89: } elsif ( $env{'form.grade_target'} eq 'webgrade'
90: && ($Apache::lonhomework::queuegrade eq 'F' )) {
91: return ($env{'form.grade_target'});
92: }
93: if ($env{'form.webgrade'} &&
94: ($Apache::lonhomework::modifygrades eq 'F'
95: || $Apache::lonhomework::queuegrade eq 'F' )) {
96: return ('grade','webgrade');
97: }
98: if ( defined($env{'form.submitted'}) &&
99: ( !defined($env{'form.resetdata'})) &&
100: ( !defined($env{'form.newrandomization'}))) {
101: return ('grade', 'web');
102: } else {
103: return ('web');
104: }
105: } elsif ($env{'request.state'} eq "construct") {
106: if ( defined($env{'form.grade_target'}) ) {
107: return ($env{'form.grade_target'});
108: }
109: if ( defined($env{'form.preview'})) {
110: if ( defined($env{'form.submitted'})) {
111: return ('grade', 'web');
112: } else {
113: return ('web');
114: }
115: } else {
116: if ( $env{'form.problemmode'} eq &mt('View') ||
117: $env{'form.problemmode'} eq &mt('Discard Edits and View')) {
118: if ( defined($env{'form.submitted'}) &&
119: (!defined($env{'form.resetdata'})) &&
120: (!defined($env{'form.newrandomization'}))) {
121: return ('grade', 'web','answer');
122: } else {
123: return ('web','answer');
124: }
125: } elsif ( $env{'form.problemmode'} eq &mt('Edit') ||
126: $env{'form.problemmode'} eq 'Edit') {
127: if ( $env{'form.submitted'} eq 'edit' ) {
128: if ( $env{'form.submit'} eq &mt('Submit Changes and View') ) {
129: return ('modified','web','answer');
130: } else {
131: return ('modified','no_output_web','edit');
132: }
133: } else {
134: return ('no_output_web','edit');
135: }
136: } else {
137: return ('web');
138: }
139: }
140: }
141: return ();
142: }
143:
144: sub setup_vars {
145: my ($target) = @_;
146: return ';'
147: # return ';$external::target='.$target.';';
148: }
149:
150: sub createmenu {
151: my ($which,$request)=@_;
152: if ($which eq 'grade') {
153: $request->print('<script language="JavaScript">
154: hwkmenu=window.open("/res/adm/pages/homeworkmenu.html","homeworkremote",
155: "height=350,width=150,menubar=no");
156: </script>');
157: }
158: }
159:
160: sub proctor_checked_in {
161: my ($slot_name,$slot,$type)=@_;
162: my @possible_proctors=split(",",$slot->{'proctor'});
163:
164: return 1 if (!@possible_proctors);
165:
166: my $key;
167: if ($type eq 'Task') {
168: my $version=$Apache::lonhomework::history{'resource.0.version'};
169: $key ="resource.$version.0.checkedin";
170: } elsif ($type eq 'problem') {
171: $key ='resource.0.checkedin';
172: }
173: # backward compatability, used to be username@domain,
174: # now is username:domain
175: my $who = $Apache::lonhomework::history{$key};
176: if ($who !~ /:/) {
177: $who =~ tr/@/:/;
178: }
179: foreach my $possible (@possible_proctors) {
180: if ($who eq $possible
181: && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
182: return 1;
183: }
184: }
185:
186: return 0;
187: }
188:
189: $Apache::lonxml::browse='';
190: sub check_ip_acc {
191: my ($acc)=@_;
192: &Apache::lonxml::debug("acc is $acc");
193: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
194: return 1;
195: }
196: my $allowed=0;
197: my $ip=$ENV{'REMOTE_ADDR'};
198: my $name;
199: foreach my $pattern (split(',',$acc)) {
200: $pattern =~ s/^\s*//;
201: $pattern =~ s/\s*$//;
202: if ($pattern =~ /\*$/) {
203: #35.8.*
204: $pattern=~s/\*//;
205: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
206: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
207: #35.8.3.[34-56]
208: my $low=$2;
209: my $high=$3;
210: $pattern=$1;
211: if ($ip =~ /^\Q$pattern\E/) {
212: my $last=(split(/\./,$ip))[3];
213: if ($last <=$high && $last >=$low) { $allowed=1; }
214: }
215: } elsif ($pattern =~ /^\*/) {
216: #*.msu.edu
217: $pattern=~s/\*//;
218: if (!defined($name)) {
219: use Socket;
220: my $netaddr=inet_aton($ip);
221: ($name)=gethostbyaddr($netaddr,AF_INET);
222: }
223: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
224: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
225: #127.0.0.1
226: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
227: } else {
228: #some.name.com
229: if (!defined($name)) {
230: use Socket;
231: my $netaddr=inet_aton($ip);
232: ($name)=gethostbyaddr($netaddr,AF_INET);
233: }
234: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
235: }
236: if ($allowed) { last; }
237: }
238: return $allowed;
239: }
240:
241: sub check_slot_access {
242: my ($id,$type)=@_;
243:
244: # does it pass normal muster
245: my ($status,$datemsg)=&check_access($id);
246:
247: my $useslots = &Apache::lonnet::EXT("resource.0.useslots");
248: if ($useslots ne 'resource' && $useslots ne 'map'
249: && $useslots ne 'map_map') {
250: return ($status,$datemsg);
251: }
252:
253: if ($status eq 'SHOW_ANSWER' ||
254: $status eq 'CLOSED' ||
255: $status eq 'INVALID_ACCESS' ||
256: $status eq 'UNAVAILABLE') {
257: return ($status,$datemsg);
258: }
259: if ($env{'request.state'} eq "construct") {
260: return ($status,$datemsg);
261: }
262:
263: if ($type eq 'Task') {
264: my $version=$Apache::lonhomework::history{'resource.version'};
265: if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
266: $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
267: return ('SHOW_ANSWER');
268: }
269: }
270:
271: my @slots=
272: (split(':',&Apache::lonnet::EXT("resource.0.availablestudent")),
273: split(':',&Apache::lonnet::EXT("resource.0.available")));
274:
275: # if (!@slots) {
276: # return ($status,$datemsg);
277: # }
278: my $slotstatus='NOT_IN_A_SLOT';
279: my ($returned_slot,$slot_name);
280: foreach my $slot (@slots) {
281: $slot =~ s/(^\s*|\s*$)//g;
282: &Apache::lonxml::debug("getting $slot");
283: my %slot=&Apache::lonnet::get_slot($slot);
284: &Apache::lonhomework::showhash(%slot);
285: if ($slot{'starttime'} < time &&
286: $slot{'endtime'} > time &&
287: &check_ip_acc($slot{'ip'})) {
288: &Apache::lonxml::debug("$slot is good");
289: $slotstatus='NEEDS_CHECKIN';
290: $returned_slot=\%slot;
291: $slot_name=$slot;
292: last;
293: }
294: }
295: if ($slotstatus eq 'NEEDS_CHECKIN' &&
296: &proctor_checked_in($slot_name,$returned_slot,$type)) {
297: &Apache::lonxml::debug("protoctor checked in");
298: $slotstatus='CAN_ANSWER';
299: }
300:
301: my ($is_correct,$got_grade,$checkedin);
302: if ($type eq 'Task') {
303: my $version=$Apache::lonhomework::history{'resource.0.version'};
304: $got_grade =
305: ($Apache::lonhomework::history{"resource.$version.0.status"}
306: =~ /^(?:pass|fail)$/);
307: $is_correct =
308: ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
309: || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
310: $checkedin =
311: $Apache::lonhomework::history{"resource.$version.0.checkedin"};
312: } elsif ($type eq 'problem') {
313: $got_grade = 1;
314: $checkedin = $Apache::lonhomework::history{"resource.0.checkedin"};
315: $is_correct =
316: ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
317: }
318:
319: &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
320:
321: # no slot is currently open, and has been checked in for this version
322: # but hasn't got a grade, therefore must be awaiting a grade
323: if (!defined($slot_name)
324: && $checkedin
325: && !$got_grade) {
326: return ('WAITING_FOR_GRADE');
327: }
328:
329: # no slot is currently open, and has been checked in for this version
330: # previous slot is therefore CLOSED, so therefore the problem is
331: if (!defined($slot_name)
332: && $checkedin
333: && $type eq 'problem') {
334: return ('CLOSED',$datemsg);
335: }
336:
337: if ($slotstatus eq 'NOT_IN_A_SLOT'
338: && $checkedin ) {
339:
340: if ($got_grade) {
341: return ('SHOW_ANSWER');
342: } else {
343: return ('WAITING_FOR_GRADE');
344: }
345:
346: }
347:
348: if ( $is_correct) {
349: if ($type eq 'problem') {
350: return ($status);
351: }
352: return ('SHOW_ANSWER');
353: }
354:
355: if ( $status eq 'CANNOT_ANSWER' &&
356: ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
357: return ($status,$datemsg);
358: }
359:
360: return ($slotstatus,$datemsg,$slot_name,$returned_slot);
361: }
362:
363: # JB, 9/24/2002: Any changes in this function may require a change
364: # in lonnavmaps::resource::getDateStatus.
365: sub check_access {
366: my ($id) = @_;
367: my $date ='';
368: my $status;
369: my $datemsg = '';
370: my $lastdate = '';
371: my $type;
372: my $passed;
373:
374: if ($env{'request.state'} eq "construct") {
375: if ($env{'form.problemstate'}) {
376: if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
377: if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' &&
378: lc($Apache::lonhomework::problemstatus) eq 'no')) {
379: return ('CANNOT_ANSWER',
380: &mt('is in this state due to author settings.'));
381: }
382: } else {
383: return ($env{'form.problemstate'},
384: &mt('is in this state due to author settings.'));
385: }
386: }
387: &Apache::lonxml::debug("in construction ignoring dates");
388: $status='CAN_ANSWER';
389: $datemsg=&mt('is in under construction');
390: # return ($status,$datemsg);
391: }
392:
393: &Apache::lonxml::debug("checking for part :$id:");
394: &Apache::lonxml::debug("time:".time);
395:
396: my ($symb)=&Apache::lonxml::whichuser();
397: &Apache::lonxml::debug("symb:".$symb);
398: #if ($env{'request.state'} ne "construct" && $symb ne '') {
399: if ($env{'request.state'} ne "construct") {
400: my $allowed=&check_ip_acc(&Apache::lonnet::EXT("resource.$id.acc"));
401: if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
402: $status='INVALID_ACCESS';
403: $date=&mt("can not be accessed from your location.");
404: return($status,$date);
405: }
406:
407: foreach my $temp ("opendate","duedate","answerdate") {
408: $lastdate = $date;
409: if ($temp eq 'duedate') {
410: $date = &due_date($id);
411: } else {
412: $date = &Apache::lonnet::EXT("resource.$id.$temp");
413: }
414:
415: my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
416: if ($thistype =~ /^(con_lost|no_such_host)/ ||
417: $date =~ /^(con_lost|no_such_host)/) {
418: $status='UNAVAILABLE';
419: $date=&mt("may open later.");
420: return($status,$date);
421: }
422: if ($thistype eq 'date_interval') {
423: if ($temp eq 'opendate') {
424: $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
425: }
426: if ($temp eq 'answerdate') {
427: $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
428: }
429: }
430: &Apache::lonxml::debug("found :$date: for :$temp:");
431: if ($date eq '') {
432: $date = &mt("an unknown date"); $passed = 0;
433: } elsif ($date eq 'con_lost') {
434: $date = &mt("an indeterminate date"); $passed = 0;
435: } else {
436: if (time < $date) { $passed = 0; } else { $passed = 1; }
437: $date = localtime $date;
438: }
439: if (!$passed) { $type=$temp; last; }
440: }
441: &Apache::lonxml::debug("have :$type:$passed:");
442: if ($passed) {
443: $status='SHOW_ANSWER';
444: $datemsg=$date;
445: } elsif ($type eq 'opendate') {
446: $status='CLOSED';
447: $datemsg = &mt("will open on")." $date";
448: } elsif ($type eq 'duedate') {
449: $status='CAN_ANSWER';
450: $datemsg = &mt("is due at")." $date";
451: } elsif ($type eq 'answerdate') {
452: $status='CLOSED';
453: $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
454: }
455: }
456: if ($status eq 'CAN_ANSWER' ||
457: (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
458: #check #tries, and if correct.
459: my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
460: my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
461: if ( $tries eq '' ) { $tries = '0'; }
462: if ( $maxtries eq '' &&
463: $env{'request.state'} ne 'construct') { $maxtries = '2'; }
464: if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
465: # if (correct and show prob status) or excused then CANNOT_ANSWER
466: if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
467: &&
468: lc($Apache::lonhomework::problemstatus) ne 'no')
469: ||
470: $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
471: $status = 'CANNOT_ANSWER';
472: }
473: }
474: if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
475: my $interval=&Apache::lonnet::EXT("resource.$id.interval");
476: &Apache::lonxml::debug("looking for interval $interval");
477: if ($interval) {
478: my $first_access=&Apache::lonnet::get_first_access('map');
479: &Apache::lonxml::debug("looking for accesstime $first_access");
480: if (!$first_access) {
481: $status='NOT_YET_VIEWED';
482: my $due_date = &due_date($id);
483: my $seconds_left = $due_date - time;
484: if ($seconds_left > $interval || $due_date eq '') {
485: $seconds_left = $interval;
486: }
487: $datemsg=&seconds_to_human_length($seconds_left);
488: }
489: }
490: }
491:
492: #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
493: # (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
494: # return ('UNCHECKEDOUT','needs to be checked out');
495: #}
496:
497:
498: &Apache::lonxml::debug("sending back :$status:$datemsg:");
499: if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
500: &Apache::lonxml::debug("should be allowed to browse a resource when closed");
501: $status='CAN_ANSWER';
502: $datemsg=&mt('is closed but you are allowed to view it');
503: }
504:
505: return ($status,$datemsg);
506: }
507: # this should work exactly like the copy in lonnavmaps.pm
508: sub due_date {
509: my ($part_id,$symb,$udom,$uname)=@_;
510: my $date;
511: my $interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
512: $udom,$uname);
513: &Apache::lonxml::debug("looking for interval $part_id $symb $interval");
514: my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
515: $udom,$uname);
516: &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
517: if ($interval =~ /\d+/) {
518: my $first_access=&Apache::lonnet::get_first_access('map',$symb);
519: &Apache::lonxml::debug("looking for first_access $first_access");
520: if (defined($first_access)) {
521: $interval = $first_access+$interval;
522: $date = ($interval < $due_date)? $interval : $due_date;
523: } else {
524: $date = $due_date;
525: }
526: } else {
527: $date = $due_date;
528: }
529: return $date
530: }
531:
532: sub seconds_to_human_length {
533: my ($length)=@_;
534:
535: my $seconds=$length%60; $length=int($length/60);
536: my $minutes=$length%60; $length=int($length/60);
537: my $hours=$length%24; $length=int($length/24);
538: my $days=$length;
539:
540: my $timestr;
541: if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
542: if ($hours > 0) { $timestr.=($timestr?", ":"").
543: &mt('[quant,_1,hour]',$hours); }
544: if ($minutes > 0) { $timestr.=($timestr?", ":"").
545: &mt('[quant,_1,minute]',$minutes); }
546: if ($seconds > 0) { $timestr.=($timestr?", ":"").
547: &mt('[quant,_1,second]',$seconds); }
548: return $timestr;
549: }
550:
551: sub showhash {
552: my (%hash) = @_;
553: &showhashsubset(\%hash,'.');
554: return '';
555: }
556:
557: sub showarray {
558: my ($array)=@_;
559: my $string="(";
560: foreach my $elm (@{ $array }) {
561: if (ref($elm) eq 'ARRAY') {
562: $string.=&showarray($elm);
563: } elsif (ref($elm) eq 'HASH') {
564: $string.= "HASH --- \n<br />";
565: $string.= &showhashsubset($elm,'.');
566: } else {
567: $string.="$elm,"
568: }
569: }
570: chop($string);
571: $string.=")";
572: return $string;
573: }
574:
575: sub showhashsubset {
576: my ($hash,$keyre) = @_;
577: my $resultkey;
578: foreach $resultkey (sort keys %$hash) {
579: if ($resultkey !~ /$keyre/) { next; }
580: if (ref($$hash{$resultkey}) eq 'ARRAY' ) {
581: &Apache::lonxml::debug("$resultkey ---- ".
582: &showarray($$hash{$resultkey}));
583: } elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
584: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
585: &showhashsubset($$hash{$resultkey},'.');
586: } else {
587: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
588: }
589: }
590: &Apache::lonxml::debug("\n<br />restored values^</br>\n");
591: return '';
592: }
593:
594: sub setuppermissions {
595: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
596: my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
597: if (! $viewgrades &&
598: exists($env{'request.course.sec'}) &&
599: $env{'request.course.sec'} !~ /^\s*$/) {
600: $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
601: '/'.$env{'request.course.sec'});
602: }
603: $Apache::lonhomework::viewgrades = $viewgrades;
604:
605: if ($Apache::lonhomework::browse eq 'F' &&
606: $env{'form.devalidatecourseresdata'} eq 'on') {
607: my (undef,$courseid) = &Apache::lonxml::whichuser();
608: &Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
609: $env{"course.$courseid.domain"});
610: }
611:
612: my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
613: if (! $modifygrades &&
614: exists($env{'request.course.sec'}) &&
615: $env{'request.course.sec'} !~ /^\s*$/) {
616: $modifygrades =
617: &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
618: '/'.$env{'request.course.sec'});
619: }
620: $Apache::lonhomework::modifygrades = $modifygrades;
621:
622: my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
623: if (! $queuegrade &&
624: exists($env{'request.course.sec'}) &&
625: $env{'request.course.sec'} !~ /^\s*$/) {
626: $queuegrade =
627: &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
628: '/'.$env{'request.course.sec'});
629: }
630: $Apache::lonhomework::queuegrade = $queuegrade;
631: return '';
632: }
633:
634: sub unset_permissions {
635: undef($Apache::lonhomework::queuegrade);
636: undef($Apache::lonhomework::modifygrades);
637: undef($Apache::lonhomework::viewgrades);
638: undef($Apache::lonhomework::browse);
639: }
640:
641: sub setupheader {
642: my $request=$_[0];
643: &Apache::loncommon::content_type($request,'text/html');
644: if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
645: &Apache::loncommon::no_cache($request);
646: }
647: # $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
648: # 'lastrevisiondate'));
649: $request->send_http_header;
650: return OK if $request->header_only;
651: return ''
652: }
653:
654: sub handle_save_or_undo {
655: my ($request,$problem,$result) = @_;
656: my $file = &Apache::lonnet::filelocation("",$request->uri);
657: my $filebak =$file.".bak";
658: my $filetmp =$file.".tmp";
659: my $error=0;
660:
661: &Apache::lonnet::correct_line_ends($result);
662:
663: if ($env{'form.Undo'} eq &mt('undo')) {
664: my $error=0;
665: if (!copy($file,$filetmp)) { $error=1; }
666: if ((!$error) && (!copy($filebak,$file))) { $error=1; }
667: if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
668: if (!$error) {
669: &Apache::lonxml::info("<p><b>".&mt("Undid changes, Switched")." $filebak ".&mt("and")." $file</b></p>");
670: } else {
671: &Apache::lonxml::info("<p><font color=\"red\" size=\"+1\"><b>".&mt("Unable to undo, unable to switch")." $filebak ".&mt("and")." $file</b></font></p>");
672: $error=1;
673: }
674: } else {
675: my $fs=Apache::File->new(">$filebak");
676: if (defined($fs)) {
677: print $fs $$problem;
678: &Apache::lonxml::info("<b>".&mt("Making Backup to").
679: " $filebak</b>");
680: } else {
681: &Apache::lonxml::info("<font color=\"red\" size=\"+1\"><b>".&mt("Unable to make backup")." $filebak</b></font>");
682: $error=2;
683: }
684: my $fh=Apache::File->new(">$file");
685: if (defined($fh)) {
686: print $fh $$result;
687: &Apache::lonxml::info("<b>".&mt("Saving Modifications to").
688: " $file</b>");
689: } else {
690: &Apache::lonxml::info("<font color=\"red\" size=\"+1\"><b>".
691: &mt("Unable to write to")." $file</b></font>");
692: $error|=4;
693: }
694: }
695: return $error;
696: }
697:
698: sub analyze_header {
699: my ($request) = @_;
700: my $result =
701: &Apache::loncommon::start_page('Analyzing a problem',undef);
702:
703: $result .=
704: &Apache::lonxml::message_location().'
705: <form name="lonhomework" method="POST" action="'.
706: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
707: &Apache::structuretags::remember_problem_state().'
708: <input type="submit" name="problemmode" value="'.&mt("EditXML").'" />
709: <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
710: <hr />
711: <input type="submit" name="submit" value="'.&mt("View").'" />
712: <hr />
713: </form>';
714: &Apache::lonxml::add_messages(\$result);
715: $request->print($result);
716: $request->rflush();
717: }
718:
719: sub analyze_footer {
720: my ($request) = @_;
721: $request->print(&Apache::loncommon::end_page());
722: $request->rflush();
723: }
724:
725: sub analyze {
726: my ($request,$file) = @_;
727: &Apache::lonxml::debug("Analyze");
728: my $result;
729: my %overall;
730: my %seedexample;
731: my %allparts;
732: my $rndseed=$env{'form.rndseed'};
733: &analyze_header($request);
734: my %prog_state=
735: &Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
736: &mt('Getting Problem Variants'),
737: $env{'form.numtoanalyze'},
738: 'inline',undef);
739: for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
740: &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
741: &mt('last problem'));
742: if (&Apache::loncommon::connection_aborted($request)) { return; }
743: my $thisseed=$i+$rndseed;
744: my $subresult=&Apache::lonnet::ssi($request->uri,
745: ('grade_target' => 'analyze'),
746: ('rndseed' => $thisseed));
747: (my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
748: my %analyze=&Apache::lonnet::str2hash($subresult);
749: my @parts;
750: if (defined(@{ $analyze{'parts'} })) {
751: @parts=@{ $analyze{'parts'} };
752: }
753: foreach my $part (@parts) {
754: if (!exists($allparts{$part})) {$allparts{$part}=1;};
755: if ($analyze{$part.'.type'} eq 'numericalresponse' ||
756: $analyze{$part.'.type'} eq 'stringresponse' ||
757: $analyze{$part.'.type'} eq 'formularesponse' ) {
758: my $concatanswer=join("\0",@{ $analyze{$part.'.answer'} });
759: if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
760: @{$analyze{$part.'.answer'}}=('<font color="red">'.&mt('Error').'</font>');
761: }
762: push( @{ $overall{$part.'.answer'} },
763: [@{ $analyze{$part.'.answer'} }]);
764: $seedexample{join("\0",@{ $analyze{$part.'.answer'}})}=$thisseed;
765: }
766: }
767: }
768: &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
769: &mt('Analyzing Results'));
770: $request->print('<hr />'.&mt('List of possible answers').': ');
771: foreach my $part (sort(keys(%allparts))) {
772: if (defined(@{ $overall{$part.'.answer'} })) {
773: my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
774: $request->print('<table class="thinborder"><tr><th colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part.'</th></tr>');
775: my %frequency;
776: foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
777: $frequency{join("\0",@{ $answer })}++;
778: }
779: $request->print('<tr><th colspan="'.($num_cols).'">'.&mt('Answer').'</th><th>'.&mt('Frequency').'<br />('
780: .&mt('click for example').')</th></tr>');
781: foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
782: $request->print('<tr><td class="center">'.
783: join('</td><td class="center">',split("\0",$answer)).
784: '</td><td class="center"><a href="'.$request->uri.'?rndseed='.$seedexample{$answer}.'">'.$frequency{$answer}.
785: '</a></td></tr>');
786: }
787: $request->print('</table>');
788: } else {
789: $request->print('<p>'.&mt('Response').' '.$part.' '.
790: &mt('is not analyzable at this time').'</p>');
791: }
792: }
793: if (scalar(keys(%allparts)) == 0 ) {
794: $request->print('<p>'.&mt('Found no analyzable responses in this problem, currently only Numerical, Formula and String response styles are supported.').'</p>');
795: }
796: &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
797: &analyze_footer($request);
798: &Apache::lonhomework::showhash(%overall);
799: return $result;
800: }
801:
802: sub editxmlmode {
803: my ($request,$file) = @_;
804: my $result;
805: my $problem=&Apache::lonnet::getfile($file);
806: if ($problem eq -1) {
807: &Apache::lonxml::error("<b> ".&mt('Unable to find').
808: " <i>$file</i></b>");
809: $problem='';
810: }
811: if (defined($env{'form.editxmltext'}) || defined($env{'form.Undo'})) {
812: my $error=&handle_save_or_undo($request,\$problem,
813: \$env{'form.editxmltext'});
814: if (!$error) { $problem=&Apache::lonnet::getfile($file); }
815: }
816: &Apache::lonhomework::showhashsubset(\%env,'^form');
817: if ( $env{'form.submit'} eq &mt('Submit Changes and View') ) {
818: &Apache::lonhomework::showhashsubset(\%env,'^form');
819: $env{'form.problemmode'}='View';
820: &renderpage($request,$file);
821: } else {
822: my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
823: my $xml_help = '<table><tr><td>'.
824: &Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
825: "Problem Editing Help").
826: '</td><td>'.
827: &Apache::loncommon::help_open_menu(undef,undef,5,'Authoring').
828: '</td></tr></table>';
829: if ($cols > 80) { $cols = 80; }
830: if ($cols < 70) { $cols = 70; }
831: if ($rows < 20) { $rows = 20; }
832: my $start_page =
833: &Apache::loncommon::start_page("EditXML $file",
834: &Apache::edit::js_change_detection());
835:
836: $result.=$start_page.
837: &renderpage($request,$file,['no_output_web'],1).
838: &Apache::lonxml::message_location().'
839: <form '.&Apache::edit::form_change_detection().' name="lonhomework" method="POST" action="'.
840: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
841: &Apache::structuretags::remember_problem_state().'
842: <input type="hidden" name="problemmode" value="'.&mt('EditXML').'" />
843: <input type="submit" name="problemmode" accesskey="d" value="'.&mt('Discard Edits and View').'" />
844: <input type="submit" '.&Apache::edit::submit_ask_anyway().'name="problemmode" accesskey="e" value="'.&mt('Edit').'" />
845: <input type="submit" name="Undo" accesskey="u" value="'.&mt('undo').'" />
846: <hr />
847: <input type="submit" name="submit" accesskey="s" value="'.&mt('Submit Changes').'" />
848: <input type="submit" name="submit" accesskey="v" value="'.&mt('Submit Changes and View').'" />
849: <hr />
850: ' . $xml_help . '
851: <textarea '.&Apache::edit::element_change_detection().' style="width:100%" rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
852: &HTML::Entities::encode($problem,'<>&"').'</textarea><br />
853: <input type="submit" name="submit" accesskey="s" value="'.&mt('Submit Changes').'" />
854: <input type="submit" name="submit" accesskey="v" value="'.&mt('Submit Changes and View').'" />
855: </form>'.&Apache::loncommon::end_page();
856: &Apache::lonxml::add_messages(\$result);
857: $request->print($result);
858: }
859: return '';
860: }
861:
862: #
863: # Render the page in whatever target desired.
864: #
865: sub renderpage {
866: my ($request,$file,$targets,$return_string) = @_;
867:
868: my @targets = @{$targets || [&get_target()]};
869: &Apache::lonhomework::showhashsubset(\%env,'form.');
870: &Apache::lonxml::debug("Running targets ".join(':',@targets));
871: my $overall_result;
872: foreach my $target (@targets) {
873: # FIXME need to do something intelligent when a problem goes
874: # from viewable to not viewable due to map conditions
875: #&setuppermissions();
876: #if ( $Apache::lonhomework::browse ne '2'
877: # && $Apache::lonhomework::browse ne 'F' ) {
878: # $request->print(" You most likely shouldn't see me.");
879: #}
880: #my $t0 = [&gettimeofday()];
881: my $output=1;
882: if ($target eq 'no_output_web') {
883: $target = 'web'; $output=0;
884: }
885: my $problem=&Apache::lonnet::getfile($file);
886: my $result;
887: if ($problem eq -1) {
888: my $filename=(split('/',$file))[-1];
889: $result.="<b> ".&mt('Unable to find')." <i>$filename</i></b>";
890: $problem='';
891: }
892:
893: my %mystyle;
894: if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
895: if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
896: if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
897:
898: &Apache::lonxml::debug("Should be parsing now");
899: $result .= &Apache::lonxml::xmlparse($request, $target, $problem,
900: &setup_vars($target),%mystyle);
901: undef($Apache::lonhomework::parsing_a_problem);
902: if (!$output) { $result = ''; }
903: #$request->print("Result follows:");
904: if ($target eq 'modified') {
905: &handle_save_or_undo($request,\$problem,\$result);
906: } else {
907: if ($target eq 'analyze') {
908: $result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
909: undef(%Apache::lonhomework::analyze);
910: }
911: #my $td=&tv_interval($t0);
912: #if ( $Apache::lonxml::debug) {
913: #$result =~ s:</body>::;
914: #$result.="<br />Spent $td seconds processing target $target\n</body>";
915: #}
916: # $request->print($result);
917: $overall_result.=$result;
918: # $request->rflush();
919: }
920: #$request->print(":Result ends");
921: #my $td=&tv_interval($t0);
922: }
923: if (!$return_string) {
924: &Apache::lonxml::add_messages(\$overall_result);
925: $request->print($overall_result);
926: $request->rflush();
927: } else {
928: return $overall_result;
929: }
930: }
931:
932: # with no arg it returns a HTML <option> list of the template titles
933: # with one arg it returns the filename associated with the arg passed
934: sub get_template_list {
935: my ($namewanted,$extension) = @_;
936: my $result;
937: my @allnames;
938: &Apache::lonxml::debug("Looking for :$extension:");
939: foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
940: my $name=&Apache::lonnet::metadata($file,'title');
941: if ($namewanted && ($name eq $namewanted)) {
942: $result=$file;
943: last;
944: } else {
945: if ($name) { push (@allnames, $name); }
946: }
947: }
948: if (@allnames && !$result) {
949: $result="<option>".&mt("Select a")." $extension ".&mt('template')."</option>\n<option>".
950: join('</option><option>',sort(@allnames)).'</option>';
951: }
952: return $result;
953: }
954:
955: sub newproblem {
956: my ($request) = @_;
957: my $extension=$request->uri;
958: $extension=~s:^.*\.([\w]+)$:$1:;
959: &Apache::lonxml::debug("Looking for :$extension:");
960: my $templatelist=&get_template_list('',$extension);
961: if ($env{'form.template'} &&
962: $env{'form.template'} ne "Select a $extension template") {
963: use File::Copy;
964: my $file = &get_template_list($env{'form.template'},$extension);
965: my $dest = &Apache::lonnet::filelocation("",$request->uri);
966: copy($file,$dest);
967: &renderpage($request,$dest);
968: } elsif($env{'form.newfile'} && !$templatelist) {
969: # I don't like hard-coded filenames but for now, this will work.
970: use File::Copy;
971: my $templatefilename =
972: $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
973: &Apache::lonxml::debug("$templatefilename");
974: my $dest = &Apache::lonnet::filelocation("",$request->uri);
975: copy($templatefilename,$dest);
976: &renderpage($request,$dest);
977: } else {
978: my $url=&HTML::Entities::encode($request->uri,'<>&"');
979: my $shownurl=$url;
980: $shownurl=~s-^/~-/priv/-;
981: my $dest = &Apache::lonnet::filelocation("",$request->uri);
982: my $errormsg;
983: if ($env{'form.newfile'}) {
984: $errormsg='<p><font color="red">'.&mt('You did not select a template.').'</font></p>'."\n";
985: }
986: my $instructions;
987: my $start_page =
988: &Apache::loncommon::start_page("Create New $extension");
989: if ($templatelist) { $instructions=&mt(", select a template from the pull-down menu below.").'<br />'.&mt("Then");}
990: my %lt=&Apache::lonlocal::texthash( 'create' => 'Creating a new',
991: 'resource' => 'resource',
992: 'requested' => 'The requested file',
993: 'not exist' => 'currently does not exist',
994: 'createnew' => 'To create a new',
995: 'click' => 'click on the',
996: 'Create' => 'Create',
997: 'button' => 'button');
998: my $extensionTranslated = &mt($extension);
999: $request->print("
1000: $start_page
1001: <h1>".&mt("Creating a new $extension resource.")."</h1>
1002: $errormsg
1003: ".&mt("The requested file [_1] currently does not exist.",
1004: "<tt>$shownurl</tt>")."
1005: <p>
1006: <b>
1007: ".&mt("To create a new $extension, select a template from the".
1008: "pull-down menu below. Then click on the \"Create $extension\" button.")."</b>
1009: </p>");
1010:
1011: if (defined($templatelist)) {
1012: $request->print("<select name=\"template\">$templatelist</select>");
1013: }
1014: $request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"".&mt('Create')." $extension\" />");
1015: $request->print("</form></p>".&Apache::loncommon::end_page());
1016: }
1017: return '';
1018: }
1019:
1020: sub handler {
1021: #my $t0 = [&gettimeofday()];
1022: my $request=$_[0];
1023: $Apache::lonxml::request=$request;
1024: $Apache::lonxml::debug=$env{'user.debug'};
1025: $env{'request.uri'}=$request->uri;
1026: &setuppermissions();
1027: # some times multiple problemmodes are submitted, need to select
1028: # the last one
1029: if ( defined($env{'form.problemmode'}) && ref($env{'form.problemmode'}) ) {
1030: my $mode=$env{'form.problemmode'}->[-1];
1031: undef $env{'form.problemmode'};
1032: $env{'form.problemmode'}=$mode;
1033: }
1034:
1035: my $file=&Apache::lonnet::filelocation("",$request->uri);
1036:
1037: #check if we know where we are
1038: if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) {
1039: # if we are browsing we might not be able to know where we are
1040: if ($Apache::lonhomework::browse ne 'F' &&
1041: $env{'request.state'} ne "construct") {
1042: #should know where we are, so ask
1043: &unset_permissions();
1044: $request->internal_redirect('/adm/ambiguous');
1045: return OK;
1046: }
1047: }
1048: if (&setupheader($request)) {
1049: &unset_permissions();
1050: return OK;
1051: }
1052: &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1053: &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1054: my ($symb) = &Apache::lonxml::whichuser();
1055: &Apache::lonxml::debug('symb is '.$symb);
1056: if ($env{'request.state'} eq "construct") {
1057: if ( -e $file ) {
1058: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1059: ['problemmode']);
1060: if (!(defined $env{'form.problemmode'})) {
1061: #first visit to problem in construction space
1062: $env{'form.problemmode'}='View';
1063: &renderpage($request,$file);
1064: } elsif ($env{'form.problemmode'} eq &mt('EditXML') ||
1065: $env{'form.problemmode'} eq 'EditXML') {
1066: &editxmlmode($request,$file);
1067: } elsif ($env{'form.problemmode'} eq &mt('Calculate answers')) {
1068: &analyze($request,$file);
1069: } else {
1070: &renderpage($request,$file);
1071: }
1072: } else {
1073: # requested file doesn't exist in contruction space
1074: &newproblem($request);
1075: }
1076: } else {
1077: # just render the page normally outside of construction space
1078: &Apache::lonxml::debug("not construct");
1079: &renderpage($request,$file);
1080: }
1081: #my $td=&tv_interval($t0);
1082: #&Apache::lonxml::debug("Spent $td seconds processing");
1083: # always turn off debug messages
1084: $Apache::lonxml::debug=0;
1085: &unset_permissions();
1086: return OK;
1087:
1088: }
1089:
1090: 1;
1091: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>