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