Annotation of loncom/homework/lonhomework.pm, revision 1.246

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

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