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