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