Annotation of loncom/homework/lonhomework.pm, revision 1.145

1.63      albertel    1: # The LearningOnline Network with CAPA
1.52      albertel    2: # The LON-CAPA Homework handler
1.63      albertel    3: #
1.145   ! albertel    4: # $Id: lonhomework.pm,v 1.144 2003/09/17 18:16:39 albertel Exp $
1.63      albertel    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: #
1.52      albertel   28: # Guy Albertelli
1.17      www        29: # 11/30 Gerd Kortemeyer
1.56      www        30: # 6/1,8/17,8/18 Gerd Kortemeyer
1.82      bowersj2   31: # 7/18 Jeremy Bowers
1.1       albertel   32: 
                     33: package Apache::lonhomework;
                     34: use strict;
1.73      albertel   35: use Apache::style();
                     36: use Apache::lonxml();
                     37: use Apache::lonnet();
                     38: use Apache::lonplot();
                     39: use Apache::inputtags();
                     40: use Apache::structuretags();
                     41: use Apache::randomlabel();
                     42: use Apache::response();
                     43: use Apache::hint();
                     44: use Apache::outputtags();
1.83      albertel   45: use Apache::caparesponse();
                     46: use Apache::radiobuttonresponse();
                     47: use Apache::optionresponse();
                     48: use Apache::imageresponse();
                     49: use Apache::essayresponse();
                     50: use Apache::externalresponse();
1.106     albertel   51: use Apache::rankresponse();
1.107     albertel   52: use Apache::matchresponse();
1.137     albertel   53: use Apache::chemresponse();
1.26      www        54: use Apache::Constants qw(:common);
1.73      albertel   55: use HTML::Entities();
1.83      albertel   56: use Apache::loncommon();
1.47      albertel   57: #use Time::HiRes qw( gettimeofday tv_interval );
1.43      albertel   58: 
1.69      harris41   59: BEGIN {
1.145   ! albertel   60:     &Apache::lonxml::register_insert();
1.43      albertel   61: }
                     62: 
1.5       albertel   63: sub get_target {
1.145   ! albertel   64:     if (($ENV{'request.state'} eq "published") ||
        !            65: 	($ENV{'request.state'} eq "uploaded")) {
        !            66: 	if ( defined($ENV{'form.grade_target'}  ) 
        !            67: 	     && ($ENV{'form.grade_target'} eq 'tex')) {
        !            68: 	    return ($ENV{'form.grade_target'});
        !            69: 	} elsif ( defined($ENV{'form.grade_target'}  ) 
        !            70: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
        !            71: 	    return ($ENV{'form.grade_target'});
        !            72: 	}
        !            73: 
1.62      albertel   74: 	if ( defined($ENV{'form.submitted'}) &&
1.145   ! albertel   75: 	     ( !defined($ENV{'form.resetdata'})) &&
        !            76: 	     ( !defined($ENV{'form.newrandomization'}))) {
        !            77: 	    return ('grade', 'web');
        !            78: 	} else {
        !            79: 	    return ('web');
        !            80: 	}
        !            81:     } elsif ($ENV{'request.state'} eq "construct") {
        !            82: 	if ( defined($ENV{'form.grade_target'}) ) {
        !            83: 	    return ($ENV{'form.grade_target'});
        !            84: 	}
        !            85: 	if ( defined($ENV{'form.preview'})) {
        !            86: 	    if ( defined($ENV{'form.submitted'})) {
        !            87: 		return ('grade', 'web');
        !            88: 	    } else {
        !            89: 		return ('web');
        !            90: 	    }
        !            91: 	} else {
        !            92: 	    if ( $ENV{'form.problemmode'} eq 'View' ||
        !            93: 		 $ENV{'form.problemmode'} eq 'Discard Edits and View') {
        !            94: 		if ( defined($ENV{'form.submitted'}) &&
        !            95: 		     (!defined($ENV{'form.resetdata'})) &&
        !            96: 		     (!defined($ENV{'form.newrandomization'}))) {
        !            97: 		    return ('grade', 'web','answer');
        !            98: 		} else {
        !            99: 		    return ('web','answer');
        !           100: 		}
        !           101: 	    } elsif ( $ENV{'form.problemmode'} eq 'Edit' ) {
        !           102: 		if ( $ENV{'form.submitted'} eq 'edit' ) {
        !           103: 		    if ( $ENV{'form.submit'} eq 'Submit Changes and View' ) {
        !           104: 			return ('modified','web','answer');
        !           105: 		    } else {
        !           106: 			return ('modified','edit');
        !           107: 		    }
        !           108: 		} else {
        !           109: 		    return ('edit');
        !           110: 		}
        !           111: 	    } else {
        !           112: 		return ('web');
        !           113: 	    }
        !           114: 	}
1.15      albertel  115:     }
1.145   ! albertel  116:     return ();
1.5       albertel  117: }
                    118: 
