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

1.63      albertel    1: # The LearningOnline Network with CAPA
1.52      albertel    2: # The LON-CAPA Homework handler
1.63      albertel    3: #
1.146   ! albertel    4: # $Id: lonhomework.pm,v 1.145 2003/09/18 19:59:15 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 {
                     93: 	    if ( $ENV{'form.problemmode'} eq 'View' ||
                     94: 		 $ENV{'form.problemmode'} eq 'Discard Edits and View') {
                     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: 		}
                    102: 	    } elsif ( $ENV{'form.problemmode'} eq 'Edit' ) {
                    103: 		if ( $ENV{'form.submitted'} eq 'edit' ) {
                    104: 		    if ( $ENV{'form.submit'} eq 'Submit Changes and View' ) {
                    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'}) {
                    310: 	$request->content_type('text/xml');
                    311:     } else {
                    312: 	$request->content_type('text/html');
                    313:     }
                    314:     $request->content_encoding('UTF-8');
                    315:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
                    316: 	&Apache::loncommon::no_cache($request);
                    317:     }
                    318:     $request->send_http_header;
                    319:     return OK if $request->header_only;
                    320:     return ''
1.41      albertel  321: }
1.35      albertel  322: 
1.47      albertel  323: sub handle_save_or_undo {
1.145     albertel  324:     my ($request,$problem,$result) = @_;
                    325:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
                    326:     my $filebak =$file.".bak";
                    327:     my $filetmp =$file.".tmp";
                    328:     my $error=0;
1.52      albertel  329: 
1.145     albertel  330:     if ($ENV{'form.Undo'} eq 'undo') {
                    331: 	my $error=0;
                    332: 	if (!copy($file,$filetmp)) { $error=1; }
                    333: 	if ((!$error) && (!copy($filebak,$file))) { $error=1; }
                    334: 	if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
                    335: 	if (!$error) {
1.146   ! albertel  336: 	    $request->print("<p><b>".&mt("Undid changes, Switched")." $filebak ".&mt("and")." $file</b></p>");
1.145     albertel  337: 	} else {
1.146   ! albertel  338: 	    $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  339: 	    $error=1;
                    340: 	}
1.52      albertel  341:     } else {
1.145     albertel  342: 	my $fs=Apache::File->new(">$filebak");
                    343: 	if (defined($fs)) {
                    344: 	    print $fs $$problem;
1.146   ! albertel  345: 	    $request->print("<b>".&mt("Making Backup to").
        !           346: 			    " $filebak</b><br />");
1.145     albertel  347: 	} else {
1.146   ! albertel  348: 	    $request->print("<font color=\"red\" size=\"+1\"><b>".&mt("Unable to make backup")." $filebak</b></font>");
1.145     albertel  349: 	    $error=2;
                    350: 	}
                    351: 	my $fh=Apache::File->new(">$file");
                    352: 	if (defined($fh)) {
                    353: 	    print $fh $$result;
1.146   ! albertel  354: 	    $request->print("<b>".&mt("Saving Modifications to").
        !           355: 			    " $file</b><br />");
1.145     albertel  356: 	} else {
1.146   ! albertel  357: 	    $request->print("<font color=\"red\" size=\"+1\"><b>".
        !           358: 			    &mt("Unable to write to")." $file</b></font>");
1.145     albertel  359: 	    $error|=4;
                    360: 	}
1.52      albertel  361:     }
1.145     albertel  362:     return $error;
1.64      albertel  363: }
                    364: 
1.101     albertel  365: sub analyze_header {
                    366:     my ($request) = @_;
1.109     albertel  367:     my $result.='<html>
1.146   ! albertel  368:             <head><title>'.&mt("Analyzing a problem").'</title></head>
1.109     albertel  369:             <body bgcolor="#FFFFFF">
1.101     albertel  370:             <form name="lonhomework" method="POST" action="'.
1.145     albertel  371: 	    $ENV{'request.uri'}.'">
1.146   ! albertel  372:             <input type="submit" name="problemmode" value="'.&mt("EditXML").'" />
        !           373:             <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
1.101     albertel  374:             <hr />
1.146   ! albertel  375:             <input type="submit" name="submit" value="'.&mt("View").'" />
1.101     albertel  376:             <hr />
1.146   ! albertel  377:             '.&mt('List of possible answers').':
1.101     albertel  378:             </form>';
                    379:     $request->print($result);
                    380:     $request->rflush();
                    381: }
                    382: 
