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