1.3       albertel  119: sub setup_vars {
1.145   ! albertel  120:     my ($target) = @_;
        !           121:     return ';'
1.11      albertel  122: #  return ';$external::target='.$target.';';
1.2       albertel  123: }
                    124: 
                    125: sub send_header {
1.145   ! albertel  126:     my ($request)= @_;
        !           127:     $request->print(&Apache::lontexconvert::header());
1.16      albertel  128: #  $request->print('<form name='.$ENV{'form.request.prefix'}.'lonhomework method="POST" action="'.$request->uri.'">');
1.2       albertel  129: }
                    130: 
1.36      albertel  131: sub createmenu {
1.145   ! albertel  132:     my ($which,$request)=@_;
        !           133:     if ($which eq 'grade') {
        !           134: 	$request->print('<script language="JavaScript"> 
1.91      albertel  135:           hwkmenu=window.open("/res/adm/pages/homeworkmenu.html","homeworkremote",
1.52      albertel  136:                  "height=350,width=150,menubar=no");
                    137:           </script>');
1.145   ! albertel  138:     }
1.36      albertel  139: }
                    140: 
1.2       albertel  141: sub send_footer {
1.145   ! albertel  142:     my ($request)= @_;
1.16      albertel  143: #  $request->print('</form>');
1.145   ! albertel  144:     $request->print(&Apache::lontexconvert::footer());
1.2       albertel  145: }
                    146: 
1.52      albertel  147: $Apache::lonxml::browse='';
1.53      www       148: 
1.92      bowersj2  149: # JB, 9/24/2002: Any changes in this function may require a change
                    150: # in lonnavmaps::resource::getDateStatus.
1.53      www       151: sub check_access {
1.145   ! albertel  152:     my ($id) = @_;
        !           153:     my $date ='';
        !           154:     my $status;
        !           155:     my $datemsg = '';
        !           156:     my $lastdate = '';
        !           157:     my $temp;
        !           158:     my $type;
        !           159:     my $passed;
        !           160: 
        !           161:     if ($ENV{'request.state'} eq "construct") {
        !           162: 	&Apache::lonxml::debug("in construction ignoring dates");
        !           163: 	$status='CAN_ANSWER';
        !           164: 	$datemsg='is in under construction';
        !           165: 	return ($status,$datemsg);
        !           166:     }
        !           167: 
        !           168:     &Apache::lonxml::debug("checking for part :$id:");
        !           169:     &Apache::lonxml::debug("time:".time);
        !           170:     foreach $temp ("opendate","duedate","answerdate") {
        !           171: 	$lastdate = $date;
        !           172: 	$date = &Apache::lonnet::EXT("resource.$id.$temp");
        !           173: 	my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
        !           174: 	if ($thistype =~ /^(con_lost|no_such_host)/ ||
        !           175: 	    $date     =~ /^(con_lost|no_such_host)/) {
        !           176: 	    $status='UNAVAILABLE';
        !           177: 	    $date="may open later.";
        !           178: 	    return($status,$date);
        !           179: 	}
        !           180: 	if ($thistype eq 'date_interval') {
        !           181: 	    if ($temp eq 'opendate') {
        !           182: 		$date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
        !           183: 	    }
        !           184: 	    if ($temp eq 'answerdate') {
        !           185: 		$date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
        !           186: 	    }
        !           187: 	}
        !           188: 	&Apache::lonxml::debug("found :$date: for :$temp:");
        !           189: 	if ($date eq '') {
        !           190: 	    $date = "an unknown date"; $passed = 0;
        !           191: 	} elsif ($date eq 'con_lost') {
        !           192: 	    $date = "an indeterminate date"; $passed = 0;
        !           193: 	} else {
        !           194: 	    if (time < $date) { $passed = 0; } else { $passed = 1; }
        !           195: 	    $date = localtime $date;
        !           196: 	}
        !           197: 	if (!$passed) { $type=$temp; last; }
1.51      harris41  198:     }
1.145   ! albertel  199:     &Apache::lonxml::debug("have :$type:$passed:");
        !           200:     if ($passed) {
        !           201: 	$status='SHOW_ANSWER';
        !           202: 	$datemsg=$date;
        !           203:     } elsif ($type eq 'opendate') {
        !           204: 	$status='CLOSED';
        !           205: 	$datemsg = "will open on $date";
        !           206:     } elsif ($type eq 'duedate') {
        !           207: 	$status='CAN_ANSWER';
        !           208: 	$datemsg = "is due at $date";
        !           209:     } elsif ($type eq 'answerdate') {
        !           210: 	$status='CLOSED';
        !           211: 	$datemsg = "was due on $lastdate, and answers will be available on $date";
        !           212:     }
        !           213:     if ($status eq 'CAN_ANSWER') {
        !           214: 	#check #tries, and if correct.
        !           215: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
        !           216: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
        !           217: 	if ( $tries eq '' ) { $tries = '0'; }
        !           218: 	if ( $maxtries eq '' ) { $maxtries = '2'; } 
        !           219: 	if ($tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
        !           220: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
        !           221: 	if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
        !           222: 	    &&
        !           223: 	    lc($Apache::lonhomework::problemstatus) ne 'no')
        !           224: 	   ||
        !           225: 	   $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
        !           226: 	    $status = 'CANNOT_ANSWER';
        !           227: 	}
1.121     albertel  228:     }
1.54      www       229: 
1.133     albertel  230:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
                    231:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
                    232:   #    return ('UNCHECKEDOUT','needs to be checked out');
                    233:   #}
1.54      www       234: 
                    235: 
1.145   ! albertel  236:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
        !           237:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
        !           238: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
        !           239: 	$status='CAN_ANSWER';
        !           240: 	$datemsg='is closed but you are allowed to view it';
        !           241:     }
