File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.206: download - view: text, annotated - select for diffs
Tue May 3 00:05:41 2005 UTC (19 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- adding gradding queus mechanism
   - submissions adds to grading queue
   - webgrade attempts to find a suitable user to grade and lock it to myself with proper error handling for a variety of failure modes (i.e tries to do a 2 phase commit)

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

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