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

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

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