1.106     albertel  242: 
1.145   ! albertel  243:     return ($status,$datemsg);
1.20      albertel  244: }
                    245: 
1.41      albertel  246: sub showhash {
1.145   ! albertel  247:     my (%hash) = @_;
        !           248:     &showhashsubset(\%hash,'.');
        !           249:     return '';
1.79      albertel  250: }
                    251: 
1.106     albertel  252: sub showarray {
                    253:     my ($array)=@_;
                    254:     my $string="(";
                    255:     foreach my $elm (@{ $array }) {
                    256: 	if (ref($elm)) {
                    257: 	    if ($elm =~ /ARRAY/ ) {
                    258: 		$string.=&showarray($elm);
                    259: 	    }
                    260: 	} else {
                    261: 	    $string.="$elm,"
                    262: 	}
                    263:     }
                    264:     chop($string);
                    265:     $string.=")";
                    266:     return $string;
                    267: }
                    268: 
1.79      albertel  269: sub showhashsubset {
1.145   ! albertel  270:     my ($hash,$keyre) = @_;
        !           271:     my $resultkey;
        !           272:     foreach $resultkey (sort keys %$hash) {
        !           273: 	if ($resultkey =~ /$keyre/) {
        !           274: 	    if (ref($$hash{$resultkey})) {
        !           275: 		if ($$hash{$resultkey} =~ /ARRAY/ ) {
        !           276: 		    &Apache::lonxml::debug("$resultkey ---- ".
        !           277: 					   &showarray($$hash{$resultkey}));
        !           278: 		} elsif ($$hash{$resultkey} =~ /HASH/ ) {
        !           279: 		    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
        !           280: 		    &showhashsubset($$hash{$resultkey},'.');
        !           281: 		} else {
        !           282: 		    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
        !           283: 		}
        !           284: 	    } else {
        !           285: 		&Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
        !           286: 	    }
        !           287: 	}
        !           288:     }
        !           289:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
        !           290:     return '';
1.41      albertel  291: }
                    292: 
                    293: sub setuppermissions {
1.145   ! albertel  294:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
        !           295:     my $viewgrades = &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
        !           296:     if (! $viewgrades && 
        !           297: 	exists($ENV{'request.course.sec'}) && 
        !           298: 	$ENV{'request.course.sec'} !~ /^\s*$/) {
        !           299: 	$viewgrades = &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'}.
1.127     matthew   300:                                                '/'.$ENV{'request.course.sec'});
1.145   ! albertel  301:     }
        !           302:     $Apache::lonhomework::viewgrades = $viewgrades;
        !           303:     return ''