1.109     albertel  383: sub analyze_footer {
                    384:     my ($request) = @_;
                    385:     my $result='</body></html>';
                    386:     $request->print($result);
                    387:     $request->rflush();
                    388: }
                    389: 
1.74      albertel  390: sub analyze {
1.101     albertel  391:     my ($request,$file) = @_;
                    392:     &Apache::lonxml::debug("Analyze");
                    393:     my $result;
                    394:     my %overall;
                    395:     my %allparts;
                    396:     my $rndseed=$ENV{'form.rndseed'};
                    397:     &analyze_header($request);
1.114     albertel  398:     my %prog_state=
1.146   ! albertel  399: 	&Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
        !           400: 					      &mt('Getting Problem Variants'),
1.114     albertel  401: 					      $ENV{'form.numtoanalyze'});
1.102     albertel  402:     for(my $i=1;$i<$ENV{'form.numtoanalyze'}+1;$i++) {
1.114     albertel  403: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
1.146   ! albertel  404: 						 &mt('last problem'));
1.101     albertel  405: 	my $subresult=&Apache::lonnet::ssi($request->uri,
                    406: 					   ('grade_target' => 'analyze'),
1.130     albertel  407: 					   ('rndseed' => $i+$rndseed));
1.101     albertel  408: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    409: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.114     albertel  410: 	my @parts;
                    411: 	if (defined(@{ $analyze{'parts'} })) {
                    412: 	    @parts=@{ $analyze{'parts'} };
                    413: 	}
1.101     albertel  414: 	foreach my $part (@parts) {
                    415: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
1.109     albertel  416: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
                    417: 		$analyze{$part.'.type'} eq 'stringresponse'	||
                    418: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
1.101     albertel  419: 		push( @{ $overall{$part.'.answer'} },
                    420: 		      [@{ $analyze{$part.'.answer'} }]);
                    421: 	    }
                    422: 	}
                    423:     }
1.114     albertel  424:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
1.146   ! albertel  425: 					  &mt('Analyzing Results'));
1.134     albertel  426:     foreach my $part (sort(keys(%allparts))) {
1.109     albertel  427: 	if (defined(@{ $overall{$part.'.answer'} })) {
1.132     albertel  428: 	    my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
1.146   ! albertel  429: 	    $request->print('<table><tr><td colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part.'</td></tr>');
1.130     albertel  430: 	    my %frequency;
1.109     albertel  431: 	    foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
1.132     albertel  432: 		$frequency{join("\0",@{ $answer })}++;
1.130     albertel  433: 	    }
1.146   ! albertel  434: 	    $request->print('<tr><td colspan="'.($num_cols).'">'.&mt('Answer').'</td><td>'.&mt('Frequency').'</td></tr>');
1.132     albertel  435: 	    foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
                    436: 		$request->print('<tr><td align="right">'.
                    437: 				join('</td><td align="right">',split("\0",$answer)).
1.130     albertel  438: 				'</td><td>('.$frequency{$answer}.
                    439: 				')</td></tr>');
1.109     albertel  440: 	    }
                    441: 	    $request->print('</table>');
                    442: 	} else {
1.146   ! albertel  443: 	    $request->print('<p>'.&mt('Part').' '.$part.' '.
        !           444: 			    &mt('is not analyzable at this time').'</p>');
1.101     albertel  445: 	}
                    446:     }
