1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Homework handler
3: #
4: # $Id: lonhomework.pm,v 1.231 2005/12/21 19:05:05 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27:
28:
29: package Apache::lonhomework;
30: use strict;
31: use Apache::style();
32: use Apache::lonxml();
33: use Apache::lonnet;
34: use Apache::lonplot();
35: use Apache::inputtags();
36: use Apache::structuretags();
37: use Apache::randomlabel();
38: use Apache::response();
39: use Apache::hint();
40: use Apache::outputtags();
41: use Apache::caparesponse();
42: use Apache::radiobuttonresponse();
43: use Apache::optionresponse();
44: use Apache::imageresponse();
45: use Apache::essayresponse();
46: use Apache::externalresponse();
47: use Apache::rankresponse();
48: use Apache::matchresponse();
49: use Apache::chemresponse();
50: use Apache::drawimage();
51: use Apache::Constants qw(:common);
52: use HTML::Entities();
53: use Apache::loncommon();
54: use Apache::lonlocal;
55: use Time::HiRes qw( gettimeofday tv_interval );
56: use Apache::lonnet();
57:
58: # FIXME - improve commenting
59:
60:
61: BEGIN {
62: &Apache::lonxml::register_insert();
63: }
64:
65:
66: #
67: # Decides what targets to render for.
68: # Implicit inputs:
69: # Various session environment variables:
70: # request.state - published - is a /res/ resource
71: # uploaded - is a /uploaded/ resource
72: # contruct - is a /priv/ resource
73: # form.grade_target - a form parameter requesting a specific target
74: sub get_target {
75: &Apache::lonxml::debug("request.state = $env{'request.state'}");
76: if( defined($env{'form.grade_target'})) {
77: &Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
78: } else {
79: &Apache::lonxml::debug("form.grade_target <undefined>");
80: }
81: if (($env{'request.state'} eq "published") ||
82: ($env{'request.state'} eq "uploaded")) {
83: if ( defined($env{'form.grade_target'} )
84: && ($env{'form.grade_target'} eq 'tex')) {
85: return ($env{'form.grade_target'});
86: } elsif ( defined($env{'form.grade_target'} )
87: && ($Apache::lonhomework::viewgrades eq 'F' )) {
88: return ($env{'form.grade_target'});
89: }
90: if ($env{'form.webgrade'} &&
91: $Apache::lonhomework::modifygrades eq 'F') {
92: return ('grade','webgrade');
93: }
94: if ( defined($env{'form.submitted'}) &&
95: ( !defined($env{'form.resetdata'})) &&
96: ( !defined($env{'form.newrandomization'}))) {
97: return ('grade', 'web');
98: } else {
99: return ('web');
100: }
101: } elsif ($env{'request.state'} eq "construct") {
102: if ( defined($env{'form.grade_target'}) ) {
103: return ($env{'form.grade_target'});
104: }
105: if ( defined($env{'form.preview'})) {
106: if ( defined($env{'form.submitted'})) {
107: return ('grade', 'web');
108: } else {
109: return ('web');
110: }
111: } else {
112: if ( $env{'form.problemmode'} eq &mt('View') ||
113: $env{'form.problemmode'} eq &mt('Discard Edits and View')) {
114: if ( defined($env{'form.submitted'}) &&
115: (!defined($env{'form.resetdata'})) &&
116: (!defined($env{'form.newrandomization'}))) {
117: return ('grade', 'web','answer');
118: } else {
119: return ('web','answer');
120: }
121: } elsif ( $env{'form.problemmode'} eq &mt('Edit') ||
122: $env{'form.problemmode'} eq 'Edit') {
123: if ( $env{'form.submitted'} eq 'edit' ) {
124: if ( $env{'form.submit'} eq &mt('Submit Changes and View') ) {
125: return ('modified','web','answer');
126: } else {
127: return ('modified','no_output_web','edit');
128: }
129: } else {
130: return ('no_output_web','edit');
131: }
132: } else {
133: return ('web');
134: }
135: }
136: }
137: return ();
138: }
139:
140: sub setup_vars {
141: my ($target) = @_;
142: return ';'
143: # return ';$external::target='.$target.';';
144: }
145:
146: sub send_header {
147: my ($request)= @_;
148: $request->print(&Apache::lontexconvert::header());
149: # $request->print('<form name='.$env{'form.request.prefix'}.'lonhomework method="POST" action="'.$request->uri.'">');
150: }
151:
152: sub createmenu {
153: my ($which,$request)=@_;
154: if ($which eq 'grade') {
155: $request->print('<script language="JavaScript">
156: hwkmenu=window.open("/res/adm/pages/homeworkmenu.html","homeworkremote",
157: "height=350,width=150,menubar=no");
158: </script>');
159: }
160: }
161:
162: sub send_footer {
163: my ($request)= @_;
164: # $request->print('</form>');
165: $request->print(&Apache::lontexconvert::footer());
166: }
167:
168: sub proctor_checked_in {
169: my ($slot_name,$slot,$type)=@_;
170: my @possible_proctors=split(",",$slot->{'proctor'});
171:
172: my $key;
173: if ($type eq 'Task') {
174: my $version=$Apache::lonhomework::history{'resource.0.version'};
175: $key ="resource.$version.0.checkedin";
176: } elsif ($type eq 'problem') {
177: $key ='resource.0.checkedin';
178: }
179:
180: foreach my $possible (@possible_proctors) {
181: if ($Apache::lonhomework::history{$key} eq $possible
182: && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
183: return 1;
184: }
185: }
186:
187: return 0;
188: }
189:
190: $Apache::lonxml::browse='';
191: sub check_ip_acc {
192: my ($acc)=@_;
193: &Apache::lonxml::debug("acc is $acc");
194: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
195: return 1;
196: }
197: my $allowed=0;
198: my $ip=$ENV{'REMOTE_ADDR'};
199: my $name;
200: foreach my $pattern (split(',',$acc)) {
201: 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.0.checkedin"} &&
264: $Apache::lonhomework::history{"resource.$version.0.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 ($got_grade,$checkedin);
299: if ($type eq 'Task') {
300: my $version=$Apache::lonhomework::history{'resource.0.version'};
301: $got_grade =
302: ($Apache::lonhomework::history{"resource.$version.0.status"}
303: =~ /^(?:pass|fail)$/);
304: $checkedin =
305: $Apache::lonhomework::history{"resource.$version.0.checkedin"};
306: } elsif ($type eq 'problem') {
307: $got_grade = 1;
308: $checkedin = $Apache::lonhomework::history{"resource.0.checkedin"};
309: }
310:
311: if ($slotstatus eq 'NOT_IN_A_SLOT'
312: && $checkedin ) {
313:
314: if ($got_grade) {
315: return ('SHOW_ANSWER');
316: } else {
317: return ('WAITING_FOR_GRADE');
318: }
319:
320: }
321: if ( $status eq 'CANNOT_ANSWER' &&
322: ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
323: return ($status,$datemsg);
324: }
325:
326: return ($slotstatus,$datemsg,$slot_name,$returned_slot);
327: }
328:
329: # JB, 9/24/2002: Any changes in this function may require a change
330: # in lonnavmaps::resource::getDateStatus.
331: sub check_access {
332: my ($id) = @_;
333: my $date ='';
334: my $status;
335: my $datemsg = '';
336: my $lastdate = '';
337: my $type;
338: my $passed;
339:
340: if ($env{'request.state'} eq "construct") {
341: if ($env{'form.problemstate'}) {
342: if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
343: if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' &&
344: lc($Apache::lonhomework::problemstatus) eq 'no')) {
345: return ('CANNOT_ANSWER',
346: &mt('is in this state due to author settings.'));
347: }
348: } else {
349: return ($env{'form.problemstate'},
350: &mt('is in this state due to author settings.'));
351: }
352: }
353: &Apache::lonxml::debug("in construction ignoring dates");
354: $status='CAN_ANSWER';
355: $datemsg=&mt('is in under construction');
356: # return ($status,$datemsg);
357: }
358:
359: &Apache::lonxml::debug("checking for part :$id:");
360: &Apache::lonxml::debug("time:".time);
361:
362: my ($symb)=&Apache::lonxml::whichuser();
363: &Apache::lonxml::debug("symb:".$symb);
364: #if ($env{'request.state'} ne "construct" && $symb ne '') {
365: if ($env{'request.state'} ne "construct") {
366: my $allowed=&check_ip_acc(&Apache::lonnet::EXT("resource.$id.acc"));
367: if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
368: $status='INVALID_ACCESS';
369: $date=&mt("can not be accessed from your location.");
370: return($status,$date);
371: }
372:
373: foreach my $temp ("opendate","duedate","answerdate") {
374: $lastdate = $date;
375: $date = &Apache::lonnet::EXT("resource.$id.$temp");
376: my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
377: if ($thistype =~ /^(con_lost|no_such_host)/ ||
378: $date =~ /^(con_lost|no_such_host)/) {
379: $status='UNAVAILABLE';
380: $date=&mt("may open later.");
381: return($status,$date);
382: }
383: if ($thistype eq 'date_interval') {
384: if ($temp eq 'opendate') {
385: $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
386: }
387: if ($temp eq 'answerdate') {
388: $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
389: }
390: }
391: &Apache::lonxml::debug("found :$date: for :$temp:");
392: if ($date eq '') {
393: $date = &mt("an unknown date"); $passed = 0;
394: } elsif ($date eq 'con_lost') {
395: $date = &mt("an indeterminate date"); $passed = 0;
396: } else {
397: if (time < $date) { $passed = 0; } else { $passed = 1; }
398: $date = localtime $date;
399: }
400: if (!$passed) { $type=$temp; last; }
401: }
402: &Apache::lonxml::debug("have :$type:$passed:");
403: if ($passed) {
404: $status='SHOW_ANSWER';
405: $datemsg=$date;
406: } elsif ($type eq 'opendate') {
407: $status='CLOSED';
408: $datemsg = &mt("will open on")." $date";
409: } elsif ($type eq 'duedate') {
410: $status='CAN_ANSWER';
411: $datemsg = &mt("is due at")." $date";
412: } elsif ($type eq 'answerdate') {
413: $status='CLOSED';
414: $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
415: }
416: }
417: if ($status eq 'CAN_ANSWER' ||
418: (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
419: #check #tries, and if correct.
420: my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
421: my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
422: if ( $tries eq '' ) { $tries = '0'; }
423: if ( $maxtries eq '' &&
424: $env{'request.state'} ne 'construct') { $maxtries = '2'; }
425: if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
426: # if (correct and show prob status) or excused then CANNOT_ANSWER
427: if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
428: &&
429: lc($Apache::lonhomework::problemstatus) ne 'no')
430: ||
431: $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
432: $status = 'CANNOT_ANSWER';
433: }
434: }
435: if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
436: my $interval=&Apache::lonnet::EXT("resource.$id.interval");
437: &Apache::lonxml::debug("looking for interval $interval");
438: if ($interval) {
439: my $first_access=&Apache::lonnet::get_first_access('map');
440: &Apache::lonxml::debug("looking for accesstime $first_access");
441: if (!$first_access) {
442: $status='NOT_YET_VIEWED';
443: $datemsg=&seconds_to_human_length($interval);
444: } else {
445: my $newdate=localtime($first_access+$interval);
446: if (time > ($first_access+$interval)) {
447: $status='CLOSED';
448: $datemsg = &mt("was due on")." $newdate".&mt(", and answers will be available on")." $date";
449: } else {
450: $datemsg = &mt("is due at")." $newdate";
451: }
452: }
453: }
454: }
455: #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
456: # (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
457: # return ('UNCHECKEDOUT','needs to be checked out');
458: #}
459:
460:
461: &Apache::lonxml::debug("sending back :$status:$datemsg:");
462: if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
463: &Apache::lonxml::debug("should be allowed to browse a resource when closed");
464: $status='CAN_ANSWER';
465: $datemsg=&mt('is closed but you are allowed to view it');
466: }
467:
468: return ($status,$datemsg);
469: }
470:
471: sub seconds_to_human_length {
472: my ($length)=@_;
473:
474: my $seconds=$length%60; $length=int($length/60);
475: my $minutes=$length%60; $length=int($length/60);
476: my $hours=$length%24; $length=int($length/24);
477: my $days=$length;
478:
479: my $timestr;
480: if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
481: if ($hours > 0) { $timestr.=($timestr?", ":"").
482: &mt('[quant,_1,hour]',$hours); }
483: if ($minutes > 0) { $timestr.=($timestr?", ":"").
484: &mt('[quant,_1,minute]',$minutes); }
485: if ($seconds > 0) { $timestr.=($timestr?", ":"").
486: &mt('[quant,_1,second]',$seconds); }
487: return $timestr;
488: }
489:
490: sub showhash {
491: my (%hash) = @_;
492: &showhashsubset(\%hash,'.');
493: return '';
494: }
495:
496: sub showarray {
497: my ($array)=@_;
498: my $string="(";
499: foreach my $elm (@{ $array }) {
500: if (ref($elm) eq 'ARRAY') {
501: $string.=&showarray($elm);
502: } elsif (ref($elm) eq 'HASH') {
503: $string.= "HASH --- \n<br />";
504: $string.= &showhashsubset($elm,'.');
505: } else {
506: $string.="$elm,"
507: }
508: }
509: chop($string);
510: $string.=")";
511: return $string;
512: }
513:
514: sub showhashsubset {
515: my ($hash,$keyre) = @_;
516: my $resultkey;
517: foreach $resultkey (sort keys %$hash) {
518: if ($resultkey !~ /$keyre/) { next; }
519: if (ref($$hash{$resultkey}) eq 'ARRAY' ) {
520: &Apache::lonxml::debug("$resultkey ---- ".
521: &showarray($$hash{$resultkey}));
522: } elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
523: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
524: &showhashsubset($$hash{$resultkey},'.');
525: } else {
526: &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
527: }
528: }
529: &Apache::lonxml::debug("\n<br />restored values^</br>\n");
530: return '';
531: }
532:
533: sub setuppermissions {
534: $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
535: my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
536: if (! $viewgrades &&
537: exists($env{'request.course.sec'}) &&
538: $env{'request.course.sec'} !~ /^\s*$/) {
539: $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
540: '/'.$env{'request.course.sec'});
541: }
542: $Apache::lonhomework::viewgrades = $viewgrades; # File global variable...dirt.
543: if ($Apache::lonhomework::browse eq 'F' &&
544: $env{'form.devalidatecourseresdata'} eq 'on') {
545: my (undef,$courseid) = &Apache::lonxml::whichuser();
546: &Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
547: $env{"course.$courseid.domain"});
548: }
549: my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
550: if (! $modifygrades &&
551: exists($env{'request.course.sec'}) &&
552: $env{'request.course.sec'} !~ /^\s*$/) {
553: $modifygrades =
554: &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
555: '/'.$env{'request.course.sec'});
556: }
557: $Apache::lonhomework::modifygrades = $modifygrades;
558: return '';
559: }
560:
561: sub setupheader {
562: my $request=$_[0];
563: &Apache::loncommon::content_type($request,'text/html');
564: if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
565: &Apache::loncommon::no_cache($request);
566: }
567: # $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
568: # 'lastrevisiondate'));
569: $request->send_http_header;
570: return OK if $request->header_only;
571: return ''
572: }
573:
574: sub handle_save_or_undo {
575: my ($request,$problem,$result) = @_;
576: my $file = &Apache::lonnet::filelocation("",$request->uri);
577: my $filebak =$file.".bak";
578: my $filetmp =$file.".tmp";
579: my $error=0;
580:
581: &Apache::lonnet::correct_line_ends($result);
582:
583: if ($env{'form.Undo'} eq &mt('undo')) {
584: my $error=0;
585: if (!copy($file,$filetmp)) { $error=1; }
586: if ((!$error) && (!copy($filebak,$file))) { $error=1; }
587: if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
588: if (!$error) {
589: &Apache::lonxml::info("<p><b>".&mt("Undid changes, Switched")." $filebak ".&mt("and")." $file</b></p>");
590: } else {
591: &Apache::lonxml::info("<p><font color=\"red\" size=\"+1\"><b>".&mt("Unable to undo, unable to switch")." $filebak ".&mt("and")." $file</b></font></p>");
592: $error=1;
593: }
594: } else {
595: my $fs=Apache::File->new(">$filebak");
596: if (defined($fs)) {
597: print $fs $$problem;
598: &Apache::lonxml::info("<b>".&mt("Making Backup to").
599: " $filebak</b>");
600: } else {
601: &Apache::lonxml::info("<font color=\"red\" size=\"+1\"><b>".&mt("Unable to make backup")." $filebak</b></font>");
602: $error=2;
603: }
604: my $fh=Apache::File->new(">$file");
605: if (defined($fh)) {
606: print $fh $$result;
607: &Apache::lonxml::info("<b>".&mt("Saving Modifications to").
608: " $file</b>");
609: } else {
610: &Apache::lonxml::info("<font color=\"red\" size=\"+1\"><b>".
611: &mt("Unable to write to")." $file</b></font>");
612: $error|=4;
613: }
614: }
615: return $error;
616: }
617:
618: sub analyze_header {
619: my ($request) = @_;
620: my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,
621: ($env{'environment.remote'} ne 'off'));
622: my $html=&Apache::lonxml::xmlbegin();
623: my $result.=$html.'
624: <head><title>'.&mt("Analyzing a problem").'</title></head>
625: '.$bodytag.&Apache::lonxml::message_location().'
626: <form name="lonhomework" method="POST" action="'.
627: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
628: &Apache::structuretags::remember_problem_state().'
629: <input type="submit" name="problemmode" value="'.&mt("EditXML").'" />
630: <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
631: <hr />
632: <input type="submit" name="submit" value="'.&mt("View").'" />
633: <hr />
634: </form>';
635: &Apache::lonxml::add_messages(\$result);
636: $request->print($result);
637: $request->rflush();
638: }
639:
640: sub analyze_footer {
641: my ($request) = @_;
642: my $result='</body></html>';
643: $request->print($result);
644: $request->rflush();
645: }
646:
647: sub analyze {
648: my ($request,$file) = @_;
649: &Apache::lonxml::debug("Analyze");
650: my $result;
651: my %overall;
652: my %seedexample;
653: my %allparts;
654: my $rndseed=$env{'form.rndseed'};
655: &analyze_header($request);
656: my %prog_state=
657: &Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
658: &mt('Getting Problem Variants'),
659: $env{'form.numtoanalyze'},
660: 'inline',undef);
661: for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
662: &Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
663: &mt('last problem'));
664: if (&Apache::loncommon::connection_aborted($request)) { return; }
665: my $thisseed=$i+$rndseed;
666: my $subresult=&Apache::lonnet::ssi($request->uri,
667: ('grade_target' => 'analyze'),
668: ('rndseed' => $thisseed));
669: (my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
670: my %analyze=&Apache::lonnet::str2hash($subresult);
671: my @parts;
672: if (defined(@{ $analyze{'parts'} })) {
673: @parts=@{ $analyze{'parts'} };
674: }
675: foreach my $part (@parts) {
676: if (!exists($allparts{$part})) {$allparts{$part}=1;};
677: if ($analyze{$part.'.type'} eq 'numericalresponse' ||
678: $analyze{$part.'.type'} eq 'stringresponse' ||
679: $analyze{$part.'.type'} eq 'formularesponse' ) {
680: my $concatanswer=join("\0",@{ $analyze{$part.'.answer'} });
681: if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
682: @{$analyze{$part.'.answer'}}=('<font color="red">'.&mt('Error').'</font>');
683: }
684: push( @{ $overall{$part.'.answer'} },
685: [@{ $analyze{$part.'.answer'} }]);
686: $seedexample{join("\0",@{ $analyze{$part.'.answer'}})}=$thisseed;
687: }
688: }
689: }
690: &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
691: &mt('Analyzing Results'));
692: $request->print('<hr />'.&mt('List of possible answers').': ');
693: foreach my $part (sort(keys(%allparts))) {
694: if (defined(@{ $overall{$part.'.answer'} })) {
695: my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
696: $request->print('<table class="thinborder"><tr><th colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part.'</th></tr>');
697: my %frequency;
698: foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
699: $frequency{join("\0",@{ $answer })}++;
700: }
701: $request->print('<tr><th colspan="'.($num_cols).'">'.&mt('Answer').'</th><th>'.&mt('Frequency').'<br />('
702: .&mt('click for example').')</th></tr>');
703: foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
704: $request->print('<tr><td class="center">'.
705: join('</td><td class="center">',split("\0",$answer)).
706: '</td><td class="center"><a href="'.$request->uri.'?rndseed='.$seedexample{$answer}.'">'.$frequency{$answer}.
707: '</a></td></tr>');
708: }
709: $request->print('</table>');
710: } else {
711: $request->print('<p>'.&mt('Response').' '.$part.' '.
712: &mt('is not analyzable at this time').'</p>');
713: }
714: }
715: if (scalar(keys(%allparts)) == 0 ) {
716: $request->print('<p>'.&mt('Found no analyzable responses in this problem, currently only Numerical, Formula and String response styles are supported.').'</p>');
717: }
718: &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
719: &analyze_footer($request);
720: &Apache::lonhomework::showhash(%overall);
721: return $result;
722: }
723:
724: sub editxmlmode {
725: my ($request,$file) = @_;
726: my $result;
727: my $problem=&Apache::lonnet::getfile($file);
728: if ($problem eq -1) {
729: &Apache::lonxml::error("<b> ".&mt('Unable to find').
730: " <i>$file</i></b>");
731: $problem='';
732: }
733: if (defined($env{'form.editxmltext'}) || defined($env{'form.Undo'})) {
734: my $error=&handle_save_or_undo($request,\$problem,
735: \$env{'form.editxmltext'});
736: if (!$error) { $problem=&Apache::lonnet::getfile($file); }
737: }
738: &Apache::lonhomework::showhashsubset(\%env,'^form');
739: if ( $env{'form.submit'} eq &mt('Submit Changes and View') ) {
740: &Apache::lonhomework::showhashsubset(\%env,'^form');
741: $env{'form.problemmode'}='View';
742: &renderpage($request,$file);
743: } else {
744: my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
745: my $xml_help = '<table><tr><td>'.
746: &Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
747: "Problem Editing Help").
748: '</td><td>'.
749: &Apache::loncommon::help_open_menu('',undef,undef,undef,5,'Authoring').
750: '</td></tr></table>';
751: if ($cols > 80) { $cols = 80; }
752: if ($cols < 70) { $cols = 70; }
753: if ($rows < 20) { $rows = 20; }
754: my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,
755: ($env{'environment.remote'} ne 'off'));
756: my $html=&Apache::lonxml::xmlbegin();
757: my $head="<head><title>EditXML $file</title>".
758: &Apache::edit::js_change_detection()."</head>";
759:
760: $result.=$html.$head.$bodytag.
761: &renderpage($request,$file,['no_output_web'],1).
762: &Apache::lonxml::message_location().'
763: <form '.&Apache::edit::form_change_detection().' name="lonhomework" method="POST" action="'.
764: &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
765: &Apache::structuretags::remember_problem_state().'
766: <input type="hidden" name="problemmode" value="'.&mt('EditXML').'" />
767: <input type="submit" name="problemmode" accesskey="d" value="'.&mt('Discard Edits and View').'" />
768: <input type="submit" name="problemmode" accesskey="e" value="'.&mt('Edit').'" />
769: <input type="submit" name="Undo" accesskey="u" value="'.&mt('undo').'" />
770: <hr />
771: <input type="submit" name="submit" accesskey="s" value="'.&mt('Submit Changes').'" />
772: <input type="submit" name="submit" accesskey="v" value="'.&mt('Submit Changes and View').'" />
773: <hr />
774: ' . $xml_help . '
775: <textarea '.&Apache::edit::element_change_detection().' style="width:100%" rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
776: &HTML::Entities::encode($problem,'<>&"').'</textarea><br />
777: <input type="submit" name="submit" accesskey="s" value="'.&mt('Submit Changes').'" />
778: <input type="submit" name="submit" accesskey="v" value="'.&mt('Submit Changes and View').'" />
779: </form></body></html>';
780: &Apache::lonxml::add_messages(\$result);
781: $request->print($result);
782: }
783: return '';
784: }
785:
786: #
787: # Render the page in whatever target desired.
788: #
789: sub renderpage {
790: my ($request,$file,$targets,$return_string) = @_;
791:
792: my @targets = @{$targets || [&get_target()]};
793: &Apache::lonhomework::showhashsubset(\%env,'form.');
794: &Apache::lonxml::debug("Running targets ".join(':',@targets));
795: my $overall_result;
796: foreach my $target (@targets) {
797: # FIXME need to do something intelligent when a problem goes
798: # from viewable to not viewable due to map conditions
799: #&setuppermissions();
800: #if ( $Apache::lonhomework::browse ne '2'
801: # && $Apache::lonhomework::browse ne 'F' ) {
802: # $request->print(" You most likely shouldn't see me.");
803: #}
804: #my $t0 = [&gettimeofday()];
805: my $output=1;
806: if ($target eq 'no_output_web') {
807: $target = 'web'; $output=0;
808: }
809: my $problem=&Apache::lonnet::getfile($file);
810: my $result;
811: if ($problem eq -1) {
812: my $filename=(split('/',$file))[-1];
813: $result.="<b> ".&mt('Unable to find')." <i>$filename</i></b>";
814: $problem='';
815: }
816:
817: my %mystyle;
818: if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
819: if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
820: if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
821:
822: &Apache::lonxml::debug("Should be parsing now");
823: $result .= &Apache::lonxml::xmlparse($request, $target, $problem,
824: &setup_vars($target),%mystyle);
825: undef($Apache::lonhomework::parsing_a_problem);
826: if (!$output) { $result = ''; }
827: #$request->print("Result follows:");
828: if ($target eq 'modified') {
829: &handle_save_or_undo($request,\$problem,\$result);
830: } else {
831: if ($target eq 'analyze') {
832: $result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
833: undef(%Apache::lonhomework::analyze);
834: }
835: #my $td=&tv_interval($t0);
836: #if ( $Apache::lonxml::debug) {
837: #$result =~ s:</body>::;
838: #$result.="<br />Spent $td seconds processing target $target\n</body>";
839: #}
840: # $request->print($result);
841: $overall_result.=$result;
842: # $request->rflush();
843: }
844: #$request->print(":Result ends");
845: #my $td=&tv_interval($t0);
846: }
847: if (!$return_string) {
848: &Apache::lonxml::add_messages(\$overall_result);
849: $request->print($overall_result);
850: $request->rflush();
851: } else {
852: return $overall_result;
853: }
854: }
855:
856: # with no arg it returns a HTML <option> list of the template titles
857: # with one arg it returns the filename associated with the arg passed
858: sub get_template_list {
859: my ($namewanted,$extension) = @_;
860: my $result;
861: my @allnames;
862: &Apache::lonxml::debug("Looking for :$extension:");
863: foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
864: my $name=&Apache::lonnet::metadata($file,'title');
865: if ($namewanted && ($name eq $namewanted)) {
866: $result=$file;
867: last;
868: } else {
869: if ($name) { push (@allnames, $name); }
870: }
871: }
872: if (@allnames && !$result) {
873: $result="<option>".&mt("Select a")." $extension ".&mt('template')."</option>\n<option>".
874: join('</option><option>',sort(@allnames)).'</option>';
875: }
876: return $result;
877: }
878:
879: sub newproblem {
880: my ($request) = @_;
881: my $extension=$request->uri;
882: $extension=~s:^.*\.([\w]+)$:$1:;
883: &Apache::lonxml::debug("Looking for :$extension:");
884: my $templatelist=&get_template_list('',$extension);
885: if ($env{'form.template'} &&
886: $env{'form.template'} ne "Select a $extension template") {
887: use File::Copy;
888: my $file = &get_template_list($env{'form.template'},$extension);
889: my $dest = &Apache::lonnet::filelocation("",$request->uri);
890: copy($file,$dest);
891: &renderpage($request,$dest);
892: } elsif($env{'form.newfile'} && !$templatelist) {
893: # I don't like hard-coded filenames but for now, this will work.
894: use File::Copy;
895: my $templatefilename =
896: $request->dir_config('lonIncludes').'/templates/blank.problem';
897: &Apache::lonxml::debug("$templatefilename");
898: my $dest = &Apache::lonnet::filelocation("",$request->uri);
899: copy($templatefilename,$dest);
900: &renderpage($request,$dest);
901: } else {
902: my $url=&HTML::Entities::encode($request->uri,'<>&"');
903: my $shownurl=$url;
904: $shownurl=~s-^/~-/priv/-;
905: my $dest = &Apache::lonnet::filelocation("",$request->uri);
906: my $errormsg;
907: if ($env{'form.newfile'}) {
908: $errormsg='<p><font color="red">'.&mt('You did not select a template.').'</font></p>'."\n";
909: }
910: my $instructions;
911: my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,
912: ($env{'environment.remote'} ne 'off'));
913: if ($templatelist) { $instructions=&mt(", select a template from the pull-down menu below.").'<br />'.&mt("Then");}
914: my %lt=&Apache::lonlocal::texthash( 'create' => 'Creating a new',
915: 'resource' => 'resource',
916: 'requested' => 'The requested file',
917: 'not exist' => 'currently does not exist',
918: 'createnew' => 'To create a new',
919: 'click' => 'click on the',
920: 'Create' => 'Create',
921: 'button' => 'button');
922: $request->print(<<ENDNEWPROBLEM);
923: $bodytag
924: <h1>$lt{'create'} $extension $lt{'resource'}</h1>
925: $errormsg
926: $lt{'requested'} <tt>$shownurl</tt> $lt{'not exist'}.
927: <p>
928: <b>$lt{'createnew'} $extension$instructions $lt{'click'} "$lt{'Create'} $extension" $lt{'button'}.</b>
929: </p>
930: <p><form action="$url" method="POST">
931: ENDNEWPROBLEM
932: if (defined($templatelist)) {
933: $request->print("<select name=\"template\">$templatelist</select>");
934: }
935: $request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"".&mt('Create')." $extension\" />");
936: $request->print("</form></p></body>");
937: }
938: return '';
939: }
940:
941: sub view_or_edit_menu {
942: my ($request) = @_;
943: my $url=&HTML::Entities::encode($request->uri,'<>&"');
944: my %lt=&Apache::lonlocal::texthash( 'would' => 'Would you like to',
945: 'view' => 'View',
946: 'Edit' => 'edit',
947: 'or' => 'or',
948: 'the problem' => 'the problem');
949: $request->print(<<EDITMENU);
950: <body bgcolor="#FFFFFF">
951: <form action="$url" method="POST">
952: $lt{'would'} <input type="submit" name="problemmode" accesskey="v" value="<{'view'}">
953: <{'or'} <input type="submit" name="problemmode" accesskey="e" value="<{'Edit'}">
954: <{'the problem'}.
955: </form>
956: </body>
957: EDITMENU
958: }
959:
960: sub handler {
961: #my $t0 = [&gettimeofday()];
962: my $request=$_[0];
963: $Apache::lonxml::request=$request;
964: $Apache::lonxml::debug=$env{'user.debug'};
965: $env{'request.uri'}=$request->uri;
966: &setuppermissions();
967: # some times multiple problemmodes are submitted, need to select
968: # the last one
969: if ( defined($env{'form.problemmode'}) && ref($env{'form.problemmode'}) ) {
970: my $mode=$env{'form.problemmode'}->[-1];
971: undef $env{'form.problemmode'};
972: $env{'form.problemmode'}=$mode;
973: }
974:
975: my $file=&Apache::lonnet::filelocation("",$request->uri);
976:
977: #check if we know where we are
978: if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) {
979: # if we are browsing we might not be able to know where we are
980: if ($Apache::lonhomework::browse ne 'F' &&
981: $env{'request.state'} ne "construct") {
982: #should know where we are, so ask
983: $request->internal_redirect('/adm/ambiguous'); return OK;
984: }
985: }
986: if (&setupheader($request)) { return OK; }
987: &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:");
988: &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
989: my ($symb) = &Apache::lonxml::whichuser();
990: &Apache::lonxml::debug('symb is '.$symb);
991: if ($env{'request.state'} eq "construct" || $symb eq '') {
992: if ($env{'form.resetdata'} eq &mt('Reset Submissions') ||
993: $env{'form.resetdata'} eq &mt('New Problem Variation') ||
994: $env{'form.newrandomization'} eq &mt('New Randomization')) {
995: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
996: &Apache::lonnet::tmpreset($symb,'',$domain,$name);
997: &Apache::lonxml::debug("Attempt reset");
998: }
999: }
1000: if ($env{'request.state'} eq "construct") {
1001: if ( -e $file ) {
1002: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1003: ['problemmode']);
1004: if (!(defined $env{'form.problemmode'})) {
1005: #first visit to problem in construction space
1006: #&view_or_edit_menu($request);
1007: $env{'form.problemmode'}='View';
1008: &renderpage($request,$file);
1009: } elsif ($env{'form.problemmode'} eq &mt('EditXML') ||
1010: $env{'form.problemmode'} eq 'EditXML') {
1011: &editxmlmode($request,$file);
1012: } elsif ($env{'form.problemmode'} eq &mt('Calculate answers')) {
1013: &analyze($request,$file);
1014: } else {
1015: &renderpage($request,$file);
1016: }
1017: } else {
1018: # requested file doesn't exist in contruction space
1019: &newproblem($request);
1020: }
1021: } else {
1022: # just render the page normally outside of construction space
1023: &Apache::lonxml::debug("not construct");
1024: &renderpage($request,$file);
1025: }
1026: #my $td=&tv_interval($t0);
1027: #&Apache::lonxml::debug("Spent $td seconds processing");
1028: # &Apache::lonhomework::send_footer($request);
1029: # always turn off debug messages
1030: $Apache::lonxml::debug=0;
1031: return OK;
1032:
1033: }
1034:
1035: 1;
1036: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>