1.41      albertel  304: }
                    305: 
                    306: sub setupheader {
1.120     albertel  307:     my $request=$_[0];
                    308:     if ($ENV{'browser.mathml'}) {
                    309: 	$request->content_type('text/xml');
                    310:     } else {
                    311: 	$request->content_type('text/html');
                    312:     }
                    313:     $request->content_encoding('UTF-8');
                    314:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
                    315: 	&Apache::loncommon::no_cache($request);
                    316:     }
                    317:     $request->send_http_header;
                    318:     return OK if $request->header_only;
                    319:     return ''
1.41      albertel  320: }
1.35      albertel  321: 
1.47      albertel  322: sub handle_save_or_undo {
1.145   ! albertel  323:     my ($request,$problem,$result) = @_;
        !           324:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
        !           325:     my $filebak =$file.".bak";
        !           326:     my $filetmp =$file.".tmp";
        !           327:     my $error=0;
1.52      albertel  328: 
1.145   ! albertel  329:     if ($ENV{'form.Undo'} eq 'undo') {
        !           330: 	my $error=0;
        !           331: 	if (!copy($file,$filetmp)) { $error=1; }
        !           332: 	if ((!$error) && (!copy($filebak,$file))) { $error=1; }
        !           333: 	if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
        !           334: 	if (!$error) {
        !           335: 	    $request->print("<p><b>Undid changes, Switched $filebak and $file</b></p>");
        !           336: 	} else {
        !           337: 	    $request->print("<p><font color=\"red\" size=\"+1\"><b>Unable to undo, unable to switch $filebak and $file</b></font></p>");
        !           338: 	    $error=1;
        !           339: 	}
1.52      albertel  340:     } else {
1.145   ! albertel  341: 	my $fs=Apache::File->new(">$filebak");
        !           342: 	if (defined($fs)) {
        !           343: 	    print $fs $$problem;
        !           344: 	    $request->print("<b>Making Backup to $filebak</b><br />");
        !           345: 	} else {
        !           346: 	    $request->print("<font color=\"red\" size=\"+1\"><b>Unable to make backup $filebak</b></font>");
        !           347: 	    $error=2;
        !           348: 	}
        !           349: 	my $fh=Apache::File->new(">$file");
        !           350: 	if (defined($fh)) {
        !           351: 	    print $fh $$result;
        !           352: 	    $request->print("<b>Saving Modifications to $file</b><br />");
        !           353: 	} else {
        !           354: 	    $request->print("<font color=\"red\" size=\"+1\"><b>Unable to write to $file</b></font>");
        !           355: 	    $error|=4;
        !           356: 	}
1.52      albertel  357:     }
1.145   ! albertel  358:     return $error;
1.64      albertel  359: }
                    360: 
1.101     albertel  361: sub analyze_header {
                    362:     my ($request) = @_;
1.109     albertel  363:     my $result.='<html>
                    364:             <head><title>Analyzing a problem</title></head>
                    365:             <body bgcolor="#FFFFFF">
1.101     albertel  366:             <form name="lonhomework" method="POST" action="'.
1.145   ! albertel  367: 	    $ENV{'request.uri'}.'">
1.101     albertel  368:             <input type="submit" name="problemmode" value="EditXML" />
                    369:             <input type="submit" name="problemmode" value="Edit" />
                    370:             <hr />
                    371:             <input type="submit" name="submit" value="View" />
                    372:             <hr />
                    373:             List of possible answers:
                    374:             </form>';
                    375:     $request->print($result);
                    376:     $request->rflush();
                    377: }
                    378: 
1.109     albertel  379: sub analyze_footer {
                    380:     my ($request) = @_;
                    381:     my $result='</body></html>';
                    382:     $request->print($result);
                    383:     $request->rflush();
                    384: }
                    385: 
