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