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