File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.160: download - view: text, annotated - select for diffs
Thu Jan 15 03:44:01 2004 UTC (20 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
FAQ and bugs on problem editing

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

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