File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.150: download - view: text, annotated - select for diffs
Fri Sep 19 20:29:29 2003 UTC (21 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- start locaization of structuretags.pm
- need to check form values against localized versions of string (it works!)
- Need to stop enociding high ascci othewise no umlauts

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

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