File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.205: download - view: text, annotated - select for diffs
Fri Apr 29 21:22:33 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- adding 'webgrade' target for bridgetasks

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

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