File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.167: download - view: text, annotated - select for diffs
Mon Feb 16 19:19:31 2004 UTC (20 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#1682, the ficred state 'Open and correct' Coupled with 'Don't Show Feedback' now works properly, I.e. it doesn't dhow feedback and state is properly set to 'CAN_ANSWER'

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Homework handler
    3: #
    4: # $Id: lonhomework.pm,v 1.167 2004/02/16 19:19:31 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','is in this state by royal decree.');
  209: 		}
  210: 	    } else {
  211: 		return ($ENV{'form.problemstate'},
  212: 			'is in this state by royal decree.');
  213: 	    }
  214: 	}
  215: 	&Apache::lonxml::debug("in construction ignoring dates");
  216: 	$status='CAN_ANSWER';
  217: 	$datemsg=&mt('is in under construction');
  218: #	return ($status,$datemsg);
  219:     }
  220: 
  221:     &Apache::lonxml::debug("checking for part :$id:");
  222:     &Apache::lonxml::debug("time:".time);
  223: 
  224:     if ($ENV{'request.state'} ne "construct") {
  225: 	my $allowed=&check_ip_acc(&Apache::lonnet::EXT("resource.$id.acc"));
  226: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
  227: 	    $status='INVALID_ACCESS';
  228: 	    $date=&mt("can not be accessed from your location.");
  229: 	    return($status,$date);
  230: 	}
  231: 	
  232: 	foreach $temp ("opendate","duedate","answerdate") {
  233: 	    $lastdate = $date;
  234: 	    $date = &Apache::lonnet::EXT("resource.$id.$temp");
  235: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
  236: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
  237: 		$date     =~ /^(con_lost|no_such_host)/) {
  238: 		$status='UNAVAILABLE';
  239: 		$date=&mt("may open later.");
  240: 		return($status,$date);
  241: 	    }
  242: 	    if ($thistype eq 'date_interval') {
  243: 		if ($temp eq 'opendate') {
  244: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
  245: 		}
  246: 		if ($temp eq 'answerdate') {
  247: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
  248: 		}
  249: 	    }
  250: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
  251: 	    if ($date eq '') {
  252: 		$date = &mt("an unknown date"); $passed = 0;
  253: 	    } elsif ($date eq 'con_lost') {
  254: 		$date = &mt("an indeterminate date"); $passed = 0;
  255: 	    } else {
  256: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
  257: 		$date = localtime $date;
  258: 	    }
  259: 	    if (!$passed) { $type=$temp; last; }
  260: 	}
  261: 	&Apache::lonxml::debug("have :$type:$passed:");
  262: 	if ($passed) {
  263: 	    $status='SHOW_ANSWER';
  264: 	    $datemsg=$date;
  265: 	} elsif ($type eq 'opendate') {
  266: 	    $status='CLOSED';
  267: 	    $datemsg = &mt("will open on")." $date";
  268: 	} elsif ($type eq 'duedate') {
  269: 	    $status='CAN_ANSWER';
  270: 	    $datemsg = &mt("is due at")." $date";
  271: 	} elsif ($type eq 'answerdate') {
  272: 	    $status='CLOSED';
  273: 	    $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
  274: 	}
  275:     }
  276:     if ($status eq 'CAN_ANSWER') {
  277: 	#check #tries, and if correct.
  278: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
  279: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
  280: 	if ( $tries eq '' ) { $tries = '0'; }
  281: 	if ( $maxtries eq '' && 
  282: 	     $ENV{'request.state'} ne 'construct') { $maxtries = '2'; } 
  283: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
  284: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
  285: 	if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
  286: 	    &&
  287: 	    lc($Apache::lonhomework::problemstatus) ne 'no')
  288: 	   ||
  289: 	   $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
  290: 	    $status = 'CANNOT_ANSWER';
  291: 	}
  292:     }
  293: 
  294:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
  295:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
  296:   #    return ('UNCHECKEDOUT','needs to be checked out');
  297:   #}
  298: 
  299: 
  300:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
  301:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
  302: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
  303: 	$status='CAN_ANSWER';
  304: 	$datemsg=&mt('is closed but you are allowed to view it');
  305:     }
  306: 
  307:     return ($status,$datemsg);
  308: }
  309: 
  310: sub showhash {
  311:     my (%hash) = @_;
  312:     &showhashsubset(\%hash,'.');
  313:     return '';
  314: }
  315: 
  316: sub showarray {
  317:     my ($array)=@_;
  318:     my $string="(";
  319:     foreach my $elm (@{ $array }) {
  320: 	if (ref($elm)) {
  321: 	    if ($elm =~ /ARRAY/ ) {
  322: 		$string.=&showarray($elm);
  323: 	    }
  324: 	} else {
  325: 	    $string.="$elm,"
  326: 	}
  327:     }
  328:     chop($string);
  329:     $string.=")";
  330:     return $string;
  331: }
  332: 
  333: sub showhashsubset {
  334:     my ($hash,$keyre) = @_;
  335:     my $resultkey;
  336:     foreach $resultkey (sort keys %$hash) {
  337: 	if ($resultkey =~ /$keyre/) {
  338: 	    if (ref($$hash{$resultkey})) {
  339: 		if ($$hash{$resultkey} =~ /ARRAY/ ) {
  340: 		    &Apache::lonxml::debug("$resultkey ---- ".
  341: 					   &showarray($$hash{$resultkey}));
  342: 		} elsif ($$hash{$resultkey} =~ /HASH/ ) {
  343: 		    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  344: 		    &showhashsubset($$hash{$resultkey},'.');
  345: 		} else {
  346: 		    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  347: 		}
  348: 	    } else {
  349: 		&Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  350: 	    }
  351: 	}
  352:     }
  353:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
  354:     return '';
  355: }
  356: 
  357: sub setuppermissions {
  358:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
  359:     my $viewgrades = &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
  360:     if (! $viewgrades && 
  361: 	exists($ENV{'request.course.sec'}) && 
  362: 	$ENV{'request.course.sec'} !~ /^\s*$/) {
  363: 	$viewgrades = &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'}.
  364:                                                '/'.$ENV{'request.course.sec'});
  365:     }
  366:     $Apache::lonhomework::viewgrades = $viewgrades;
  367:     return ''
  368: }
  369: 
  370: sub setupheader {
  371:     my $request=$_[0];
  372:     if ($ENV{'browser.mathml'}) {
  373: 	&Apache::loncommon::content_type($request,'text/xml');
  374:     } else {
  375: 	&Apache::loncommon::content_type($request,'text/html');
  376:     }
  377:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
  378: 	&Apache::loncommon::no_cache($request);
  379:     }
  380:     $request->send_http_header;
  381:     return OK if $request->header_only;
  382:     return ''
  383: }
  384: 
  385: sub handle_save_or_undo {
  386:     my ($request,$problem,$result) = @_;
  387:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
  388:     my $filebak =$file.".bak";
  389:     my $filetmp =$file.".tmp";
  390:     my $error=0;
  391: 
  392:     &Apache::lonnet::correct_line_ends($result);
  393: 
  394:     if ($ENV{'form.Undo'} eq &mt('undo')) {
  395: 	my $error=0;
  396: 	if (!copy($file,$filetmp)) { $error=1; }
  397: 	if ((!$error) && (!copy($filebak,$file))) { $error=1; }
  398: 	if ((!$error) && (!move($filetmp,$filebak))) { $error=1; }
  399: 	if (!$error) {
  400: 	    $request->print("<p><b>".&mt("Undid changes, Switched")." $filebak ".&mt("and")." $file</b></p>");
  401: 	} else {
  402: 	    $request->print("<p><font color=\"red\" size=\"+1\"><b>".&mt("Unable to undo, unable to switch")." $filebak ".&mt("and")." $file</b></font></p>");
  403: 	    $error=1;
  404: 	}
  405:     } else {
  406: 	my $fs=Apache::File->new(">$filebak");
  407: 	if (defined($fs)) {
  408: 	    print $fs $$problem;
  409: 	    $request->print("<b>".&mt("Making Backup to").
  410: 			    " $filebak</b><br />");
  411: 	} else {
  412: 	    $request->print("<font color=\"red\" size=\"+1\"><b>".&mt("Unable to make backup")." $filebak</b></font>");
  413: 	    $error=2;
  414: 	}
  415: 	my $fh=Apache::File->new(">$file");
  416: 	if (defined($fh)) {
  417: 	    print $fh $$result;
  418: 	    $request->print("<b>".&mt("Saving Modifications to").
  419: 			    " $file</b><br />");
  420: 	} else {
  421: 	    $request->print("<font color=\"red\" size=\"+1\"><b>".
  422: 			    &mt("Unable to write to")." $file</b></font>");
  423: 	    $error|=4;
  424: 	}
  425:     }
  426:     return $error;
  427: }
  428: 
  429: sub analyze_header {
  430:     my ($request) = @_;
  431:     my $result.='<html>
  432:             <head><title>'.&mt("Analyzing a problem").'</title></head>
  433:             <body bgcolor="#FFFFFF">
  434:             <form name="lonhomework" method="POST" action="'.
  435: 	    $ENV{'request.uri'}.'">
  436:             <input type="submit" name="problemmode" value="'.&mt("EditXML").'" />
  437:             <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
  438:             <hr />
  439:             <input type="submit" name="submit" value="'.&mt("View").'" />
  440:             <hr />
  441:             '.&mt('List of possible answers').':
  442:             </form>';
  443:     $request->print($result);
  444:     $request->rflush();
  445: }
  446: 
  447: sub analyze_footer {
  448:     my ($request) = @_;
  449:     my $result='</body></html>';
  450:     $request->print($result);
  451:     $request->rflush();
  452: }
  453: 
  454: sub analyze {
  455:     my ($request,$file) = @_;
  456:     &Apache::lonxml::debug("Analyze");
  457:     my $result;
  458:     my %overall;
  459:     my %allparts;
  460:     my $rndseed=$ENV{'form.rndseed'};
  461:     &analyze_header($request);
  462:     my %prog_state=
  463: 	&Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
  464: 					      &mt('Getting Problem Variants'),
  465: 					      $ENV{'form.numtoanalyze'});
  466:     for(my $i=1;$i<$ENV{'form.numtoanalyze'}+1;$i++) {
  467: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
  468: 						 &mt('last problem'));
  469: 	my $subresult=&Apache::lonnet::ssi($request->uri,
  470: 					   ('grade_target' => 'analyze'),
  471: 					   ('rndseed' => $i+$rndseed));
  472: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
  473: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  474: 	my @parts;
  475: 	if (defined(@{ $analyze{'parts'} })) {
  476: 	    @parts=@{ $analyze{'parts'} };
  477: 	}
  478: 	foreach my $part (@parts) {
  479: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
  480: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
  481: 		$analyze{$part.'.type'} eq 'stringresponse'	||
  482: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
  483: 		push( @{ $overall{$part.'.answer'} },
  484: 		      [@{ $analyze{$part.'.answer'} }]);
  485: 	    }
  486: 	}
  487:     }
  488:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
  489: 					  &mt('Analyzing Results'));
  490:     foreach my $part (sort(keys(%allparts))) {
  491: 	if (defined(@{ $overall{$part.'.answer'} })) {
  492: 	    my $num_cols=scalar(@{ $overall{$part.'.answer'}->[0] });
  493: 	    $request->print('<table><tr><td colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part.'</td></tr>');
  494: 	    my %frequency;
  495: 	    foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'} })) {
  496: 		$frequency{join("\0",@{ $answer })}++;
  497: 	    }
  498: 	    $request->print('<tr><td colspan="'.($num_cols).'">'.&mt('Answer').'</td><td>'.&mt('Frequency').'</td></tr>');
  499: 	    foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
  500: 		$request->print('<tr><td align="right">'.
  501: 				join('</td><td align="right">',split("\0",$answer)).
  502: 				'</td><td>('.$frequency{$answer}.
  503: 				')</td></tr>');
  504: 	    }
  505: 	    $request->print('</table>');
  506: 	} else {
  507: 	    $request->print('<p>'.&mt('Response').' '.$part.' '.
  508: 			    &mt('is not analyzable at this time').'</p>');
  509: 	}
  510:     }
  511:     if (scalar(keys(%allparts)) == 0 ) {
  512: 	$request->print('<p>'.&mt('Found no analyzable respones in this problem, currently only Numerical, Formula and String response styles are supported.').'</p>');
  513:     }
  514:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
  515:     &analyze_footer($request);
  516:     &Apache::lonhomework::showhash(%overall);
  517:     return $result;
  518: }
  519: 
  520: sub editxmlmode {
  521:     my ($request,$file) = @_;
  522:     my $result;
  523:     my $problem=&Apache::lonnet::getfile($file);
  524:     if ($problem eq -1) {
  525: 	&Apache::lonxml::error("<b> ".&mt('Unable to find').
  526: 			       " <i>$file</i></b>");
  527: 	$problem='';
  528:     }
  529:     if (defined($ENV{'form.editxmltext'}) || defined($ENV{'form.Undo'})) {
  530: 	my $error=&handle_save_or_undo($request,\$problem,
  531: 				       \$ENV{'form.editxmltext'});
  532: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
  533:     }
  534:     &Apache::lonhomework::showhashsubset(\%ENV,'^form');
  535:     if ( $ENV{'form.submit'} eq &mt('Submit Changes and View') ) {
  536: 	&Apache::lonhomework::showhashsubset(\%ENV,'^form');
  537: 	$ENV{'form.problemmode'}='View';
  538: 	&renderpage($request,$file);
  539:     } else {
  540: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
  541: 	my $xml_help = '<table><tr><td>'.
  542: 	    &Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
  543: 						    "Problem Editing Help").
  544: 						    '</td><td>'.
  545:        &Apache::loncommon::help_open_faq(5).
  546:        &Apache::loncommon::help_open_bug('Authoring').'</td></tr></table>';
  547: 	if ($cols > 80) { $cols = 80; }
  548: 	if ($cols < 70) { $cols = 70; }
  549: 	if ($rows < 20) { $rows = 20; }
  550: 	$result.='<html><body bgcolor="#FFFFFF">
  551:             <form name="lonhomework" method="POST" action="'.
  552: 	    $ENV{'request.uri'}.'">
  553:             <input type="hidden" name="problemmode" value="'.&mt('EditXML').'" />
  554:             <input type="submit" name="problemmode" value="'.&mt('Discard Edits and View').'" />
  555:             <input type="submit" name="problemmode" value="'.&mt('Edit').'" />
  556:             <hr />
  557:             <input type="submit" name="submit" value="'.&mt('Submit Changes').'" />
  558:             <input type="submit" name="submit" value="'.&mt('Submit Changes and View').'" />
  559:             <input type="submit" name="Undo" value="'.&mt('undo').'" />
  560:             <hr />
  561:             ' . $xml_help . '
  562:             <textarea rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
  563: 	    &HTML::Entities::encode($problem).'</textarea>
  564:             </form></body></html>';
  565: 	$request->print($result);
  566:     }
  567:     return '';
  568: }
  569: 
  570: sub renderpage {
  571:     my ($request,$file) = @_;
  572: 
  573:     my (@targets) = &get_target();
  574:     &Apache::lonhomework::showhashsubset(\%ENV,'form.');
  575:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
  576:     foreach my $target (@targets) {
  577: 	#my $t0 = [&gettimeofday()];
  578: 	my $problem=&Apache::lonnet::getfile($file);
  579: 	if ($problem eq -1) {
  580: 	    &Apache::lonxml::error("<b> ".&mt('Unable to find')." <i>$file</i></b>");
  581: 	    $problem='';
  582: 	}
  583: 
  584: 	my %mystyle;
  585: 	my $result = '';
  586: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
  587: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
  588: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%ENV,'^form');}
  589: 
  590: 	&Apache::lonxml::debug("Should be parsing now");
  591: 	$result = &Apache::lonxml::xmlparse($request, $target, $problem,
  592: 					    &setup_vars($target),%mystyle);
  593: 	undef($Apache::lonhomework::parsing_a_problem);
  594: 	#$request->print("Result follows:");
  595: 	if ($target eq 'modified') {
  596: 	    &handle_save_or_undo($request,\$problem,\$result);
  597: 	} else {
  598: 	    if ($target eq 'analyze') {
  599: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
  600: 		undef(%Apache::lonhomework::analyze);
  601: 	    }
  602: 	    #my $td=&tv_interval($t0);
  603: 	    #if ( $Apache::lonxml::debug) {
  604: 	    #$result =~ s:</body>::;
  605: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
  606: 	    #}
  607: 	    $request->print($result);
  608: 	    $request->rflush();
  609: 	}
  610: 	#$request->print(":Result ends");
  611: 	#my $td=&tv_interval($t0);
  612:     }
  613: }
  614: 
  615: # with no arg it returns a HTML <option> list of the template titles
  616: # with one arg it returns the filename associated with the arg passed
  617: sub get_template_list {
  618:     my ($namewanted,$extension) = @_;
  619:     my $result;
  620:     my @allnames;
  621:     &Apache::lonxml::debug("Looking for :$extension:");
  622:     foreach my $file (</home/httpd/html/res/adm/includes/templates/*.$extension>) {
  623: 	my $name=&Apache::lonnet::metadata($file,'title');
  624: 	if ($namewanted && ($name eq $namewanted)) {
  625: 	    $result=$file;
  626: 	    last;
  627: 	} else {
  628: 	    if ($name) { push (@allnames, $name); }
  629: 	}
  630:     }
  631:     if (@allnames && !$result) {
  632: 	$result="<option>".&mt("Select a")." $extension ".&mt('template')."</option>\n<option>".
  633: 	    join('</option><option>',sort(@allnames)).'</option>';
  634:     }
  635:     return $result;
  636: }
  637: 
  638: sub newproblem {
  639:     my ($request) = @_;
  640:     my $extension=$request->uri;
  641:     $extension=~s:^.*\.([\w]+)$:$1:;
  642:     &Apache::lonxml::debug("Looking for :$extension:");
  643:     my $templatelist=&get_template_list('',$extension);
  644:     if ($ENV{'form.template'} &&
  645: 	$ENV{'form.template'} ne "Select a $extension template") {
  646: 	use File::Copy;
  647: 	my $file = &get_template_list($ENV{'form.template'},$extension);
  648: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
  649: 	copy($file,$dest);
  650: 	&renderpage($request,$dest);
  651:     } elsif($ENV{'form.newfile'} && !$templatelist) {
  652: 	# I don't like hard-coded filenames but for now, this will work.
  653: 	use File::Copy;
  654: 	my $templatefilename =
  655: 	    $request->dir_config('lonIncludes').'/templates/blank.problem';
  656: 	&Apache::lonxml::debug("$templatefilename");
  657: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
  658: 	copy($templatefilename,$dest);
  659: 	&renderpage($request,$dest);
  660:     } else {
  661: 	my $url=$request->uri;
  662: 	my $shownurl=$url;
  663: 	$shownurl=~s-^/~-/priv/-;
  664: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
  665: 	my $errormsg;
  666: 	if ($ENV{'form.newfile'}) {
  667: 	    $errormsg='<p><font color="red">'.&mt('You did not select a template.').'</font></p>'."\n";
  668: 	}
  669: 	my $instructions;
  670: 	my $bodytag=&Apache::loncommon::bodytag(undef,undef,undef,1);
  671: 	if ($templatelist) { $instructions=&mt(", select a template from the pull-down menu below.").'<br />'.&mt("Then");}
  672: 	my %lt=&Apache::lonlocal::texthash( 'create' => 'Creating a new',
  673: 			  'resource' => 'resource',
  674: 			  'requested' => 'The requested file',
  675: 			  'not exist' => 'currently does not exist',
  676: 			  'createnew' => 'To create a new',
  677: 			  'click' => 'click on the',
  678: 			  'Create' => 'Create',
  679: 			  'button' => 'button');
  680: 	$request->print(<<ENDNEWPROBLEM);
  681: $bodytag
  682: <h1>$lt{'create'} $extension $lt{'resource'}</h1>
  683: $errormsg
  684: $lt{'requested'} <tt>$shownurl</tt> $lt{'not exist'}.
  685: <p>
  686: <b>$lt{'createnew'} $extension$instructions $lt{'click'} "$lt{'Create'} $extension" $lt{'button'}.</b>
  687: </p>
  688: <p><form action="$url" method="POST">
  689: ENDNEWPROBLEM
  690: 	if (defined($templatelist)) {
  691: 	    $request->print("<select name=\"template\">$templatelist</select>");
  692: 	}
  693: 	$request->print("<br /><input type=\"submit\" name=\"newfile\" value=\"".&mt('Create')." $extension\" />");
  694: 	$request->print("</form></p></body>");
  695:     }
  696:     return '';
  697: }
  698: 
  699: sub view_or_edit_menu {
  700:     my ($request) = @_;
  701:     my $url=$request->uri;
  702:     my %lt=&Apache::lonlocal::texthash( 'would' => 'Would you like to',
  703: 		      'view' => 'View',
  704: 		      'Edit' => 'edit',
  705: 		      'or' => 'or',
  706: 		      'the problem' => 'the problem');
  707:     $request->print(<<EDITMENU);
  708: <body bgcolor="#FFFFFF">
  709: <form action="$url" method="POST">
  710: $lt{'would'} <input type="submit" name="problemmode" value="&lt{'view'}">
  711: &lt{'or'} <input type="submit" name="problemmode" value="&lt{'Edit'}">
  712: &lt{'the problem'}.
  713: </form>
  714: </body>
  715: EDITMENU
  716: }
  717: 
  718: sub handler {
  719:     #my $t0 = [&gettimeofday()];
  720:     my $request=$_[0];
  721:     
  722:     $Apache::lonxml::debug=$ENV{'user.debug'};
  723:     if (&setupheader($request)) { return OK; }
  724:     $ENV{'request.uri'}=$request->uri;
  725: 
  726:     #setup permissions
  727:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$ENV{'request.filename'});
  728:     $Apache::lonhomework::viewgrades=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'});
  729:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:");
  730:     # some times multiple problemmodes are submitted, need to select
  731:     # the last one
  732:     &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
  733:     if ( defined($ENV{'form.problemmode'}) &&
  734: 	 ref($ENV{'form.problemmode'}) ) {
  735: 	&Apache::lonxml::debug("Problem Mode ".join(",",@$ENV{'form.problemmode'}));
  736: 	my $mode=$ENV{'form.problemmode'}->[-1];
  737: 	undef $ENV{'form.problemmode'};
  738: 	$ENV{'form.problemmode'}=$mode;
  739:     }
  740:     &Apache::lonxml::debug("Problem Mode ".$ENV{'form.problemmode'});
  741:     my $file=&Apache::lonnet::filelocation("",$request->uri);
  742: 
  743:     #check if we know where we are
  744:     if ($ENV{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
  745: 	# if we are browsing we might not be able to know where we are
  746: 	if ($Apache::lonhomework::browse ne 'F') {
  747: 	    #should know where we are, so ask
  748: 	    if ( &Apache::lonnet::mod_perl_version() == 2 ) {
  749: 		&Apache::lonnet::cleanenv();
  750: 	    }
  751: 	    $request->internal_redirect('/adm/ambiguous'); return;
  752: 	}
  753:     }
  754: 
  755:     my ($symb) = &Apache::lonxml::whichuser();
  756:     &Apache::lonxml::debug('symb is '.$symb);
  757:     if ($ENV{'request.state'} eq "construct" || $symb eq '') {
  758: 	if ($ENV{'form.resetdata'} eq &mt('Reset Submissions') ||
  759: 	    $ENV{'form.resetdata'} eq &mt('New Problem Variation') ||
  760: 	    $ENV{'form.newrandomization'} eq &mt('New Randomization')) {
  761: 	    my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
  762: 	    &Apache::lonnet::tmpreset($symb,'',$domain,$name);
  763: 	    &Apache::lonxml::debug("Attempt reset");
  764: 	}
  765:     }
  766:     if ($ENV{'request.state'} eq "construct") {
  767: 	if ( -e $file ) {
  768: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  769: 						    ['problemmode']);
  770: 	    if (!(defined $ENV{'form.problemmode'})) {
  771: 		#first visit to problem in construction space
  772: 		#&view_or_edit_menu($request);
  773: 		$ENV{'form.problemmode'}='View';
  774: 		&renderpage($request,$file);
  775: 	    } elsif ($ENV{'form.problemmode'} eq &mt('EditXML')) {
  776: 		&editxmlmode($request,$file);
  777: 	    } elsif ($ENV{'form.problemmode'} eq &mt('Calculate answers')) {
  778: 		&analyze($request,$file);
  779: 	    } else {
  780: 		&renderpage($request,$file);
  781: 	    }
  782: 	} else {
  783: 	    # requested file doesn't exist in contruction space
  784: 	    &newproblem($request);
  785: 	}
  786:     } else {
  787: 	# just render the page normally outside of construction space
  788: 	&Apache::lonxml::debug("not construct");
  789: 	&renderpage($request,$file);
  790:     }
  791:     #my $td=&tv_interval($t0);
  792:     #&Apache::lonxml::debug("Spent $td seconds processing");
  793:     # &Apache::lonhomework::send_footer($request);
  794:     # always turn off debug messages
  795:     $Apache::lonxml::debug=0;
  796:     return OK;
  797: 
  798: }
  799: 
  800: 1;
  801: __END__

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