1.130     albertel  447:     if (scalar(keys(%allparts)) == 0 ) {
1.146   ! albertel  448: 	$request->print('<p>'.&mt('Found no analyzable parts in this problem,
1.130     albertel  449:                          currently only Numerical, Formula and String response
1.146   ! albertel  450:                          styles are supported.').'</p>');
1.130     albertel  451:     }
1.114     albertel  452:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1.109     albertel  453:     &analyze_footer($request);
1.101     albertel  454:     &Apache::lonhomework::showhash(%overall);
                    455:     return $result;
1.74      albertel  456: }
                    457: 
1.64      albertel  458: sub editxmlmode {
1.145     albertel  459:     my ($request,$file) = @_;
                    460:     my $result;
                    461:     my $problem=&Apache::lonnet::getfile($file);
                    462:     if ($problem eq -1) {
1.146   ! albertel  463: 	&Apache::lonxml::error("<b> ".&mt('Unable to find').
        !           464: 			       " <i>$file</i></b>");
1.145     albertel  465: 	$problem='';
                    466:     }
                    467:     if (defined($ENV{'form.editxmltext'}) || defined($ENV{'form.Undo'})) {
                    468: 	my $error=&handle_save_or_undo($request,\$problem,
                    469: 				       \$ENV{'form.editxmltext'});
                    470: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
                    471:     }
1.80      albertel  472:     &Apache::lonhomework::showhashsubset(\%ENV,'^form');
1.145     albertel  473:     if ( $ENV{'form.submit'} eq 'Submit Changes and View' ) {
                    474: 	&Apache::lonhomework::showhashsubset(\%ENV,'^form');
                    475: 	$ENV{'form.problemmode'}='View';
                    476: 	&renderpage($request,$file);
                    477:     } else {
                    478: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
                    479: 	my $xml_help = Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
                    480: 							      "Problem Editing Help");
                    481: 	if ($cols > 80) { $cols = 80; }
                    482: 	if ($cols < 70) { $cols = 70; }
                    483: 	if ($rows < 20) { $rows = 20; }
                    484: 	$result.='<html><body bgcolor="#FFFFFF">
1.64      albertel  485:             <form name="lonhomework" method="POST" action="'.
1.145     albertel  486: 	    $ENV{'request.uri'}.'">
1.146   ! albertel  487:             <input type="hidden" name="problemmode" value="'.&mt('EditXML').'" />
        !           488:             <input type="submit" name="problemmode" value="'.&mt('Discard Edits and View').'" />
        !           489:             <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
1.64      albertel  490:             <hr />
1.146   ! albertel  491:             <input type="submit" name="submit" value="'.&mt('Submit Changes').'" />
        !           492:             <input type="submit" name="submit" value="'.&mt('Submit Changes and View').'" />
        !           493:             <input type="submit" name="Undo" value="'.&mt('undo').'" />
1.64      albertel  494:             <hr />
1.110     albertel  495:             ' . $xml_help . '
1.64      albertel  496:             <textarea rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
1.145     albertel  497: 	    &HTML::Entities::encode($problem).'</textarea>
1.64      albertel  498:             </form></body></html>';
1.145     albertel  499: 	$request->print($result);
                    500:     }
                    501:     return '';
1.47      albertel  502: }
                    503: 
1.41      albertel  504: sub renderpage {
1.145     albertel  505:     my ($request,$file) = @_;
1.52      albertel  506: 
1.145     albertel  507:     my (@targets) = &get_target();
                    508:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
                    509:     foreach my $target (@targets) {
                    510: 	#my $t0 = [&gettimeofday()];
                    511: 	my $problem=&Apache::lonnet::getfile($file);
                    512: 	if ($problem eq -1) {
1.146   ! albertel  513: 	    &Apache::lonxml::error("<b> ".&mt('Unable to find')." <i>$file</i></b>");
1.145     albertel  514: 	    $problem='';
                    515: 	}
1.52      albertel  516: 
1.145     albertel  517: 	my %mystyle;
                    518: 	my $result = '';
                    519: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
                    520: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
                    521: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%ENV,'^form');}
                    522: 
                    523: 	&Apache::lonxml::debug("Should be parsing now");
                    524: 	$result = &Apache::lonxml::xmlparse($request, $target, $problem,
                    525: 					    &setup_vars($target),%mystyle);
                    526: 	undef($Apache::lonhomework::parsing_a_problem);
                    527: 	#$request->print("Result follows:");
                    528: 	if ($target eq 'modified') {
                    529: 	    &handle_save_or_undo($request,\$problem,\$result);
                    530: 	} else {
                    531: 	    if ($target eq 'analyze') {
                    532: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
                    533: 		undef(%Apache::lonhomework::analyze);
                    534: 	    }
                    535: 	    #my $td=&tv_interval($t0);
                    536: 	    #if ( $Apache::lonxml::debug) {
                    537: 	    #$result =~ s:</body>::;
                    538: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
                    539: 	    #}
                    540: 	    $request->print($result);
                    541: 	    $request->rflush();
                    542: 	}
                    543: 	#$request->print(":Result ends");
                    544: 	#my $td=&tv_interval($t0);
1.52      albertel  545:     }
1.41      albertel  546: }
                    547: 
