File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.183: download - view: text, annotated - select for diffs
Sat Nov 13 20:40:32 2004 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: version_1_2_99_0, HEAD
- add in bodytag for edixtxml and anlyze modes

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

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