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