File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.144: download - view: text, annotated - select for diffs
Wed Sep 17 18:16:39 2003 UTC (20 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- stupid typo
- removing the blind acceptance of the answers target as a form parameter

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

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