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