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