File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.241: download - view: text, annotated - select for diffs
Fri Apr 21 15:26:25 2006 UTC (18 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- strip adding leading or trailing whitespace from a slot definition

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

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