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