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