1.74      albertel  386: sub analyze {
1.101     albertel  387:     my ($request,$file) = @_;
                    388:     &Apache::lonxml::debug("Analyze");
                    389:     my $result;
                    390:     my %overall;
                    391:     my %allparts;
                    392:     my $rndseed=$ENV{'form.rndseed'};
                    393:     &analyze_header($request);
1.114     albertel  394:     my %prog_state=
                    395: 	&Apache::lonhtmlcommon::Create_PrgWin($request,'Analyze Progress',
                    396: 					      'Getting Problem Variants',
                    397: 					      $ENV{'form.numtoanalyze'});
1.102     albertel  398:     for(my $i=1;$i<$ENV{'form.numtoanalyze'}+1;$i++) {
1.114     albertel  399: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
                    400: 						 'last problem');
1.101     albertel  401: 	my $subresult=&Apache::lonnet::ssi($request->uri,
                    402: 					   ('grade_target' => 'analyze'),
1.130     albertel  403: 					   ('rndseed' => $i+$rndseed));
1.101     albertel  404: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    405: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.114     albertel  406: 	my @parts;
                    407: 	if (defined(@{ $analyze{'parts'} })) {
                    408: 	    @parts=@{ $analyze{'parts'} };
                    409: 	}
1.101     albertel  410: 	foreach my $part (@parts) {
                    411: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
1.109     albertel  412: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
                    413: 		$analyze{$part.'.type'} eq 'stringresponse'	||
                    414: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
1.101     albertel  415: 		push( @{ $overall{$part.'.answer'} },
                    416: 		      [@{ $analyze{$part.'.answer'} }]);
                    417: 	    }
                    418: 	}
                    419:     }
1.114     albertel  420:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
                    421: 					  'Analyzing Results');
1.134     albertel  422:     foreach my $part (sort(keys(%allparts))) {
1.109     albertel  423: 	if (defined(@{ $overall{$part.'.answer'} })) {
1.132     albertel  424: 	    my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
                    425: 	    $request->print('<table><tr><td colspan="'.($num_cols+1).'">Part '.$part.'</td></tr>');
1.130     albertel  426: 	    my %frequency;
1.109     albertel  427: 	    foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
1.132     albertel  428: 		$frequency{join("\0",@{ $answer })}++;
1.130     albertel  429: 	    }
1.132     albertel  430: 	    $request->print('<tr><td colspan="'.($num_cols).'">Answer</td><td>Frequency</td></tr>');
                    431: 	    foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
                    432: 		$request->print('<tr><td align="right">'.
                    433: 				join('</td><td align="right">',split("\0",$answer)).
1.130     albertel  434: 				'</td><td>('.$frequency{$answer}.
                    435: 				')</td></tr>');
1.109     albertel  436: 	    }
                    437: 	    $request->print('</table>');
                    438: 	} else {
                    439: 	    $request->print('<p>Part '.$part.
1.130     albertel  440: 			    ' is not analyzable at this time</p>');
1.101     albertel  441: 	}
                    442:     }
1.130     albertel  443:     if (scalar(keys(%allparts)) == 0 ) {
                    444: 	$request->print('<p>Found no analyzable parts in this problem,
                    445:                          currently only Numerical, Formula and String response
                    446:                          styles are supported.</p>');
                    447:     }
1.114     albertel  448:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1.109     albertel  449:     &analyze_footer($request);
1.101     albertel  450:     &Apache::lonhomework::showhash(%overall);
                    451:     return $result;
1.74      albertel  452: }
                    453: 