1.42      albertel  548: # with no arg it returns a HTML <option> list of the template titles
                    549: # with one arg it returns the filename associated with the arg passed
                    550: sub get_template_list {
1.145     albertel  551:     my ($namewanted,$extension) = @_;
                    552:     my $result;
                    553:     my @allnames;
                    554:     &Apache::lonxml::debug("Looking for :$extension:");
                    555:     foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
                    556: 	my $name=&Apache::lonnet::metadata($file,'title');
                    557: 	if ($namewanted && ($name eq $namewanted)) {
                    558: 	    $result=$file;
                    559: 	    last;
                    560: 	} else {
                    561: 	    if ($name) { push (@allnames, $name); }
                    562: 	}
                    563:     }
                    564:     if (@allnames && !$result) {
1.146   ! albertel  565: 	$result="<option>".&mt("Select a")." $extension ".&mt('template')."</option>\n<option>".
1.145     albertel  566: 	    join('</option><option>',sort(@allnames)).'</option>';
1.42      albertel  567:     }
1.145     albertel  568:     return $result;
1.42      albertel  569: }
                    570: 
                    571: sub newproblem {
1.65      matthew   572:     my ($request) = @_;
                    573:     my $extension=$request->uri;
                    574:     $extension=~s:^.*\.([\w]+)$:$1:;
                    575:     &Apache::lonxml::debug("Looking for :$extension:");
1.131     albertel  576:     my $templatelist=&get_template_list('',$extension);
1.85      albertel  577:     if ($ENV{'form.template'} &&
1.128     albertel  578: 	$ENV{'form.template'} ne "Select a $extension template") {
1.65      matthew   579: 	use File::Copy;
                    580: 	my $file = &get_template_list($ENV{'form.template'},$extension);
                    581: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
                    582: 	copy($file,$dest);
                    583: 	&renderpage($request,$dest);
1.131     albertel  584:     } elsif($ENV{'form.newfile'} && !$templatelist) {
                    585: 	# I don't like hard-coded filenames but for now, this will work.
                    586: 	use File::Copy;
                    587: 	my $templatefilename =
                    588: 	    $request->dir_config('lonIncludes').'/templates/blank.problem';
                    589: 	&Apache::lonxml::debug("$templatefilename");
                    590: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
                    591: 	copy($templatefilename,$dest);
                    592: 	&renderpage($request,$dest);
1.85      albertel  593:     } else {
1.65      matthew   594: 	my $url=$request->uri;
                    595: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.128     albertel  596: 	my $errormsg;
                    597: 	if ($ENV{'form.newfile'}) {
1.146   ! albertel  598: 	    $errormsg='<p><font color="red">'.&mt('You did not select a template.').'</font></p>'."\n";
1.128     albertel  599: 	}
1.85      albertel  600: 	my $instructions;
1.146   ! albertel  601: 	if ($templatelist) { $instructions=&mt(", select a template from the pull-down menu below.").'<br />'.&mt("Then");}
        !           602: 	my %lt=&texthash( 'create' => 'Creating a new',
        !           603: 			  'resource' => 'resource',
        !           604: 			  'requested' => 'The requested file',
        !           605: 			  'not exist' => 'currently does not exist',
        !           606: 			  'createnew' => 'To create a new',
        !           607: 			  'click' => 'click on the',
        !           608: 			  'Create' => 'Create',
        !           609: 			  'button' => 'button');
1.65      matthew   610: 	$request->print(<<ENDNEWPROBLEM);
1.42      albertel  611: <body bgcolor="#FFFFFF">
1.146   ! albertel  612: <h1>$lt{'create'} $extension &lt{'resource'}</h1>
1.128     albertel  613: $errormsg
1.146   ! albertel  614: $lt{'requested'} <tt>$url</tt> $lt{'not exist'}.
1.105     www       615: <p>
1.146   ! albertel  616: <b>$lt{'createnew'} $extension$instructions $lt{'click'} "$lt{'Create'} $extension" $lt{'button'}.</b>
1.105     www       617: </p>
                    618: <p><form action="$url" method="POST">
1.42      albertel  619: ENDNEWPROBLEM
1.85      albertel  620: 	if (defined($templatelist)) {
                    621: 	    $request->print("<select name=\"template\">$templatelist</select>");
                    622: 	}
1.146   ! albertel  623: 	$request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"".&mt('Create')." $extension\" />");
1.105     www       624: 	$request->print("</form></p></body>");
1.65      matthew   625:     }
                    626:     return '';
1.42      albertel  627: }
                    628: 
                    629: sub view_or_edit_menu {
1.145     albertel  630:     my ($request) = @_;
                    631:     my $url=$request->uri;
1.146   ! albertel  632:     my %lt=&texthash( 'would' => 'Would you like to',
        !           633: 		      'view' => 'View',
        !           634: 		      'Edit' => 'edit',
        !           635: 		      'or' => 'or',
        !           636: 		      'the problem' => 'the problem');
1.145     albertel  637:     $request->print(<<EDITMENU);
1.42      albertel  638: <body bgcolor="#FFFFFF">
                    639: <form action="$url" method="POST">
1.146   ! albertel  640: $lt{'would'} <input type="submit" name="problemmode" value="&lt{'view'}">
        !           641: &lt{'or'} <input type="submit" name="problemmode" value="&lt{'Edit'}">
        !           642: &lt{'the problem'}.
1.42      albertel  643: </form>
                    644: </body>
                    645: EDITMENU
                    646: }
                    647: 
