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