File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.190: download - view: text, annotated - select for diffs
Wed Dec 22 22:05:40 2004 UTC (19 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#3746

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

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