1.41      albertel  648: sub handler {
1.145     albertel  649:     #my $t0 = [&gettimeofday()];
                    650:     my $request=$_[0];
                    651:     
                    652:     $Apache::lonxml::debug=$ENV{'user.debug'};
1.41      albertel  653: 
1.145     albertel  654:     if (&setupheader($request)) { return OK; }
                    655:     $ENV{'request.uri'}=$request->uri;
1.41      albertel  656: 
1.145     albertel  657:     #setup permissions
                    658:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
                    659:     $Apache::lonhomework::viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
                    660:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:");
                    661:     # some times multiple problemmodes are submitted, need to select
                    662:     # the last one
                    663:     &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
                    664:     if ( defined($ENV{'form.problemmode'}) &&
                    665: 	 ref($ENV{'form.problemmode'}) ) {
                    666: 	&Apache::lonxml::debug("Problem Mode ".join(",",@$ENV{'form.problemmode'}));
                    667: 	my $mode=$ENV{'form.problemmode'}->[-1];
                    668: 	undef $ENV{'form.problemmode'};
                    669: 	$ENV{'form.problemmode'}=$mode;
                    670:     }
                    671:     &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
                    672:     my $file=&Apache::lonnet::filelocation("",$request->uri);
                    673: 
                    674:     #check if we know where we are
                    675:     if ($ENV{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
                    676: 	# if we are browsing we might not be able to know where we are
                    677: 	if ($Apache::lonhomework::browse ne 'F') {
                    678: 	    #should know where we are, so ask
                    679: 	    if ( &Apache::lonnet::mod_perl_version() == 2 ) {
                    680: 		&Apache::lonnet::cleanenv();
                    681: 	    }
                    682: 	    $request->internal_redirect('/adm/ambiguous'); return;
                    683: 	}
                    684:     }
1.41      albertel  685: 
1.145     albertel  686:     my ($symb) = &Apache::lonxml::whichuser();
                    687:     &Apache::lonxml::debug('symb is '.$symb);
                    688:     if ($ENV{'request.state'} eq "construct" || $symb eq '') {
                    689: 	if ($ENV{'form.resetdata'} eq 'Reset Submissions' ||
                    690: 	    $ENV{'form.resetdata'} eq 'New Problem Variation' ||
                    691: 	    $ENV{'form.newrandomization'} eq 'New Randomization') {
                    692: 	    my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                    693: 	    &Apache::lonnet::tmpreset($symb,'',$domain,$name);
                    694: 	    &Apache::lonxml::debug("Attempt reset");
                    695: 	}
                    696:     }
                    697:     if ($ENV{'request.state'} eq "construct") {
                    698: 	if ( -e $file ) {
                    699: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                    700: 						    ['problemmode']);
                    701: 	    if (!(defined $ENV{'form.problemmode'})) {
                    702: 		#first visit to problem in construction space
                    703: 		#&view_or_edit_menu($request);
                    704: 		$ENV{'form.problemmode'}='View';
                    705: 		&renderpage($request,$file);
                    706: 	    } elsif ($ENV{'form.problemmode'} eq 'EditXML') {
                    707: 		&editxmlmode($request,$file);
                    708: 	    } elsif ($ENV{'form.problemmode'} eq 'Calculate answers') {
                    709: 		&analyze($request,$file);
                    710: 	    } else {
                    711: 		&renderpage($request,$file);
                    712: 	    }
                    713: 	} else {
                    714: 	    # requested file doesn't exist in contruction space
                    715: 	    &newproblem($request);
                    716: 	}
                    717:     } else {
                    718: 	# just render the page normally outside of construction space
                    719: 	&Apache::lonxml::debug("not construct");
1.52      albertel  720: 	&renderpage($request,$file);
1.41      albertel  721:     }
1.145     albertel  722:     #my $td=&tv_interval($t0);
                    723:     #&Apache::lonxml::debug("Spent $td seconds processing");
                    724:     # &Apache::lonhomework::send_footer($request);
                    725:     # always turn off debug messages
                    726:     $Apache::lonxml::debug=0;
                    727:     return OK;
1.52      albertel  728: 
1.1       albertel  729: }
                    730: 
                    731: 1;
                    732: __END__

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