1.64      albertel  454: sub editxmlmode {
1.145   ! albertel  455:     my ($request,$file) = @_;
        !           456:     my $result;
        !           457:     my $problem=&Apache::lonnet::getfile($file);
        !           458:     if ($problem eq -1) {
        !           459: 	&Apache::lonxml::error("<b> Unable to find <i>$file</i></b>");
        !           460: 	$problem='';
        !           461:     }
        !           462:     if (defined($ENV{'form.editxmltext'}) || defined($ENV{'form.Undo'})) {
        !           463: 	my $error=&handle_save_or_undo($request,\$problem,
        !           464: 				       \$ENV{'form.editxmltext'});
        !           465: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
        !           466:     }
1.80      albertel  467:     &Apache::lonhomework::showhashsubset(\%ENV,'^form');
1.145   ! albertel  468:     if ( $ENV{'form.submit'} eq 'Submit Changes and View' ) {
        !           469: 	&Apache::lonhomework::showhashsubset(\%ENV,'^form');
        !           470: 	$ENV{'form.problemmode'}='View';
        !           471: 	&renderpage($request,$file);
        !           472:     } else {
        !           473: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
        !           474: 	my $xml_help = Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
        !           475: 							      "Problem Editing Help");
        !           476: 	if ($cols > 80) { $cols = 80; }
        !           477: 	if ($cols < 70) { $cols = 70; }
        !           478: 	if ($rows < 20) { $rows = 20; }
        !           479: 	$result.='<html><body bgcolor="#FFFFFF">
1.64      albertel  480:             <form name="lonhomework" method="POST" action="'.
1.145   ! albertel  481: 	    $ENV{'request.uri'}.'">
1.64      albertel  482:             <input type="hidden" name="problemmode" value="EditXML" />
1.80      albertel  483:             <input type="submit" name="problemmode" value="Discard Edits and View" />
1.64      albertel  484:             <input type="submit" name="problemmode" value="Edit" />
                    485:             <hr />
                    486:             <input type="submit" name="submit" value="Submit Changes" />
1.80      albertel  487:             <input type="submit" name="submit" value="Submit Changes and View" />
1.64      albertel  488:             <input type="submit" name="Undo" value="undo" />
                    489:             <hr />
1.110     albertel  490:             ' . $xml_help . '
1.64      albertel  491:             <textarea rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
1.145   ! albertel  492: 	    &HTML::Entities::encode($problem).'</textarea>
1.64      albertel  493:             </form></body></html>';
1.145   ! albertel  494: 	$request->print($result);
        !           495:     }
        !           496:     return '';
1.47      albertel  497: }
                    498: 
1.41      albertel  499: sub renderpage {
1.145   ! albertel  500:     my ($request,$file) = @_;
1.52      albertel  501: 
1.145   ! albertel  502:     my (@targets) = &get_target();
        !           503:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
        !           504:     foreach my $target (@targets) {
        !           505: 	#my $t0 = [&gettimeofday()];
        !           506: 	my $problem=&Apache::lonnet::getfile($file);
        !           507: 	if ($problem eq -1) {
        !           508: 	    &Apache::lonxml::error("<b> Unable to find <i>$file</i></b>");
        !           509: 	    $problem='';
        !           510: 	}
1.52      albertel  511: 
1.145   ! albertel  512: 	my %mystyle;
        !           513: 	my $result = '';
        !           514: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
        !           515: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
        !           516: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%ENV,'^form');}
        !           517: 
        !           518: 	&Apache::lonxml::debug("Should be parsing now");
        !           519: 	$result = &Apache::lonxml::xmlparse($request, $target, $problem,
        !           520: 					    &setup_vars($target),%mystyle);
        !           521: 	undef($Apache::lonhomework::parsing_a_problem);
        !           522: 	#$request->print("Result follows:");
        !           523: 	if ($target eq 'modified') {
        !           524: 	    &handle_save_or_undo($request,\$problem,\$result);
        !           525: 	} else {
        !           526: 	    if ($target eq 'analyze') {
        !           527: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
        !           528: 		undef(%Apache::lonhomework::analyze);
        !           529: 	    }
        !           530: 	    #my $td=&tv_interval($t0);
        !           531: 	    #if ( $Apache::lonxml::debug) {
        !           532: 	    #$result =~ s:</body>::;
        !           533: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
        !           534: 	    #}
        !           535: 	    $request->print($result);
        !           536: 	    $request->rflush();
        !           537: 	}
        !           538: 	#$request->print(":Result ends");
        !           539: 	#my $td=&tv_interval($t0);
1.52      albertel  540:     }
1.41      albertel  541: }
                    542: 
