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