File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.189: download - view: text, annotated - select for diffs
Mon Dec 20 17:24:10 2004 UTC (19 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- trying to prvent the creation of yet another debug facilty, correcting some comments

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

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