1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Homework handler
3: #
4: # $Id: lonhomework.pm,v 1.251 2006/06/20 03:33:55 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.$id.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.$id.availablestudent")),
273: split(':',&Apache::lonnet::EXT("resource.$id.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: }
316:
317: &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
318:
319: # no slot is currently open, and has been checked in for this version
320: # but hasn't got a grade, therefore must be awaiting a grade
321: if (!defined($slot_name)
322: && $checkedin
323: && !$got_grade) {
324: return ('WAITING_FOR_GRADE');
325: }
326:
327: if ($slotstatus eq 'NOT_IN_A_SLOT'
328: && $checkedin ) {
329:
330: if ($got_grade) {
331: return ('SHOW_ANSWER');
332: } else {
333: return ('WAITING_FOR_GRADE');
334: }
335:
336: }
337: if ( $is_correct) {
338: return ('SHOW_ANSWER');
339: }
340: if ( $status eq 'CANNOT_ANSWER' &&
341: ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
342: return ($status,$datemsg);
343: }
344:
345: return ($slotstatus,$datemsg,$slot_name,$returned_slot);
346: }
347:
348: # JB, 9/24/2002: Any changes in this function may require a change
349: # in lonnavmaps::resource::getDateStatus.
350: sub check_access {
351: my ($id) = @_;
352: my $date ='';
353: my $status;
354: my $datemsg = '';
355: my $lastdate = '';
356: my $type;
357: my $passed;
358:
359: if ($env{'request.state'} eq "construct") {
360: if ($env{'form.problemstate'}) {
361: if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
362: if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' &&
363: lc($Apache::lonhomework::problemstatus) eq 'no')) {
364: return ('CANNOT_ANSWER',
365: &mt('is in this state due to author settings.'));
366: }
367: } else {
368: return ($env{'form.problemstate'},
369: &mt('is in this state due to author settings.'));
370: }
371: }
372: &Apache::lonxml::debug("in construction ignoring dates");
373: $status='CAN_ANSWER';
374: $datemsg=&mt('is in under construction');
375: # return ($status,$datemsg);
376: }
377:
378: &Apache::lonxml::debug("checking for part :$id:");
379: &Apache::lonxml::debug("time:".time);
380:
381: my ($symb)=&Apache::lonxml::whichuser();
382: &Apache::lonxml::debug("symb:".$symb);
383: #if ($env{'request.state'} ne "construct" && $symb ne '') {
384: if ($env{'request.state'} ne "construct") {
385: my $allowed=&check_ip_acc(&Apache::lonnet::EXT("resource.$id.acc"));
386: if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
387: $status='INVALID_ACCESS';
388: $date=&mt("can not be accessed from your location.");
389: return($status,$date);
390: }
391:
392: foreach my $temp ("opendate","duedate","answerdate") {
393: $lastdate = $date;
394: if ($temp eq 'duedate') {
395: $date = &due_date($id);
396: } else {
397: $date = &Apache::lonnet::EXT("resource.$id.$temp");
398: }
399:
400: my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
401: if ($thistype =~ /^(con_lost|no_such_host)/ ||
402: $date =~ /^(con_lost|no_such_host)/) {
403: $status='UNAVAILABLE';
404: $date=&mt("may open later.");
405: return($status,$date);
406: }
407: if ($thistype eq 'date_interval') {
408: if ($temp eq 'opendate') {
409: $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
410: }
411: if ($temp eq 'answerdate') {
412: $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
413: }
414: }
415: &Apache::lonxml::debug("found :$date: for :$temp:");
416: if ($date eq '') {
417: $date = &mt("an unknown date"); $passed = 0;
418: } elsif ($date eq 'con_lost') {
419: $date = &mt("an indeterminate date"); $passed = 0;
420: } else {
421: if (time < $date) { $passed = 0; } else { $passed = 1; }
422: $date = localtime $date;
423: }
424: if (!$passed) { $type=$temp; last; }
425: }
426: &Apache::lonxml::debug("have :$type:$passed:");
427: if ($passed) {
428: $status='SHOW_ANSWER';
429: $datemsg=$date;
430: } elsif ($type eq 'opendate') {
431: $status='CLOSED';
432: $datemsg = &mt("will open on")." $date";
433: } elsif ($type eq 'duedate') {
434: $status='CAN_ANSWER';
435: $datemsg = &mt("is due at")." $date";
436: } elsif ($type eq 'answerdate') {
437: $status='CLOSED';
438: $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
439: }
440: }
441: if ($status eq 'CAN_ANSWER' ||
442: (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
443: #check #tries, and if correct.
444: my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
445: my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
446: if ( $tries eq '' ) { $tries = '0'; }
447: if ( $maxtries eq '' &&
448: $env{'request.state'} ne 'construct') { $maxtries = '2'; }
449: if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
450: # if (correct and show prob status) or excused then CANNOT_ANSWER
451: if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
452: &&
453: lc($Apache::lonhomework::problemstatus) ne 'no')
454: ||
455: $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
456: $status = 'CANNOT_ANSWER';
457: }
458: }
459: if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
460: my $interval=&Apache::lonnet::EXT("resource.$id.interval");
461: &Apache::lonxml::debug("looking for interval $interval");
462: if ($interval) {
463: my $first_access=&Apache::lonnet::get_first_access('map');
464: &Apache::lonxml::debug("looking for accesstime $first_access");
465: if (!$first_access) {
466: $status='NOT_YET_VIEWED';
467: my $due_date = &due_date($id);
468: $datemsg=&seconds_to_human_length($due_date-time);
469: }
470: }
471: }
472:
473: #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
474: # (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
475: # return ('UNCHECKEDOUT','needs to be checked out');
476: #}
477:
478:
479: &Apache::lonxml::debug("sending back :$status:$datemsg:");
480: if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
481: &Apache::lonxml::debug("should be allowed to browse a resource when closed");
482: $status='CAN_ANSWER';
483: $datemsg=&mt('is closed but you are allowed to view it');
484: }
485:
486: return ($status,$datemsg);
487: }
488: # this should work exactly like the copy in lonnavmaps.pm
489: sub due_date {
490: my ($part_id,$symb,$udom,$uname)=@_;
491: my $date;
492: my $interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
493: $udom,$uname);
494: &Apache::lonxml::debug("looking for interval $part_id $symb $interval");
495: my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
496: $udom,$uname);
497: &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
498: if (defined($interval)) {
499: my $first_access=&Apache::lonnet::get_first_access('map',$symb);
500: if (defined($first_access)) {
501: $interval = $first_access+$interval;
502: $date = ($interval < $due_date)? $interval : $due_date;
503: } else {
504: $date = $due_date;
505: }
506: } else {
507: $date = $due_date;
508: }
509: return $date
510: }
511:
512: sub seconds_to_human_length {
513: my ($length)=@_;
514:
515: my $seconds=$length%60; $length=int($length/60);
516: my $minutes=$length%60; $length=int($length/60);
517: my $hours=$length%24; $length=int($length/24);
518: my $days=$length;
519:
520: my $timestr;
521: if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
522: if ($hours > 0) { $timestr.=($timestr?", ":"").
523: &mt('[quant,_1,hour]',$hours); }
524: if ($minutes > 0) { $timestr.=($timestr?", ":"").
525: &mt('[quant,_1,minute]',$minutes); }
526: if ($seconds > 0) { $timestr.=($timestr?", ":"").
527: &mt('[quant,_1,second]',$seconds); }
528: return $timestr;
529: }
530:
531: sub showhash {
532: my (%hash) = @_;
533: &showhashsubset(\%hash,'.');
534: return '';
535: }
536:
537: sub showarray {
538: my ($array)=@_;
539: my $string="(";
540: foreach my $elm (@{ $array }) {
541: if (ref($elm) eq 'ARRAY') {
542: $string.=&showarray($elm);
543: } elsif (ref($elm) eq 'HASH') {
544: $string.= "HASH --- \n<br />";
545: $string.= &showhashsubset($elm,'.');
546: } else {
547: $string.="$elm,"
548: }
549: }
550: chop($string);
551: $string.=")";
552: return $string;
553: }
554:
555: sub showhashsubset {
556: my ($hash,$keyre) = @_;
557: my $resultkey;
558: foreach $resultkey (sort keys %$hash) {
559: if ($resultkey !~ /$keyre/) { next; }
560: if (ref($$hash{$resultkey}) eq 'ARRAY' ) {
561: &Apache::lonxml::debug("$resultkey ---- ".
562: &showarray($$hash{$resultkey}));
563: } elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
564: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
565: &showhashsubset($$hash{$resultkey},'.');
566: } else {
567: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
568: }
569: }
570: &Apache::lonxml::debug("\n<br />restored values^</br>\n");
571: return '';
572: }
573:
574: sub setuppermissions {
575: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
576: my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
577: if (! $viewgrades &&
578: exists($env{'request.course.sec'}) &&
579: $env{'request.course.sec'} !~ /^\s*$/) {
580: $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
581: '/'.$env{'request.course.sec'});
582: }
583: $Apache::lonhomework::viewgrades = $viewgrades;
584:
585: if ($Apache::lonhomework::browse eq 'F' &&
586: $env{'form.devalidatecourseresdata'} eq 'on') {
587: my (undef,$courseid) = &Apache::lonxml::whichuser();
588: &Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
589: $env{"course.$courseid.domain"});
590: }
591:
592: my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
593: if (! $modifygrades &&
594: exists($env{'request.course.sec'}) &&
595: $env{'request.course.sec'} !~ /^\s*$/) {
596: $modifygrades =
597: &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
598: '/'.$env{'request.course.sec'});
599: }
600: $Apache::lonhomework::modifygrades = $modifygrades;
601:
602: my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
603: if (! $queuegrade &&
604: exists($env{'request.course.sec'}) &&
605: $env{'request.course.sec'} !~ /^\s*$/) {
606: $queuegrade =
607: &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
608: '/'.$env{'request.course.sec'});
609: }
610: $Apache::lonhomework::queuegrade = $queuegrade;
611: return '';
612: }
613:
614: sub setupheader {
615: my $request=$_[0];
616: &Apache::loncommon::content_type($request,'text/html');
617: if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
618: &Apache::loncommon::no_cache($request);
619: }
620: # $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
621: # 'lastrevisiondate'));
622: $request->send_http_header;
623: return OK if $request->header_only;
624: return ''
625: }
626:
627: sub handle_save_or_undo {
628: my ($request,$problem,$result) = @_;
629: my $file = &Apache::lonnet::filelocation("",$request->uri);
630: my $filebak =$file.".bak";
631: my $filetmp =$file.".tmp";
632: my $error=0;
633:
634: &Apache::lonnet::correct_line_ends($result);
635:
636: if ($env{'form.Undo'} eq &mt('undo')) {
637: my $error=0;
638: if (!copy($file,$filetmp)) { $error=1; }
639: if ((!$error) && (!copy($filebak,$file))) { $error=1; }
640: if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
641: if (!$error) {
642: &Apache::lonxml::info("<p><b>".&mt("Undid changes, Switched")." $filebak ".&mt("and")." $file</b></p>");
643: } else {
644: &Apache::lonxml::info("<p><font color=\"red\" size=\"+1\"><b>".&mt("Unable to undo, unable to switch")." $filebak ".&mt("and")." $file</b></font></p>");
645: $error=1;
646: }
647: } else {
648: my $fs=Apache::File->new(">$filebak");
649: if (defined($fs)) {
650: print $fs $$problem;
651: &Apache::lonxml::info("<b>".&mt("Making Backup to").
652: " $filebak</b>");
653: } else {
654: &Apache::lonxml::info("<font color=\"red\" size=\"+1\"><b>".&mt("Unable to make backup")." $filebak</b></font>");
655: $error=2;
656: }
657: my $fh=Apache::File->new(">$file");
658: if (defined($fh)) {
659: print $fh $$result;
660: &Apache::lonxml::info("<b>".&mt("Saving Modifications to").
661: " $file</b>");
662: } else {
663: &Apache::lonxml::info("<font color=\"red\" size=\"+1\"><b>".
664: &mt("Unable to write to")." $file</b></font>");
665: $error|=4;
666: }
667: }
668: return $error;
669: }
670:
671: sub analyze_header {
672: my ($request) = @_;
673: my $result =
674: &Apache::loncommon::start_page('Analyzing a problem',undef);
675:
676: $result .=
677: &Apache::lonxml::message_location().'
678: <form name="lonhomework" method="POST" action="'.
679: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
680: &Apache::structuretags::remember_problem_state().'
681: <input type="submit" name="problemmode" value="'.&mt("EditXML").'" />
682: <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
683: <hr />
684: <input type="submit" name="submit" value="'.&mt("View").'" />
685: <hr />
686: </form>';
687: &Apache::lonxml::add_messages(\$result);
688: $request->print($result);
689: $request->rflush();
690: }
691:
692: sub analyze_footer {
693: my ($request) = @_;
694: $request->print(&Apache::loncommon::end_page());
695: $request->rflush();
696: }
697:
698: sub analyze {
699: my ($request,$file) = @_;
700: &Apache::lonxml::debug("Analyze");
701: my $result;
702: my %overall;
703: my %seedexample;
704: my %allparts;
705: my $rndseed=$env{'form.rndseed'};
706: &analyze_header($request);
707: my %prog_state=
708: &Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
709: &mt('Getting Problem Variants'),
710: $env{'form.numtoanalyze'},
711: 'inline',undef);
712: for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
713: &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
714: &mt('last problem'));
715: if (&Apache::loncommon::connection_aborted($request)) { return; }
716: my $thisseed=$i+$rndseed;
717: my $subresult=&Apache::lonnet::ssi($request->uri,
718: ('grade_target' => 'analyze'),
719: ('rndseed' => $thisseed));
720: (my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
721: my %analyze=&Apache::lonnet::str2hash($subresult);
722: my @parts;
723: if (defined(@{ $analyze{'parts'} })) {
724: @parts=@{ $analyze{'parts'} };
725: }
726: foreach my $part (@parts) {
727: if (!exists($allparts{$part})) {$allparts{$part}=1;};
728: if ($analyze{$part.'.type'} eq 'numericalresponse' ||
729: $analyze{$part.'.type'} eq 'stringresponse' ||
730: $analyze{$part.'.type'} eq 'formularesponse' ) {
731: my $concatanswer=join("\0",@{ $analyze{$part.'.answer'} });
732: if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
733: @{$analyze{$part.'.answer'}}=('<font color="red">'.&mt('Error').'</font>');
734: }
735: push( @{ $overall{$part.'.answer'} },
736: [@{ $analyze{$part.'.answer'} }]);
737: $seedexample{join("\0",@{ $analyze{$part.'.answer'}})}=$thisseed;
738: }
739: }
740: }
741: &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
742: &mt('Analyzing Results'));
743: $request->print('<hr />'.&mt('List of possible answers').': ');
744: foreach my $part (sort(keys(%allparts))) {
745: if (defined(@{ $overall{$part.'.answer'} })) {
746: my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
747: $request->print('<table class="thinborder"><tr><th colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part.'</th></tr>');
748: my %frequency;
749: foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
750: $frequency{join("\0",@{ $answer })}++;
751: }
752: $request->print('<tr><th colspan="'.($num_cols).'">'.&mt('Answer').'</th><th>'.&mt('Frequency').'<br />('
753: .&mt('click for example').')</th></tr>');
754: foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
755: $request->print('<tr><td class="center">'.
756: join('</td><td class="center">',split("\0",$answer)).
757: '</td><td class="center"><a href="'.$request->uri.'?rndseed='.$seedexample{$answer}.'">'.$frequency{$answer}.
758: '</a></td></tr>');
759: }
760: $request->print('</table>');
761: } else {
762: $request->print('<p>'.&mt('Response').' '.$part.' '.
763: &mt('is not analyzable at this time').'</p>');
764: }
765: }
766: if (scalar(keys(%allparts)) == 0 ) {
767: $request->print('<p>'.&mt('Found no analyzable responses in this problem, currently only Numerical, Formula and String response styles are supported.').'</p>');
768: }
769: &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
770: &analyze_footer($request);
771: &Apache::lonhomework::showhash(%overall);
772: return $result;
773: }
774:
775: sub editxmlmode {
776: my ($request,$file) = @_;
777: my $result;
778: my $problem=&Apache::lonnet::getfile($file);
779: if ($problem eq -1) {
780: &Apache::lonxml::error("<b> ".&mt('Unable to find').
781: " <i>$file</i></b>");
782: $problem='';
783: }
784: if (defined($env{'form.editxmltext'}) || defined($env{'form.Undo'})) {
785: my $error=&handle_save_or_undo($request,\$problem,
786: \$env{'form.editxmltext'});
787: if (!$error) { $problem=&Apache::lonnet::getfile($file); }
788: }
789: &Apache::lonhomework::showhashsubset(\%env,'^form');
790: if ( $env{'form.submit'} eq &mt('Submit Changes and View') ) {
791: &Apache::lonhomework::showhashsubset(\%env,'^form');
792: $env{'form.problemmode'}='View';
793: &renderpage($request,$file);
794: } else {
795: my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
796: my $xml_help = '<table><tr><td>'.
797: &Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
798: "Problem Editing Help").
799: '</td><td>'.
800: &Apache::loncommon::help_open_menu('',undef,undef,undef,5,'Authoring').
801: '</td></tr></table>';
802: if ($cols > 80) { $cols = 80; }
803: if ($cols < 70) { $cols = 70; }
804: if ($rows < 20) { $rows = 20; }
805: my $start_page =
806: &Apache::loncommon::start_page("EditXML $file",
807: &Apache::edit::js_change_detection());
808:
809: $result.=$start_page.
810: &renderpage($request,$file,['no_output_web'],1).
811: &Apache::lonxml::message_location().'
812: <form '.&Apache::edit::form_change_detection().' name="lonhomework" method="POST" action="'.
813: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
814: &Apache::structuretags::remember_problem_state().'
815: <input type="hidden" name="problemmode" value="'.&mt('EditXML').'" />
816: <input type="submit" name="problemmode" accesskey="d" value="'.&mt('Discard Edits and View').'" />
817: <input type="submit" '.&Apache::edit::submit_ask_anyway().'name="problemmode" accesskey="e" value="'.&mt('Edit').'" />
818: <input type="submit" name="Undo" accesskey="u" value="'.&mt('undo').'" />
819: <hr />
820: <input type="submit" name="submit" accesskey="s" value="'.&mt('Submit Changes').'" />
821: <input type="submit" name="submit" accesskey="v" value="'.&mt('Submit Changes and View').'" />
822: <hr />
823: ' . $xml_help . '
824: <textarea '.&Apache::edit::element_change_detection().' style="width:100%" rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
825: &HTML::Entities::encode($problem,'<>&"').'</textarea><br />
826: <input type="submit" name="submit" accesskey="s" value="'.&mt('Submit Changes').'" />
827: <input type="submit" name="submit" accesskey="v" value="'.&mt('Submit Changes and View').'" />
828: </form>'.&Apache::loncommon::end_page();
829: &Apache::lonxml::add_messages(\$result);
830: $request->print($result);
831: }
832: return '';
833: }
834:
835: #
836: # Render the page in whatever target desired.
837: #
838: sub renderpage {
839: my ($request,$file,$targets,$return_string) = @_;
840:
841: my @targets = @{$targets || [&get_target()]};
842: &Apache::lonhomework::showhashsubset(\%env,'form.');
843: &Apache::lonxml::debug("Running targets ".join(':',@targets));
844: my $overall_result;
845: foreach my $target (@targets) {
846: # FIXME need to do something intelligent when a problem goes
847: # from viewable to not viewable due to map conditions
848: #&setuppermissions();
849: #if ( $Apache::lonhomework::browse ne '2'
850: # && $Apache::lonhomework::browse ne 'F' ) {
851: # $request->print(" You most likely shouldn't see me.");
852: #}
853: #my $t0 = [&gettimeofday()];
854: my $output=1;
855: if ($target eq 'no_output_web') {
856: $target = 'web'; $output=0;
857: }
858: my $problem=&Apache::lonnet::getfile($file);
859: my $result;
860: if ($problem eq -1) {
861: my $filename=(split('/',$file))[-1];
862: $result.="<b> ".&mt('Unable to find')." <i>$filename</i></b>";
863: $problem='';
864: }
865:
866: my %mystyle;
867: if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
868: if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
869: if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
870:
871: &Apache::lonxml::debug("Should be parsing now");
872: $result .= &Apache::lonxml::xmlparse($request, $target, $problem,
873: &setup_vars($target),%mystyle);
874: undef($Apache::lonhomework::parsing_a_problem);
875: if (!$output) { $result = ''; }
876: #$request->print("Result follows:");
877: if ($target eq 'modified') {
878: &handle_save_or_undo($request,\$problem,\$result);
879: } else {
880: if ($target eq 'analyze') {
881: $result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
882: undef(%Apache::lonhomework::analyze);
883: }
884: #my $td=&tv_interval($t0);
885: #if ( $Apache::lonxml::debug) {
886: #$result =~ s:</body>::;
887: #$result.="<br />Spent $td seconds processing target $target\n</body>";
888: #}
889: # $request->print($result);
890: $overall_result.=$result;
891: # $request->rflush();
892: }
893: #$request->print(":Result ends");
894: #my $td=&tv_interval($t0);
895: }
896: if (!$return_string) {
897: &Apache::lonxml::add_messages(\$overall_result);
898: $request->print($overall_result);
899: $request->rflush();
900: } else {
901: return $overall_result;
902: }
903: }
904:
905: # with no arg it returns a HTML <option> list of the template titles
906: # with one arg it returns the filename associated with the arg passed
907: sub get_template_list {
908: my ($namewanted,$extension) = @_;
909: my $result;
910: my @allnames;
911: &Apache::lonxml::debug("Looking for :$extension:");
912: foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
913: my $name=&Apache::lonnet::metadata($file,'title');
914: if ($namewanted && ($name eq $namewanted)) {
915: $result=$file;
916: last;
917: } else {
918: if ($name) { push (@allnames, $name); }
919: }
920: }
921: if (@allnames && !$result) {
922: $result="<option>".&mt("Select a")." $extension ".&mt('template')."</option>\n<option>".
923: join('</option><option>',sort(@allnames)).'</option>';
924: }
925: return $result;
926: }
927:
928: sub newproblem {
929: my ($request) = @_;
930: my $extension=$request->uri;
931: $extension=~s:^.*\.([\w]+)$:$1:;
932: &Apache::lonxml::debug("Looking for :$extension:");
933: my $templatelist=&get_template_list('',$extension);
934: if ($env{'form.template'} &&
935: $env{'form.template'} ne "Select a $extension template") {
936: use File::Copy;
937: my $file = &get_template_list($env{'form.template'},$extension);
938: my $dest = &Apache::lonnet::filelocation("",$request->uri);
939: copy($file,$dest);
940: &renderpage($request,$dest);
941: } elsif($env{'form.newfile'} && !$templatelist) {
942: # I don't like hard-coded filenames but for now, this will work.
943: use File::Copy;
944: my $templatefilename =
945: $request->dir_config('lonIncludes').'/templates/blank.problem';
946: &Apache::lonxml::debug("$templatefilename");
947: my $dest = &Apache::lonnet::filelocation("",$request->uri);
948: copy($templatefilename,$dest);
949: &renderpage($request,$dest);
950: } else {
951: my $url=&HTML::Entities::encode($request->uri,'<>&"');
952: my $shownurl=$url;
953: $shownurl=~s-^/~-/priv/-;
954: my $dest = &Apache::lonnet::filelocation("",$request->uri);
955: my $errormsg;
956: if ($env{'form.newfile'}) {
957: $errormsg='<p><font color="red">'.&mt('You did not select a template.').'</font></p>'."\n";
958: }
959: my $instructions;
960: my $start_page =
961: &Apache::loncommon::start_page("Create New $extension");
962: if ($templatelist) { $instructions=&mt(", select a template from the pull-down menu below.").'<br />'.&mt("Then");}
963: my %lt=&Apache::lonlocal::texthash( 'create' => 'Creating a new',
964: 'resource' => 'resource',
965: 'requested' => 'The requested file',
966: 'not exist' => 'currently does not exist',
967: 'createnew' => 'To create a new',
968: 'click' => 'click on the',
969: 'Create' => 'Create',
970: 'button' => 'button');
971: $request->print(<<ENDNEWPROBLEM);
972: $start_page
973: <h1>$lt{'create'} $extension $lt{'resource'}</h1>
974: $errormsg
975: $lt{'requested'} <tt>$shownurl</tt> $lt{'not exist'}.
976: <p>
977: <b>$lt{'createnew'} $extension$instructions $lt{'click'} "$lt{'Create'} $extension" $lt{'button'}.</b>
978: </p>
979: <p><form action="$url" method="POST">
980: ENDNEWPROBLEM
981: if (defined($templatelist)) {
982: $request->print("<select name=\"template\">$templatelist</select>");
983: }
984: $request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"".&mt('Create')." $extension\" />");
985: $request->print("</form></p>".&Apache::loncommon::end_page());
986: }
987: return '';
988: }
989:
990: sub handler {
991: #my $t0 = [&gettimeofday()];
992: my $request=$_[0];
993: $Apache::lonxml::request=$request;
994: $Apache::lonxml::debug=$env{'user.debug'};
995: $env{'request.uri'}=$request->uri;
996: &setuppermissions();
997: # some times multiple problemmodes are submitted, need to select
998: # the last one
999: if ( defined($env{'form.problemmode'}) && ref($env{'form.problemmode'}) ) {
1000: my $mode=$env{'form.problemmode'}->[-1];
1001: undef $env{'form.problemmode'};
1002: $env{'form.problemmode'}=$mode;
1003: }
1004:
1005: my $file=&Apache::lonnet::filelocation("",$request->uri);
1006:
1007: #check if we know where we are
1008: if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) {
1009: # if we are browsing we might not be able to know where we are
1010: if ($Apache::lonhomework::browse ne 'F' &&
1011: $env{'request.state'} ne "construct") {
1012: #should know where we are, so ask
1013: $request->internal_redirect('/adm/ambiguous'); return OK;
1014: }
1015: }
1016: if (&setupheader($request)) { return OK; }
1017: &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1018: &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1019: my ($symb) = &Apache::lonxml::whichuser();
1020: &Apache::lonxml::debug('symb is '.$symb);
1021: if ($env{'request.state'} eq "construct") {
1022: if ( -e $file ) {
1023: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1024: ['problemmode']);
1025: if (!(defined $env{'form.problemmode'})) {
1026: #first visit to problem in construction space
1027: $env{'form.problemmode'}='View';
1028: &renderpage($request,$file);
1029: } elsif ($env{'form.problemmode'} eq &mt('EditXML') ||
1030: $env{'form.problemmode'} eq 'EditXML') {
1031: &editxmlmode($request,$file);
1032: } elsif ($env{'form.problemmode'} eq &mt('Calculate answers')) {
1033: &analyze($request,$file);
1034: } else {
1035: &renderpage($request,$file);
1036: }
1037: } else {
1038: # requested file doesn't exist in contruction space
1039: &newproblem($request);
1040: }
1041: } else {
1042: # just render the page normally outside of construction space
1043: &Apache::lonxml::debug("not construct");
1044: &renderpage($request,$file);
1045: }
1046: #my $td=&tv_interval($t0);
1047: #&Apache::lonxml::debug("Spent $td seconds processing");
1048: # always turn off debug messages
1049: $Apache::lonxml::debug=0;
1050: return OK;
1051:
1052: }
1053:
1054: 1;
1055: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>