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