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

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

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