File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.213: download - view: text, annotated - select for diffs
Wed Jul 13 19:48:07 2005 UTC (18 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4218 - editxml needs to save then render for error messages

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

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