1.42      albertel  543: # with no arg it returns a HTML <option> list of the template titles
                    544: # with one arg it returns the filename associated with the arg passed
                    545: sub get_template_list {
1.145   ! albertel  546:     my ($namewanted,$extension) = @_;
        !           547:     my $result;
        !           548:     my @allnames;
        !           549:     &Apache::lonxml::debug("Looking for :$extension:");
        !           550:     foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
        !           551: 	my $name=&Apache::lonnet::metadata($file,'title');
        !           552: 	if ($namewanted && ($name eq $namewanted)) {
        !           553: 	    $result=$file;
        !           554: 	    last;
        !           555: 	} else {
        !           556: 	    if ($name) { push (@allnames, $name); }
        !           557: 	}
        !           558:     }
        !           559:     if (@allnames && !$result) {
        !           560: 	$result="<option>Select a $extension template</option>\n<option>".
        !           561: 	    join('</option><option>',sort(@allnames)).'</option>';
1.42      albertel  562:     }
1.145   ! albertel  563:     return $result;
1.42      albertel  564: }
                    565: 
                    566: sub newproblem {
1.65      matthew   567:     my ($request) = @_;
                    568:     my $extension=$request->uri;
                    569:     $extension=~s:^.*\.([\w]+)$:$1:;
                    570:     &Apache::lonxml::debug("Looking for :$extension:");
1.131     albertel  571:     my $templatelist=&get_template_list('',$extension);
1.85      albertel  572:     if ($ENV{'form.template'} &&
1.128     albertel  573: 	$ENV{'form.template'} ne "Select a $extension template") {
1.65      matthew   574: 	use File::Copy;
                    575: 	my $file = &get_template_list($ENV{'form.template'},$extension);
                    576: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
                    577: 	copy($file,$dest);
                    578: 	&renderpage($request,$dest);
1.131     albertel  579:     } elsif($ENV{'form.newfile'} && !$templatelist) {
                    580: 	# I don't like hard-coded filenames but for now, this will work.
                    581: 	use File::Copy;
                    582: 	my $templatefilename =
                    583: 	    $request->dir_config('lonIncludes').'/templates/blank.problem';
                    584: 	&Apache::lonxml::debug("$templatefilename");
                    585: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
                    586: 	copy($templatefilename,$dest);
                    587: 	&renderpage($request,$dest);
1.85      albertel  588:     } else {
1.65      matthew   589: 	my $url=$request->uri;
                    590: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.128     albertel  591: 	my $errormsg;
                    592: 	if ($ENV{'form.newfile'}) {
                    593: 	    $errormsg='<p><font color="red">You did not select a template.</font></p>'."\n";
                    594: 	}
1.85      albertel  595: 	my $instructions;
1.105     www       596: 	if ($templatelist) { $instructions=", select a template from the pull-down menu below.<br />Then";}
1.65      matthew   597: 	$request->print(<<ENDNEWPROBLEM);
1.42      albertel  598: <body bgcolor="#FFFFFF">
1.105     www       599: <h1>Creating a new $extension resource</h1>
1.128     albertel  600: $errormsg
1.105     www       601: The requested file <tt>$url</tt> currently does not exist.
                    602: <p>
1.128     albertel  603: <b>To create a new $extension$instructions click on the "Create $extension" button.</b>
1.105     www       604: </p>
                    605: <p><form action="$url" method="POST">
1.42      albertel  606: ENDNEWPROBLEM
1.85      albertel  607: 	if (defined($templatelist)) {
                    608: 	    $request->print("<select name=\"template\">$templatelist</select>");
                    609: 	}
                    610: 	$request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"Create $extension\" />");
1.105     www       611: 	$request->print("</form></p></body>");
1.65      matthew   612:     }
                    613:     return '';
1.42      albertel  614: }
                    615: 
                    616: sub view_or_edit_menu {
1.145   ! albertel  617:     my ($request) = @_;
        !           618:     my $url=$request->uri;
        !           619:     $request->print(<<EDITMENU);
1.42      albertel  620: <body bgcolor="#FFFFFF">
                    621: <form action="$url" method="POST">
                    622: Would you like to <input type="submit" name="problemmode" value="View"> or
                    623: <input type="submit" name="problemmode" value="Edit"> the problem.
                    624: </form>
                    625: </body>
                    626: EDITMENU
                    627: }
                    628: 
