File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.163: download - view: text, annotated - select for diffs
Fri Feb 13 21:21:30 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- constructions space, can now go into 'CANNOT_ANSWER' mode

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

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