File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.168: download - view: text, annotated - select for diffs
Mon Feb 16 20:30:34 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- localizing problem state setter

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

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