1.41      albertel  629: sub handler {
1.145   ! albertel  630:     #my $t0 = [&gettimeofday()];
        !           631:     my $request=$_[0];
        !           632:     
        !           633:     $Apache::lonxml::debug=$ENV{'user.debug'};
1.41      albertel  634: 
1.145   ! albertel  635:     if (&setupheader($request)) { return OK; }
        !           636:     $ENV{'request.uri'}=$request->uri;
1.41      albertel  637: 
1.145   ! albertel  638:     #setup permissions
        !           639:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
        !           640:     $Apache::lonhomework::viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
        !           641:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:");
        !           642:     # some times multiple problemmodes are submitted, need to select
        !           643:     # the last one
        !           644:     &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
        !           645:     if ( defined($ENV{'form.problemmode'}) &&
        !           646: 	 ref($ENV{'form.problemmode'}) ) {
        !           647: 	&Apache::lonxml::debug("Problem Mode ".join(",",@$ENV{'form.problemmode'}));
        !           648: 	my $mode=$ENV{'form.problemmode'}->[-1];
        !           649: 	undef $ENV{'form.problemmode'};
        !           650: 	$ENV{'form.problemmode'}=$mode;
        !           651:     }
        !           652:     &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
        !           653:     my $file=&Apache::lonnet::filelocation("",$request->uri);
        !           654: 
        !           655:     #check if we know where we are
        !           656:     if ($ENV{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
        !           657: 	# if we are browsing we might not be able to know where we are
        !           658: 	if ($Apache::lonhomework::browse ne 'F') {
        !           659: 	    #should know where we are, so ask
        !           660: 	    if ( &Apache::lonnet::mod_perl_version() == 2 ) {
        !           661: 		&Apache::lonnet::cleanenv();
        !           662: 	    }
        !           663: 	    $request->internal_redirect('/adm/ambiguous'); return;
        !           664: 	}
        !           665:     }
1.41      albertel  666: 
1.145   ! albertel  667:     my ($symb) = &Apache::lonxml::whichuser();
        !           668:     &Apache::lonxml::debug('symb is '.$symb);
        !           669:     if ($ENV{'request.state'} eq "construct" || $symb eq '') {
        !           670: 	if ($ENV{'form.resetdata'} eq 'Reset Submissions' ||
        !           671: 	    $ENV{'form.resetdata'} eq 'New Problem Variation' ||
        !           672: 	    $ENV{'form.newrandomization'} eq 'New Randomization') {
        !           673: 	    my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
        !           674: 	    &Apache::lonnet::tmpreset($symb,'',$domain,$name);
        !           675: 	    &Apache::lonxml::debug("Attempt reset");
        !           676: 	}
        !           677:     }
        !           678:     if ($ENV{'request.state'} eq "construct") {
        !           679: 	if ( -e $file ) {
        !           680: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
        !           681: 						    ['problemmode']);
        !           682: 	    if (!(defined $ENV{'form.problemmode'})) {
        !           683: 		#first visit to problem in construction space
        !           684: 		#&view_or_edit_menu($request);
        !           685: 		$ENV{'form.problemmode'}='View';
        !           686: 		&renderpage($request,$file);
        !           687: 	    } elsif ($ENV{'form.problemmode'} eq 'EditXML') {
        !           688: 		&editxmlmode($request,$file);
        !           689: 	    } elsif ($ENV{'form.problemmode'} eq 'Calculate answers') {
        !           690: 		&analyze($request,$file);
        !           691: 	    } else {
        !           692: 		&renderpage($request,$file);
        !           693: 	    }
        !           694: 	} else {
        !           695: 	    # requested file doesn't exist in contruction space
        !           696: 	    &newproblem($request);
        !           697: 	}
        !           698:     } else {
        !           699: 	# just render the page normally outside of construction space
        !           700: 	&Apache::lonxml::debug("not construct");
1.52      albertel  701: 	&renderpage($request,$file);
1.41      albertel  702:     }
1.145   ! albertel  703:     #my $td=&tv_interval($t0);
        !           704:     #&Apache::lonxml::debug("Spent $td seconds processing");
        !           705:     # &Apache::lonhomework::send_footer($request);
        !           706:     # always turn off debug messages
        !           707:     $Apache::lonxml::debug=0;
        !           708:     return OK;
1.52      albertel  709: 
1.1       albertel  710: }
                    711: 
                    712: 1;
                    713: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>