File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.204: download - view: text, annotated - select for diffs
Thu Apr 7 06:56:21 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: version_1_99_0_tmcc, HEAD
- ENV -> env

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

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