File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.224: download - view: text, annotated - select for diffs
Tue Nov 15 18:38:47 2005 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminating dead code

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

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