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

1.63      albertel    1: # The LearningOnline Network with CAPA
1.52      albertel    2: # The LON-CAPA Homework handler
1.63      albertel    3: #
1.300   ! jms         4: # $Id: lonhomework.pm,v 1.299 2008/11/19 18:34:56 jms 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.300   ! jms        28: =pod
        !            29: 
        !            30: =head1 NAME
        !            31: 
        !            32: Apache::lonhomework.pm
        !            33: 
        !            34: =head1 SYNOPSIS
        !            35: 
        !            36: handles requests for output, evaluation, and
        !            37: alteration of a homework resource
        !            38: 
        !            39: This is part of the LearningOnline Network with CAPA project
        !            40: described at http://www.lon-capa.org.
        !            41: 
        !            42: 
        !            43: =head1 NOTABLE SUBROUTINES
        !            44: 
        !            45: =cut
        !            46: 
1.1       albertel   47: 
                     48: package Apache::lonhomework;
                     49: use strict;
1.73      albertel   50: use Apache::style();
                     51: use Apache::lonxml();
1.204     albertel   52: use Apache::lonnet;
1.73      albertel   53: use Apache::lonplot();
                     54: use Apache::inputtags();
                     55: use Apache::structuretags();
                     56: use Apache::randomlabel();
                     57: use Apache::response();
                     58: use Apache::hint();
                     59: use Apache::outputtags();
1.83      albertel   60: use Apache::caparesponse();
                     61: use Apache::radiobuttonresponse();
                     62: use Apache::optionresponse();
                     63: use Apache::imageresponse();
                     64: use Apache::essayresponse();
                     65: use Apache::externalresponse();
1.106     albertel   66: use Apache::rankresponse();
1.107     albertel   67: use Apache::matchresponse();
1.137     albertel   68: use Apache::chemresponse();
1.169     albertel   69: use Apache::drawimage();
1.26      www        70: use Apache::Constants qw(:common);
1.83      albertel   71: use Apache::loncommon();
1.146     albertel   72: use Apache::lonlocal;
1.179     albertel   73: use Time::HiRes qw( gettimeofday tv_interval );
1.282     albertel   74: use HTML::Entities();
                     75: use File::Copy();
1.188     foxr       76: 
1.189     albertel   77: # FIXME - improve commenting
1.188     foxr       78: 
1.43      albertel   79: 
1.69      harris41   80: BEGIN {
1.145     albertel   81:     &Apache::lonxml::register_insert();
1.43      albertel   82: }
                     83: 
1.188     foxr       84: 
1.276     foxr       85: =pod
                     86: 
                     87: =item set_bubble_lines()
                     88: 
                     89: Called at analysis time to set the bubble lines
                     90: hash for the problem.. This should be called in the
                     91: end_problemtype tag in analysis mode.
                     92: 
                     93: We fetch the hash of part id counters from lonxml
                     94:     and push them into analyze:{part_id.bubble_lines}.
                     95: 
                     96: =cut
                     97: 
                     98: sub set_bubble_lines {
                     99:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
                    100: 
                    101:     foreach my $key (keys(%bubble_counters)) {
                    102: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
                    103: 	    $bubble_counters{"$key"};
                    104:     }
                    105: }
                    106: 
1.299     jms       107: =pod
                    108: 
                    109: =item get_target()
                    110: 
                    111: Decides what targets to render for.
                    112: Implicit inputs:
                    113:   Various session environment variables:
                    114:      request.state -  published  - is a /res/ resource
                    115:                       uploaded   - is a /uploaded/ resource
                    116:                       contruct   - is a /priv/ resource
                    117:      form.grade_target - a form parameter requesting a specific target
                    118: 
                    119: =cut
                    120: 
1.5       albertel  121: sub get_target {
1.204     albertel  122:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
                    123:     if( defined($env{'form.grade_target'})) {
                    124: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
1.188     foxr      125:     } else {
1.189     albertel  126: 	&Apache::lonxml::debug("form.grade_target <undefined>");
1.188     foxr      127:     }
1.204     albertel  128:     if (($env{'request.state'} eq "published") ||
                    129: 	($env{'request.state'} eq "uploaded")) {
                    130: 	if ( defined($env{'form.grade_target'}  ) 
                    131: 	     && ($env{'form.grade_target'} eq 'tex')) {
                    132: 	    return ($env{'form.grade_target'});
                    133: 	} elsif ( defined($env{'form.grade_target'}  ) 
1.145     albertel  134: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
1.207     albertel  135: 	    return ($env{'form.grade_target'});
1.244     albertel  136: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
                    137: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
                    138: 	    return ($env{'form.grade_target'});
1.207     albertel  139: 	}
                    140: 	if ($env{'form.webgrade'} &&
1.244     albertel  141: 	    ($Apache::lonhomework::modifygrades eq 'F'
                    142: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
1.207     albertel  143: 	    return ('grade','webgrade');
1.145     albertel  144: 	}
1.204     albertel  145: 	if ( defined($env{'form.submitted'}) &&
                    146: 	     ( !defined($env{'form.newrandomization'}))) {
1.217     albertel  147: 	    return ('grade', 'web');
1.145     albertel  148: 	} else {
1.217     albertel  149: 	    return ('web');
1.145     albertel  150: 	}
1.204     albertel  151:     } elsif ($env{'request.state'} eq "construct") {
                    152: 	if ( defined($env{'form.grade_target'}) ) {
                    153: 	    return ($env{'form.grade_target'});
1.145     albertel  154: 	}
1.204     albertel  155: 	if ( defined($env{'form.preview'})) {
                    156: 	    if ( defined($env{'form.submitted'})) {
1.145     albertel  157: 		return ('grade', 'web');
                    158: 	    } else {
                    159: 		return ('web');
                    160: 	    }
                    161: 	} else {
1.267     albertel  162: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
                    163: 		#$env{'form.webgrade'} = 'yes';
                    164: 		return ('grade','webgrade','answer');
1.289     raeburn   165: 	    } elsif (($env{'form.problemmode'} eq 'view') ||
                    166: 		     ($env{'form.problemmode'} eq 'discard')) {
1.204     albertel  167: 		if ( defined($env{'form.submitted'}) &&
                    168: 		     (!defined($env{'form.resetdata'})) &&
                    169: 		     (!defined($env{'form.newrandomization'}))) {
1.145     albertel  170: 		    return ('grade', 'web','answer');
                    171: 		} else {
                    172: 		    return ('web','answer');
                    173: 		}
1.289     raeburn   174: 	    } elsif ($env{'form.problemmode'} eq 'edit') {
1.204     albertel  175: 		if ( $env{'form.submitted'} eq 'edit' ) {
1.289     raeburn   176: 		    if ( $env{'form.submitbutton'} eq &mt('Save and View') ) {
1.145     albertel  177: 			return ('modified','web','answer');
                    178: 		    } else {
1.211     albertel  179: 			return ('modified','no_output_web','edit');
1.145     albertel  180: 		    }
                    181: 		} else {
1.211     albertel  182: 		    return ('no_output_web','edit');
1.145     albertel  183: 		}
                    184: 	    } else {
                    185: 		return ('web');
                    186: 	    }
                    187: 	}
1.15      albertel  188:     }
1.145     albertel  189:     return ();
1.5       albertel  190: }
                    191: 
1.3       albertel  192: sub setup_vars {
1.145     albertel  193:     my ($target) = @_;
                    194:     return ';'
1.11      albertel  195: #  return ';$external::target='.$target.';';
1.2       albertel  196: }
                    197: 
1.36      albertel  198: sub createmenu {
1.145     albertel  199:     my ($which,$request)=@_;
                    200:     if ($which eq 'grade') {
                    201: 	$request->print('<script language="JavaScript"> 
1.91      albertel  202:           hwkmenu=window.open("/res/adm/pages/homeworkmenu.html","homeworkremote",
1.52      albertel  203:                  "height=350,width=150,menubar=no");
                    204:           </script>');
1.145     albertel  205:     }
1.36      albertel  206: }
                    207: 
1.200     albertel  208: sub proctor_checked_in {
1.226     albertel  209:     my ($slot_name,$slot,$type)=@_;
                    210:     my @possible_proctors=split(",",$slot->{'proctor'});
                    211:     
1.248     albertel  212:     return 1 if (!@possible_proctors);
                    213: 
1.226     albertel  214:     my $key;
                    215:     if ($type eq 'Task') {
1.230     albertel  216: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
                    217: 	$key ="resource.$version.0.checkedin";
1.226     albertel  218:     } elsif ($type eq 'problem') {
                    219: 	$key ='resource.0.checkedin';
                    220:     }
1.249     albertel  221:     # backward compatability, used to be username@domain, 
                    222:     # now is username:domain
                    223:     my $who = $Apache::lonhomework::history{$key};
                    224:     if ($who !~ /:/) {
                    225: 	$who =~ tr/@/:/;
                    226:     }     
1.226     albertel  227:     foreach my $possible (@possible_proctors) { 
1.249     albertel  228: 	if ($who eq $possible
1.226     albertel  229: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
1.202     albertel  230: 	    return 1;
                    231: 	}
                    232:     }
1.226     albertel  233:     
1.200     albertel  234:     return 0;
                    235: }
                    236: 
1.226     albertel  237: sub check_slot_access {
                    238:     my ($id,$type)=@_;
                    239: 
1.207     albertel  240:     # does it pass normal muster
1.226     albertel  241:     my ($status,$datemsg)=&check_access($id);
                    242:     
1.252     albertel  243:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots");
1.251     albertel  244:     if ($useslots ne 'resource' && $useslots ne 'map' 
                    245: 	&& $useslots ne 'map_map') {
1.226     albertel  246: 	return ($status,$datemsg);
                    247:     }
                    248: 
1.200     albertel  249:     if ($status eq 'SHOW_ANSWER' ||
                    250: 	$status eq 'CLOSED' ||
                    251: 	$status eq 'INVALID_ACCESS' ||
                    252: 	$status eq 'UNAVAILABLE') {
                    253: 	return ($status,$datemsg);
                    254:     }
1.204     albertel  255:     if ($env{'request.state'} eq "construct") {
1.203     albertel  256: 	return ($status,$datemsg);
                    257:     }
1.226     albertel  258:     
                    259:     if ($type eq 'Task') {
                    260: 	my $version=$Apache::lonhomework::history{'resource.version'};
1.230     albertel  261: 	if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
                    262: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
1.226     albertel  263: 	    return ('SHOW_ANSWER');
                    264: 	}
1.207     albertel  265:     }
1.226     albertel  266: 
1.288     raeburn   267:     my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent");
                    268:     my $available = &Apache::lonnet::EXT("resource.0.available");
                    269:     my @slots= (split(':',$availablestudent),split(':',$available));
1.210     albertel  270: 
1.200     albertel  271: #    if (!@slots) {
                    272: #	return ($status,$datemsg);
                    273: #    }
                    274:     my $slotstatus='NOT_IN_A_SLOT';
1.206     albertel  275:     my ($returned_slot,$slot_name);
1.210     albertel  276:     foreach my $slot (@slots) {
1.241     albertel  277: 	$slot =~ s/(^\s*|\s*$)//g;
1.201     albertel  278: 	&Apache::lonxml::debug("getting $slot");
1.200     albertel  279: 	my %slot=&Apache::lonnet::get_slot($slot);
1.201     albertel  280: 	&Apache::lonhomework::showhash(%slot);
1.200     albertel  281: 	if ($slot{'starttime'} < time &&
                    282: 	    $slot{'endtime'} > time &&
1.297     raeburn   283: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
1.202     albertel  284: 	    &Apache::lonxml::debug("$slot is good");
                    285: 	    $slotstatus='NEEDS_CHECKIN';
                    286: 	    $returned_slot=\%slot;
1.206     albertel  287: 	    $slot_name=$slot;
1.200     albertel  288: 	    last;
                    289: 	}
                    290:     }
1.202     albertel  291:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
1.226     albertel  292: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
1.202     albertel  293: 	&Apache::lonxml::debug("protoctor checked in");
1.200     albertel  294: 	$slotstatus='CAN_ANSWER';
                    295:     }
1.226     albertel  296: 
1.235     albertel  297:     my ($is_correct,$got_grade,$checkedin);
1.226     albertel  298:     if ($type eq 'Task') {
1.230     albertel  299: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
1.231     albertel  300: 	$got_grade = 
                    301: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
                    302: 	     =~ /^(?:pass|fail)$/);
1.235     albertel  303: 	$is_correct =  
                    304: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
                    305: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
1.226     albertel  306: 	$checkedin =
1.230     albertel  307: 	    $Apache::lonhomework::history{"resource.$version.0.checkedin"};
1.226     albertel  308:     } elsif ($type eq 'problem') {
1.252     albertel  309: 	$got_grade  = 1;
                    310: 	$checkedin  = $Apache::lonhomework::history{"resource.0.checkedin"};
                    311: 	$is_correct =
                    312: 	    ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
1.226     albertel  313:     }
                    314:     
1.235     albertel  315:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
                    316:     
1.243     albertel  317:     # no slot is currently open, and has been checked in for this version
                    318:     # but hasn't got a grade, therefore must be awaiting a grade
                    319:     if (!defined($slot_name)
                    320: 	&& $checkedin 
1.236     albertel  321: 	&& !$got_grade) {
                    322: 	return ('WAITING_FOR_GRADE');
                    323:     }
                    324: 
1.252     albertel  325:     # no slot is currently open, and has been checked in for this version
                    326:     # previous slot is therefore CLOSED, so therefore the problem is
                    327:     if (!defined($slot_name)
                    328: 	&& $checkedin 
                    329: 	&& $type eq 'problem') {
                    330: 	return ('CLOSED',$datemsg);
                    331:     }
                    332: 
1.226     albertel  333:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
                    334: 	&& $checkedin ) {
                    335: 
1.231     albertel  336: 	if ($got_grade) {
1.209     albertel  337: 	    return ('SHOW_ANSWER');
                    338: 	} else {
                    339: 	    return ('WAITING_FOR_GRADE');
                    340: 	}
1.226     albertel  341: 
1.207     albertel  342:     }
1.255     albertel  343: 
1.235     albertel  344:     if ( $is_correct) {
1.255     albertel  345: 	if ($type eq 'problem') {
                    346: 	    return ($status);
                    347: 	}
1.235     albertel  348: 	return ('SHOW_ANSWER');
                    349:     }
1.255     albertel  350: 
1.225     albertel  351:     if ( $status eq 'CANNOT_ANSWER' && 
                    352: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
                    353: 	return ($status,$datemsg);
                    354:     }
                    355: 
1.206     albertel  356:     return ($slotstatus,$datemsg,$slot_name,$returned_slot);
1.198     albertel  357: }
1.200     albertel  358: 
1.299     jms       359: 
                    360: =pod
                    361: 
                    362: =item check_access()
                    363: 
                    364: JB, 9/24/2002: Any changes in this function may require a change
                    365: in lonnavmaps::resource::getDateStatus.
                    366: 
                    367: =cut
                    368: 
1.53      www       369: sub check_access {
1.145     albertel  370:     my ($id) = @_;
                    371:     my $date ='';
                    372:     my $status;
                    373:     my $datemsg = '';
                    374:     my $lastdate = '';
                    375:     my $type;
                    376:     my $passed;
                    377: 
1.204     albertel  378:     if ($env{'request.state'} eq "construct") {
                    379: 	if ($env{'form.problemstate'}) {
                    380: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
1.277     albertel  381: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
                    382: 			&& &hide_problem_status())) {
1.168     albertel  383: 		    return ('CANNOT_ANSWER',
1.174     www       384: 			    &mt('is in this state due to author settings.'));
1.167     albertel  385: 		}
1.165     albertel  386: 	    } else {
1.204     albertel  387: 		return ($env{'form.problemstate'},
1.174     www       388: 			&mt('is in this state due to author settings.'));
1.165     albertel  389: 	    }
                    390: 	}
1.145     albertel  391: 	&Apache::lonxml::debug("in construction ignoring dates");
                    392: 	$status='CAN_ANSWER';
1.146     albertel  393: 	$datemsg=&mt('is in under construction');
1.163     albertel  394: #	return ($status,$datemsg);
1.145     albertel  395:     }
                    396: 
                    397:     &Apache::lonxml::debug("checking for part :$id:");
                    398:     &Apache::lonxml::debug("time:".time);
1.152     albertel  399: 
1.261     albertel  400:     my ($symb)=&Apache::lonnet::whichuser();
1.212     albertel  401:     &Apache::lonxml::debug("symb:".$symb);
                    402:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
1.204     albertel  403:     if ($env{'request.state'} ne "construct") {
1.288     raeburn   404:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc");
1.297     raeburn   405: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
1.163     albertel  406: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
                    407: 	    $status='INVALID_ACCESS';
                    408: 	    $date=&mt("can not be accessed from your location.");
1.145     albertel  409: 	    return($status,$date);
                    410: 	}
1.163     albertel  411: 	
1.226     albertel  412: 	foreach my $temp ("opendate","duedate","answerdate") {
1.163     albertel  413: 	    $lastdate = $date;
1.247     albertel  414: 	    if ($temp eq 'duedate') {
                    415: 		$date = &due_date($id);
                    416: 	    } else {
                    417: 		$date = &Apache::lonnet::EXT("resource.$id.$temp");
                    418: 	    }
                    419: 	    
1.163     albertel  420: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
                    421: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
                    422: 		$date     =~ /^(con_lost|no_such_host)/) {
                    423: 		$status='UNAVAILABLE';
                    424: 		$date=&mt("may open later.");
                    425: 		return($status,$date);
                    426: 	    }
                    427: 	    if ($thistype eq 'date_interval') {
                    428: 		if ($temp eq 'opendate') {
                    429: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
                    430: 		}
                    431: 		if ($temp eq 'answerdate') {
                    432: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
                    433: 		}
1.145     albertel  434: 	    }
1.163     albertel  435: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
                    436: 	    if ($date eq '') {
                    437: 		$date = &mt("an unknown date"); $passed = 0;
                    438: 	    } elsif ($date eq 'con_lost') {
                    439: 		$date = &mt("an indeterminate date"); $passed = 0;
                    440: 	    } else {
                    441: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
1.274     www       442: 		$date = &Apache::lonlocal::locallocaltime($date);
1.145     albertel  443: 	    }
1.163     albertel  444: 	    if (!$passed) { $type=$temp; last; }
1.145     albertel  445: 	}
1.163     albertel  446: 	&Apache::lonxml::debug("have :$type:$passed:");
                    447: 	if ($passed) {
                    448: 	    $status='SHOW_ANSWER';
                    449: 	    $datemsg=$date;
                    450: 	} elsif ($type eq 'opendate') {
                    451: 	    $status='CLOSED';
                    452: 	    $datemsg = &mt("will open on")." $date";
                    453: 	} elsif ($type eq 'duedate') {
                    454: 	    $status='CAN_ANSWER';
                    455: 	    $datemsg = &mt("is due at")." $date";
                    456: 	} elsif ($type eq 'answerdate') {
                    457: 	    $status='CLOSED';
                    458: 	    $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
1.145     albertel  459: 	}
                    460:     }
1.212     albertel  461:     if ($status eq 'CAN_ANSWER' ||
                    462: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
1.145     albertel  463: 	#check #tries, and if correct.
                    464: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
                    465: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
                    466: 	if ( $tries eq '' ) { $tries = '0'; }
1.164     albertel  467: 	if ( $maxtries eq '' && 
1.204     albertel  468: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
1.164     albertel  469: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
1.145     albertel  470: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
                    471: 	if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
                    472: 	    &&
1.277     albertel  473: 	    &show_problem_status())
1.145     albertel  474: 	   ||
                    475: 	   $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
                    476: 	    $status = 'CANNOT_ANSWER';
                    477: 	}
1.285     albertel  478: 	if ($status eq 'CANNOT_ANSWER'
                    479: 	    && &show_answer_problem_status()) {
                    480: 	    $status = 'SHOW_ANSWER';
                    481: 	}
1.121     albertel  482:     }
1.181     albertel  483:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
1.286     albertel  484: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval");
                    485: 	&Apache::lonxml::debug("looking for interval @interval");
                    486: 	if ($interval[0]) {
                    487: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1]);
1.177     albertel  488: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
                    489: 	    if (!$first_access) {
                    490: 		$status='NOT_YET_VIEWED';
1.247     albertel  491: 		my $due_date = &due_date($id);
1.256     albertel  492: 		my $seconds_left = $due_date - time;
1.286     albertel  493: 		if ($seconds_left > $interval[0] || $due_date eq '') {
                    494: 		    $seconds_left = $interval[0];
1.256     albertel  495: 		}
                    496: 		$datemsg=&seconds_to_human_length($seconds_left);
1.177     albertel  497: 	    }
                    498: 	}
                    499:     }
1.247     albertel  500: 
1.133     albertel  501:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
                    502:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
                    503:   #    return ('UNCHECKEDOUT','needs to be checked out');
                    504:   #}
1.54      www       505: 
                    506: 
1.145     albertel  507:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
                    508:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
                    509: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
                    510: 	$status='CAN_ANSWER';
1.146     albertel  511: 	$datemsg=&mt('is closed but you are allowed to view it');
1.145     albertel  512:     }
1.106     albertel  513: 
1.145     albertel  514:     return ($status,$datemsg);
1.20      albertel  515: }
1.299     jms       516: 
                    517: 
                    518: =pod 
                    519: 
                    520: =item due_date()
                    521: 
                    522:     this should work exactly like the copy in lonnavmaps.pm
                    523: 
                    524: =cut
                    525: 
1.246     albertel  526: sub due_date {
1.250     albertel  527:     my ($part_id,$symb,$udom,$uname)=@_;
1.246     albertel  528:     my $date;
1.286     albertel  529:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
1.250     albertel  530: 				       $udom,$uname);
1.286     albertel  531:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
1.250     albertel  532:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
                    533: 				       $udom,$uname);
1.247     albertel  534:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
1.286     albertel  535:     if ($interval[0] =~ /\d+/) {
                    536: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
                    537: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
1.247     albertel  538: 	if (defined($first_access)) {
1.286     albertel  539: 	    my $interval = $first_access+$interval[0];
1.283     albertel  540: 	    $date = (!$due_date || $interval < $due_date) ? $interval
                    541:                                                           : $due_date;
1.247     albertel  542: 	} else {
                    543: 	    $date = $due_date;
                    544: 	}
                    545:     } else {
                    546: 	$date = $due_date;
1.246     albertel  547:     }
                    548:     return $date
                    549: }
                    550: 
1.192     albertel  551: sub seconds_to_human_length {
                    552:     my ($length)=@_;
                    553: 
                    554:     my $seconds=$length%60; $length=int($length/60);
                    555:     my $minutes=$length%60; $length=int($length/60);
                    556:     my $hours=$length%24;   $length=int($length/24);
                    557:     my $days=$length;
                    558: 
                    559:     my $timestr;
                    560:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
                    561:     if ($hours > 0) { $timestr.=($timestr?", ":"").
                    562: 			  &mt('[quant,_1,hour]',$hours); }
                    563:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
                    564: 			    &mt('[quant,_1,minute]',$minutes); }
                    565:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
                    566: 			    &mt('[quant,_1,second]',$seconds); }
                    567:     return $timestr;
                    568: }
                    569: 
1.41      albertel  570: sub showhash {
1.145     albertel  571:     my (%hash) = @_;
                    572:     &showhashsubset(\%hash,'.');
                    573:     return '';
1.79      albertel  574: }
                    575: 
1.106     albertel  576: sub showarray {
                    577:     my ($array)=@_;
                    578:     my $string="(";
                    579:     foreach my $elm (@{ $array }) {
1.193     albertel  580: 	if (ref($elm) eq 'ARRAY') {
                    581: 	    $string.=&showarray($elm);
                    582: 	} elsif (ref($elm) eq 'HASH') {
                    583: 	    $string.= "HASH --- \n<br />";
                    584: 	    $string.= &showhashsubset($elm,'.');
1.106     albertel  585: 	} else {
                    586: 	    $string.="$elm,"
                    587: 	}
                    588:     }
                    589:     chop($string);
                    590:     $string.=")";
                    591:     return $string;
                    592: }
                    593: 
1.79      albertel  594: sub showhashsubset {
1.145     albertel  595:     my ($hash,$keyre) = @_;
                    596:     my $resultkey;
                    597:     foreach $resultkey (sort keys %$hash) {
1.193     albertel  598: 	if ($resultkey !~ /$keyre/) { next; }
                    599: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
                    600: 	    &Apache::lonxml::debug("$resultkey ---- ".
                    601: 				   &showarray($$hash{$resultkey}));
                    602: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
                    603: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
                    604: 	    &showhashsubset($$hash{$resultkey},'.');
                    605: 	} else {
                    606: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
1.145     albertel  607: 	}
                    608:     }
                    609:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
                    610:     return '';
1.41      albertel  611: }
                    612: 
                    613: sub setuppermissions {
1.204     albertel  614:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
                    615:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
1.145     albertel  616:     if (! $viewgrades && 
1.204     albertel  617: 	exists($env{'request.course.sec'}) && 
                    618: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    619: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
                    620:                                                '/'.$env{'request.course.sec'});
1.145     albertel  621:     }
1.244     albertel  622:     $Apache::lonhomework::viewgrades = $viewgrades;
                    623: 
1.185     albertel  624:     if ($Apache::lonhomework::browse eq 'F' && 
1.204     albertel  625: 	$env{'form.devalidatecourseresdata'} eq 'on') {
1.261     albertel  626: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
1.204     albertel  627: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
                    628: 					      $env{"course.$courseid.domain"});
1.185     albertel  629:     }
1.244     albertel  630: 
1.205     albertel  631:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
                    632:     if (! $modifygrades && 
                    633: 	exists($env{'request.course.sec'}) && 
                    634: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    635: 	$modifygrades = 
                    636: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                    637: 				     '/'.$env{'request.course.sec'});
                    638:     }
                    639:     $Apache::lonhomework::modifygrades = $modifygrades;
1.244     albertel  640: 
                    641:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
                    642:     if (! $queuegrade && 
                    643: 	exists($env{'request.course.sec'}) && 
                    644: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    645: 	$queuegrade = 
                    646: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
                    647: 				     '/'.$env{'request.course.sec'});
                    648:     }
                    649:     $Apache::lonhomework::queuegrade = $queuegrade;
1.205     albertel  650:     return '';
1.41      albertel  651: }
                    652: 
1.253     albertel  653: sub unset_permissions {
                    654:     undef($Apache::lonhomework::queuegrade);
                    655:     undef($Apache::lonhomework::modifygrades);
                    656:     undef($Apache::lonhomework::viewgrades);
                    657:     undef($Apache::lonhomework::browse);
                    658: }
                    659: 
1.41      albertel  660: sub setupheader {
1.120     albertel  661:     my $request=$_[0];
1.197     albertel  662:     &Apache::loncommon::content_type($request,'text/html');
1.120     albertel  663:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
                    664: 	&Apache::loncommon::no_cache($request);
                    665:     }
1.196     albertel  666: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                    667: #							  'lastrevisiondate'));
1.120     albertel  668:     $request->send_http_header;
                    669:     return OK if $request->header_only;
                    670:     return ''
1.41      albertel  671: }
1.35      albertel  672: 
1.47      albertel  673: sub handle_save_or_undo {
1.145     albertel  674:     my ($request,$problem,$result) = @_;
                    675:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
                    676:     my $filebak =$file.".bak";
                    677:     my $filetmp =$file.".tmp";
                    678:     my $error=0;
1.204     albertel  679:     if ($env{'form.Undo'} eq &mt('undo')) {
1.145     albertel  680: 	my $error=0;
1.284     albertel  681: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
                    682: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
                    683: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
1.145     albertel  684: 	if (!$error) {
1.266     albertel  685: 	    &Apache::lonxml::info("<p><b>".
                    686: 				  &mt("Undid changes, Switched [_1] and [_2]",
                    687: 				      '<span class="LC_filename">'.$filebak.
                    688: 				      '</span>',
                    689: 				      '<span class="LC_filename">'.$file.
                    690: 				      '</span>')."</b></p>");
1.145     albertel  691: 	} else {
1.266     albertel  692: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
                    693: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
                    694: 				      '<span class="LC_filename">'.
                    695: 				      $filebak.'</span>',
                    696: 				      '<span class="LC_filename">'.
                    697: 				      $file.'</span>')."</span></p>");
1.145     albertel  698: 	    $error=1;
                    699: 	}
1.52      albertel  700:     } else {
1.262     banghart  701:         &Apache::lonnet::correct_line_ends($result);
1.145     albertel  702: 	my $fs=Apache::File->new(">$filebak");
                    703: 	if (defined($fs)) {
                    704: 	    print $fs $$problem;
                    705: 	} else {
1.266     albertel  706: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
                    707: 				  &mt("Unable to make backup [_1]",
                    708: 				      '<span class="LC_filename">'.
                    709: 				      $filebak.'</span>')."</span>");
1.145     albertel  710: 	    $error=2;
                    711: 	}
                    712: 	my $fh=Apache::File->new(">$file");
                    713: 	if (defined($fh)) {
                    714: 	    print $fh $$result;
                    715: 	} else {
1.266     albertel  716: 	    &Apache::lonxml::info('<span class="LC_error">'.
                    717: 				  &mt("Unable to write to [_1]",
                    718: 				      '<span class="LC_filename">'.
                    719: 				      $file.'</span>').
                    720: 				  '</span>');
1.145     albertel  721: 	    $error|=4;
                    722: 	}
1.52      albertel  723:     }
1.145     albertel  724:     return $error;
1.64      albertel  725: }
                    726: 
1.101     albertel  727: sub analyze_header {
                    728:     my ($request) = @_;
1.289     raeburn   729:     my $js = &Apache::structuretags::setmode_javascript();
1.238     albertel  730:     my $result =
1.289     raeburn   731: 	&Apache::loncommon::start_page('Analyzing a problem',$js);
1.240     albertel  732: 
1.238     albertel  733:     $result .= 
                    734: 	&Apache::lonxml::message_location().'
1.101     albertel  735:             <form name="lonhomework" method="POST" action="'.
1.204     albertel  736: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.289     raeburn   737:             '<input type="hidden" name="problemmode" value="'.
                    738:             $env{'form.problemmode'}.'" />'.
1.179     albertel  739: 	    &Apache::structuretags::remember_problem_state().'
1.278     albertel  740:             <div class="LC_edit_problem_analyze_header">
1.289     raeburn   741:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
                    742:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
                    743:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
                    744:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
1.278     albertel  745:             <hr class="LC_edit_problem_divide" />
1.289     raeburn   746:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
                    747:             'onclick="javascript:setmode(this.form,'."'view'".')" />
1.278     albertel  748:             <hr class="LC_edit_problem_divide" />
                    749:             </div>
1.101     albertel  750:             </form>';
1.171     albertel  751:     &Apache::lonxml::add_messages(\$result);
1.101     albertel  752:     $request->print($result);
                    753:     $request->rflush();
                    754: }
                    755: 
1.109     albertel  756: sub analyze_footer {
                    757:     my ($request) = @_;
1.237     albertel  758:     $request->print(&Apache::loncommon::end_page());
1.109     albertel  759:     $request->rflush();
                    760: }
                    761: 
1.74      albertel  762: sub analyze {
1.101     albertel  763:     my ($request,$file) = @_;
                    764:     &Apache::lonxml::debug("Analyze");
                    765:     my $result;
                    766:     my %overall;
1.219     www       767:     my %seedexample;
1.101     albertel  768:     my %allparts;
1.204     albertel  769:     my $rndseed=$env{'form.rndseed'};
1.101     albertel  770:     &analyze_header($request);
1.114     albertel  771:     my %prog_state=
1.146     albertel  772: 	&Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
                    773: 					      &mt('Getting Problem Variants'),
1.204     albertel  774: 					      $env{'form.numtoanalyze'},
1.175     albertel  775: 					      'inline',undef);
1.204     albertel  776:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
1.114     albertel  777: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
1.146     albertel  778: 						 &mt('last problem'));
1.182     albertel  779: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
1.219     www       780:         my $thisseed=$i+$rndseed;
1.101     albertel  781: 	my $subresult=&Apache::lonnet::ssi($request->uri,
                    782: 					   ('grade_target' => 'analyze'),
1.219     www       783: 					   ('rndseed' => $thisseed));
1.101     albertel  784: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    785: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.114     albertel  786: 	my @parts;
                    787: 	if (defined(@{ $analyze{'parts'} })) {
                    788: 	    @parts=@{ $analyze{'parts'} };
                    789: 	}
1.101     albertel  790: 	foreach my $part (@parts) {
                    791: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
1.109     albertel  792: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
                    793: 		$analyze{$part.'.type'} eq 'stringresponse'	||
                    794: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
1.263     albertel  795: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
                    796: 		    my $i=0;
                    797: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
                    798: 			push( @{ $overall{$part.'.answer'}[$i] },
                    799: 			      $answer_part);
                    800: 			my $concatanswer= join("\0",@{ $answer_part });
                    801: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
1.266     albertel  802: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
1.263     albertel  803: 			}
                    804: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
                    805: 			    $thisseed;
                    806: 			$i++;
                    807: 		    }
1.219     www       808: 		}
1.275     albertel  809: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
                    810: 		    my $answer_part = 
                    811: 			['<span class="LC_error">'.&mt('Error').'</span>'];
                    812: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
                    813: 			$thisseed;
                    814: 		    push( @{ $overall{$part.'.answer'}[0] },
                    815: 			  $answer_part);
                    816: 		}
1.101     albertel  817: 	    }
                    818: 	}
                    819:     }
1.114     albertel  820:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
1.146     albertel  821: 					  &mt('Analyzing Results'));
1.278     albertel  822:     $request->print('<hr class="LC_edit_problem_divide" />'.&mt('List of possible answers').': ');
1.134     albertel  823:     foreach my $part (sort(keys(%allparts))) {
1.109     albertel  824: 	if (defined(@{ $overall{$part.'.answer'} })) {
1.263     albertel  825: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
                    826: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
                    827: 		$request->print('<table class="thinborder"><tr><th colspan="'.($num_cols+1).'">'.&mt('Part').' '.$part);
                    828: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
                    829: 		    $request->print(&mt(' Answer [_1]',$i+1));
                    830: 		}
                    831: 		$request->print('</th></tr>');
                    832: 		my %frequency;
                    833: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
                    834: 		    $frequency{join("\0",@{ $answer })}++;
                    835: 		}
                    836: 		$request->print('<tr><th colspan="'.($num_cols).'">'.&mt('Answer').'</th><th>'.&mt('Frequency').'<br />('
                    837: 				.&mt('click for example').')</th></tr>');
                    838: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
                    839: 		    $request->print('<tr><td class="center">'.
                    840: 				    join('</td><td class="center">',split("\0",$answer)).
                    841: 				    '</td><td class="center"><a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.
                    842: 				    '</a></td></tr>');
                    843: 		}
                    844: 		$request->print('</table>');
1.109     albertel  845: 	    }
                    846: 	} else {
1.162     albertel  847: 	    $request->print('<p>'.&mt('Response').' '.$part.' '.
1.146     albertel  848: 			    &mt('is not analyzable at this time').'</p>');
1.101     albertel  849: 	}
                    850:     }
1.130     albertel  851:     if (scalar(keys(%allparts)) == 0 ) {
1.215     raeburn   852: 	$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  853:     }
1.114     albertel  854:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1.109     albertel  855:     &analyze_footer($request);
1.101     albertel  856:     &Apache::lonhomework::showhash(%overall);
                    857:     return $result;
1.74      albertel  858: }
                    859: 
1.277     albertel  860: {
                    861:     my $show_problem_status;
                    862:     sub reset_show_problem_status {
                    863: 	undef($show_problem_status);
                    864:     }
                    865: 
                    866:     sub set_show_problem_status {
                    867: 	my ($new_status) = @_;
                    868: 	$show_problem_status = lc($new_status);
                    869:     }
                    870: 
                    871:     sub hide_problem_status {
                    872: 	return ($show_problem_status eq 'no'
                    873: 		|| $show_problem_status eq 'no_feedback_ever');
                    874:     }
                    875: 
                    876:     sub show_problem_status {
                    877: 	return ($show_problem_status eq 'yes'
1.285     albertel  878: 		|| $show_problem_status eq 'answer'
1.277     albertel  879: 		|| $show_problem_status eq '');
                    880:     }
                    881:     
                    882:     sub show_some_problem_status {
                    883: 	return ($show_problem_status eq 'no');
                    884:     }
                    885: 
                    886:     sub show_no_problem_status {
                    887: 	return ($show_problem_status eq 'no_feedback_ever');
                    888:     }
1.285     albertel  889:   
                    890:     sub show_answer_problem_status {
                    891: 	return ($show_problem_status eq 'answer');
                    892:     }
1.277     albertel  893: }
                    894: 
1.64      albertel  895: sub editxmlmode {
1.145     albertel  896:     my ($request,$file) = @_;
                    897:     my $result;
                    898:     my $problem=&Apache::lonnet::getfile($file);
                    899:     if ($problem eq -1) {
1.146     albertel  900: 	&Apache::lonxml::error("<b> ".&mt('Unable to find').
                    901: 			       " <i>$file</i></b>");
1.145     albertel  902: 	$problem='';
                    903:     }
1.204     albertel  904:     if (defined($env{'form.editxmltext'}) || defined($env{'form.Undo'})) {
1.145     albertel  905: 	my $error=&handle_save_or_undo($request,\$problem,
1.204     albertel  906: 				       \$env{'form.editxmltext'});
1.145     albertel  907: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
                    908:     }
1.204     albertel  909:     &Apache::lonhomework::showhashsubset(\%env,'^form');
1.289     raeburn   910:     if ( $env{'form.submitbutton'} eq &mt('Save and View') ) {
1.204     albertel  911: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
1.289     raeburn   912: 	$env{'form.problemmode'}='view';
1.145     albertel  913: 	&renderpage($request,$file);
                    914:     } else {
                    915: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
1.160     www       916: 	my $xml_help = '<table><tr><td>'.
                    917: 	    &Apache::loncommon::helpLatexCheatsheet("Problem_Editor_XML_Index",
                    918: 						    "Problem Editing Help").
                    919: 						    '</td><td>'.
1.254     albertel  920:        &Apache::loncommon::help_open_menu(undef,undef,5,'Authoring').
1.178     albertel  921:                 '</td></tr></table>';
1.145     albertel  922: 	if ($cols > 80) { $cols = 80; }
                    923: 	if ($cols < 70) { $cols = 70; }
                    924: 	if ($rows < 20) { $rows = 20; }
1.269     albertel  925: 	my $js =
                    926: 	    &Apache::edit::js_change_detection(). 
1.289     raeburn   927: 	    &Apache::loncommon::resize_textarea_js().
1.296     raeburn   928:             &Apache::structuretags::setmode_javascript().
1.298     foxr      929:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
1.270     albertel  930: 	my $only_body =  ($env{'environment.remote'} eq 'off')? 0 : 1;
1.296     raeburn   931: 	my $dragmath_button = 
                    932:             &Apache::lonhtmlcommon::dragmath_button("LC_editxmltext",1);
1.238     albertel  933: 	my $start_page = 
1.269     albertel  934: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
                    935: 					   {'no_auto_mt_title' => 1,
1.270     albertel  936: 					    'only_body'        => $only_body,
1.269     albertel  937: 					    'add_entries'      => {
                    938: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
                    939: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
                    940: 				    }});
1.238     albertel  941: 	$result.=$start_page.
1.213     albertel  942: 	    &renderpage($request,$file,['no_output_web'],1).
1.281     albertel  943:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="POST" action="'.
1.204     albertel  944: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.179     albertel  945: 	    &Apache::structuretags::remember_problem_state().'
1.278     albertel  946:             <div class="LC_edit_problem_editxml_header">
1.280     albertel  947:               <table class="LC_edit_problem_header_title"><tr><td>
                    948:                '.&mt('Problem Editing').&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').'
                    949:                 </td><td align="right">
                    950:                   '.&Apache::loncommon::helpLatexCheatsheet().'
                    951:                 </td></tr>
                    952:               </table>
                    953:               <div class="LC_edit_problem_discards">
1.289     raeburn   954:                 <input type="hidden" name="problemmode" value="editxml" />
1.294     foxr      955: 
1.289     raeburn   956:                 <input type="button" name="submitmode" accesskey="d" value="'.&mt('Discard Edits and View').'" '.
                    957:                 'onclick="javascript:setmode(this.form,'."'discard'".')" />
                    958:                 <input type="button" '.&Apache::edit::submit_ask_anyway('setmode(this.form,'."'edit'".')').'name="submitmode" accesskey="e" value="'.&mt('Edit').'" />
1.280     albertel  959:                 <input type="submit" name="Undo" accesskey="u" value="'.&mt('undo').'" />
1.296     raeburn   960:                 '.$dragmath_button.'
1.280     albertel  961:               </div>
                    962:               <div class="LC_edit_problem_saves">
1.289     raeburn   963:                 <input type="submit" name="submitbutton" accesskey="s" value="'.&mt('Save').'"  />
1.296     raeburn   964:                 <input type="submit" name="submitbutton" accesskey="v" value="'.&mt('Save and View').'" />
1.280     albertel  965:               </div>
                    966:               <hr class="LC_edit_problem_divide" />
1.281     albertel  967: 	      '.&Apache::lonxml::message_location().'
1.278     albertel  968:             </div>
1.280     albertel  969:             '  . '
1.269     albertel  970:             <textarea '.&Apache::edit::element_change_detection().
                    971: 	              ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" '.
                    972: 		      ' name="editxmltext" id="LC_editxmltext">'.
                    973: 		      &HTML::Entities::encode($problem,'<>&"').'</textarea>
                    974:             <div id="LC_aftertextarea">
                    975:             </div>
1.238     albertel  976:             </form>'.&Apache::loncommon::end_page();
1.171     albertel  977: 	&Apache::lonxml::add_messages(\$result);
1.145     albertel  978: 	$request->print($result);
                    979:     }
                    980:     return '';
1.47      albertel  981: }
1.189     albertel  982: 
1.299     jms       983: =pod
                    984: 
                    985: =item renderpage()
                    986: 
                    987:     Render the page in whatever target desired.
                    988: 
                    989: =cut
                    990: 
1.41      albertel  991: sub renderpage {
1.213     albertel  992:     my ($request,$file,$targets,$return_string) = @_;
1.52      albertel  993: 
1.211     albertel  994:     my @targets = @{$targets || [&get_target()]};
1.204     albertel  995:     &Apache::lonhomework::showhashsubset(\%env,'form.');
1.145     albertel  996:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
1.268     albertel  997: 
1.171     albertel  998:     my $overall_result;
1.145     albertel  999:     foreach my $target (@targets) {
1.183     albertel 1000: 	# FIXME need to do something intelligent when a problem goes
                   1001:         # from viewable to not viewable due to map conditions
                   1002: 	#&setuppermissions();
                   1003: 	#if (   $Apache::lonhomework::browse ne '2'
                   1004: 	#    && $Apache::lonhomework::browse ne 'F' ) {
                   1005: 	#    $request->print(" You most likely shouldn't see me.");
                   1006: 	#}
1.145     albertel 1007: 	#my $t0 = [&gettimeofday()];
1.211     albertel 1008: 	my $output=1;
                   1009: 	if ($target eq 'no_output_web') {
                   1010: 	    $target = 'web'; $output=0;
                   1011: 	}
1.145     albertel 1012: 	my $problem=&Apache::lonnet::getfile($file);
1.222     albertel 1013: 	my $result;
1.145     albertel 1014: 	if ($problem eq -1) {
1.260     albertel 1015: 	    $problem='';
1.222     albertel 1016: 	    my $filename=(split('/',$file))[-1];
1.260     albertel 1017: 	    my $error =
                   1018: 		"<b> ".&mt('Unable to find [_1]',
                   1019: 			   ' <span class="LC_filename">'.$filename.'</span>')
                   1020: 		."</b>";
                   1021: 	    $result.=
                   1022: 		&Apache::loncommon::simple_error_page($request,'Not available',
                   1023: 						      $error);
                   1024: 	    return;
1.145     albertel 1025: 	}
1.52      albertel 1026: 
1.145     albertel 1027: 	my %mystyle;
                   1028: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
                   1029: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
1.204     albertel 1030: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
1.145     albertel 1031: 
                   1032: 	&Apache::lonxml::debug("Should be parsing now");
1.222     albertel 1033: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
                   1034: 					     &setup_vars($target),%mystyle);
1.273     albertel 1035: 	&finished_parsing();
1.214     albertel 1036: 	if (!$output) { $result = ''; }
1.145     albertel 1037: 	#$request->print("Result follows:");
                   1038: 	if ($target eq 'modified') {
                   1039: 	    &handle_save_or_undo($request,\$problem,\$result);
                   1040: 	} else {
                   1041: 	    if ($target eq 'analyze') {
                   1042: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
                   1043: 		undef(%Apache::lonhomework::analyze);
                   1044: 	    }
                   1045: 	    #my $td=&tv_interval($t0);
                   1046: 	    #if ( $Apache::lonxml::debug) {
                   1047: 	    #$result =~ s:</body>::;
                   1048: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
                   1049: 	    #}
1.171     albertel 1050: #	    $request->print($result);
                   1051: 	    $overall_result.=$result;
                   1052: #	    $request->rflush();
1.145     albertel 1053: 	}
                   1054: 	#$request->print(":Result ends");
                   1055: 	#my $td=&tv_interval($t0);
1.52      albertel 1056:     }
1.213     albertel 1057:     if (!$return_string) {
                   1058: 	&Apache::lonxml::add_messages(\$overall_result);
                   1059: 	$request->print($overall_result);   
                   1060: 	$request->rflush();   
                   1061:     } else {
                   1062: 	return $overall_result;
                   1063:     }
1.41      albertel 1064: }
                   1065: 
1.273     albertel 1066: sub finished_parsing {
                   1067:     undef($Apache::lonhomework::parsing_a_problem);
                   1068:     undef($Apache::lonhomework::parsing_a_task);
                   1069: }
                   1070: 
1.42      albertel 1071: sub get_template_list {
1.282     albertel 1072:     my ($extension) = @_;
1.145     albertel 1073:     my $result;
                   1074:     my @allnames;
                   1075:     &Apache::lonxml::debug("Looking for :$extension:");
1.282     albertel 1076:     my $glob_extension  = $extension;
                   1077:     if ($extension eq 'survey' || $extension eq 'exam') {
                   1078: 	$glob_extension = 'problem';
                   1079:     }
                   1080:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
                   1081: 		     '/templates/*.'.$glob_extension);
1.292     www      1082:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
                   1083:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
                   1084:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
                   1085:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
1.287     raeburn  1086:     my ($midpoint,$seconddiv,$numfiles);
                   1087:     $numfiles = 0;
                   1088:     foreach my $file (@files) {
                   1089:         next if ($file->[1] !~ /\S/);
                   1090:         $numfiles ++;
                   1091:     }
                   1092:     if ($numfiles > 0) {
                   1093:         $result = '<div class="LC_left_float">';
                   1094:         $midpoint = int($numfiles/2);
                   1095:         if ($numfiles%2) {
                   1096:             $midpoint ++;
                   1097:         }
                   1098:     }
                   1099:     my $count = 0;
1.292     www      1100:     my $currentcategory='';
1.282     albertel 1101:     foreach my $file (@files) {
                   1102: 	next if ($file->[1] !~ /\S/);
1.292     www      1103:         if ($file->[2] ne $currentcategory) {
                   1104:            $currentcategory=$file->[2];
                   1105:            if ((!$seconddiv) && ($count >= $midpoint)) {
                   1106:                $result .= '</div>'."\n".'<div class="LC_left_float">'."\n";
                   1107:                $seconddiv = 1;
                   1108:            }
                   1109:            $result.='<h3>'.$currentcategory.'</h3>';
1.293     www      1110:            $count++;
1.292     www      1111:         }
1.282     albertel 1112: 	$result .=
                   1113: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
1.292     www      1114: 	    $file->[1].'</label>';
                   1115:         if ($file->[3]) {
                   1116:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
                   1117:         }
                   1118:         my $filename=$file->[0];
                   1119:         $filename=~s/^\/home\/httpd\/html//;
                   1120:         $result.=' <font size="-2"><a href="'.$filename.'" target="sample">'.&mt('Example').'</font></a><br />'."\n";
1.287     raeburn  1121:         $count ++;
                   1122:     }
                   1123:     if ($numfiles > 0) {
                   1124:         $result .= '</div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
1.42      albertel 1125:     }
1.145     albertel 1126:     return $result;
1.42      albertel 1127: }
                   1128: 
                   1129: sub newproblem {
1.65      matthew  1130:     my ($request) = @_;
1.282     albertel 1131: 
                   1132:     if ($env{'form.template'}) {
                   1133: 	my $file = $env{'form.template'};
1.65      matthew  1134: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1135: 	&File::Copy::copy($file,$dest);
1.65      matthew  1136: 	&renderpage($request,$dest);
1.282     albertel 1137: 	return;
                   1138:     }
                   1139: 
                   1140:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
                   1141:     &Apache::lonxml::debug("Looking for :$extension:");
                   1142:     my $templatelist=&get_template_list($extension);
                   1143:     if ($env{'form.newfile'} && !$templatelist) {
                   1144: 	# no templates found
1.131     albertel 1145: 	my $templatefilename =
1.258     albertel 1146: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
1.131     albertel 1147: 	&Apache::lonxml::debug("$templatefilename");
                   1148: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1149: 	&File::Copy::copy($templatefilename,$dest);
1.131     albertel 1150: 	&renderpage($request,$dest);
1.85      albertel 1151:     } else {
1.176     albertel 1152: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
                   1153: 	my $shownurl=$url;	
1.157     albertel 1154: 	$shownurl=~s-^/~-/priv/-;
1.65      matthew  1155: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.128     albertel 1156: 	my $errormsg;
1.85      albertel 1157: 	my $instructions;
1.240     albertel 1158: 	my $start_page = 
                   1159: 	    &Apache::loncommon::start_page("Create New $extension");
1.258     albertel 1160: 	$request->print("
1.240     albertel 1161: $start_page
1.258     albertel 1162: <h1>".&mt("Creating a new $extension resource.")."</h1>
1.128     albertel 1163: $errormsg
1.258     albertel 1164: ".&mt("The requested file [_1] currently does not exist.",
                   1165:       "<tt>$shownurl</tt>")."
1.105     www      1166: <p>
1.258     albertel 1167: <b>
                   1168: ".&mt("To create a new $extension, select a template from the".
1.282     albertel 1169:       " list below. Then click on the \"Create $extension\" button.")."</b>
1.259     albertel 1170: </p><form action=\"$url\" method=\"POST\">");
1.258     albertel 1171: 
1.85      albertel 1172: 	if (defined($templatelist)) {
1.282     albertel 1173: 	    $request->print($templatelist);
1.85      albertel 1174: 	}
1.282     albertel 1175: 	$request->print('<br /><input type="submit" name="newfile" value="'.
                   1176: 			&mt("Create $extension").'" />');
1.238     albertel 1177: 	$request->print("</form></p>".&Apache::loncommon::end_page());
1.65      matthew  1178:     }
1.282     albertel 1179:     return;
1.42      albertel 1180: }
                   1181: 
1.268     albertel 1182: sub update_construct_style {
                   1183:     if ($env{'request.state'} eq "construct"
1.289     raeburn  1184: 	&& $env{'form.problemmode'} eq 'view' 
1.268     albertel 1185: 	&&  defined($env{'form.submitted'})
                   1186: 	&& !defined($env{'form.resetdata'})
                   1187: 	&& !defined($env{'form.newrandomization'})) {
                   1188: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
                   1189: 	    ||$env{'form.clear_style_file'}) {
                   1190: 	    &Apache::lonnet::delenv('construct\\.style');
                   1191: 	} elsif ($env{'form.style_file'} 
                   1192: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
1.291     raeburn  1193: 	    &Apache::lonnet::appenv({'construct.style' => 
                   1194: 				        $env{'form.style_file'}});
1.268     albertel 1195: 	}
                   1196:     }
                   1197: }
                   1198: 
                   1199: 
1.41      albertel 1200: sub handler {
1.145     albertel 1201:     #my $t0 = [&gettimeofday()];
                   1202:     my $request=$_[0];
1.223     albertel 1203:     $Apache::lonxml::request=$request;
1.204     albertel 1204:     $Apache::lonxml::debug=$env{'user.debug'};
                   1205:     $env{'request.uri'}=$request->uri;
1.180     albertel 1206:     &setuppermissions();
1.193     albertel 1207: 
1.145     albertel 1208:     my $file=&Apache::lonnet::filelocation("",$request->uri);
                   1209: 
                   1210:     #check if we know where we are
1.204     albertel 1211:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
1.145     albertel 1212: 	# if we are browsing we might not be able to know where we are
1.173     albertel 1213: 	if ($Apache::lonhomework::browse ne 'F' && 
1.204     albertel 1214: 	    $env{'request.state'} ne "construct") {
1.145     albertel 1215: 	    #should know where we are, so ask
1.253     albertel 1216: 	    &unset_permissions();
                   1217: 	    $request->internal_redirect('/adm/ambiguous');
                   1218: 	    return OK;
1.145     albertel 1219: 	}
                   1220:     }
1.253     albertel 1221:     if (&setupheader($request)) {
                   1222: 	&unset_permissions();
                   1223: 	return OK;
                   1224:     }
1.244     albertel 1225:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1.204     albertel 1226:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1.261     albertel 1227:     my ($symb) = &Apache::lonnet::whichuser();
1.145     albertel 1228:     &Apache::lonxml::debug('symb is '.$symb);
1.204     albertel 1229:     if ($env{'request.state'} eq "construct") {
1.145     albertel 1230: 	if ( -e $file ) {
                   1231: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1232: 						    ['problemmode']);
1.204     albertel 1233: 	    if (!(defined $env{'form.problemmode'})) {
1.145     albertel 1234: 		#first visit to problem in construction space
1.289     raeburn  1235: 		$env{'form.problemmode'}= 'view';
1.145     albertel 1236: 		&renderpage($request,$file);
1.289     raeburn  1237: 	    } elsif ($env{'form.problemmode'} eq 'editxml') {
1.145     albertel 1238: 		&editxmlmode($request,$file);
1.289     raeburn  1239: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
1.145     albertel 1240: 		&analyze($request,$file);
                   1241: 	    } else {
1.268     albertel 1242: 		&update_construct_style();
1.145     albertel 1243: 		&renderpage($request,$file);
                   1244: 	    }
                   1245: 	} else {
                   1246: 	    # requested file doesn't exist in contruction space
                   1247: 	    &newproblem($request);
                   1248: 	}
                   1249:     } else {
                   1250: 	# just render the page normally outside of construction space
                   1251: 	&Apache::lonxml::debug("not construct");
1.52      albertel 1252: 	&renderpage($request,$file);
1.41      albertel 1253:     }
1.145     albertel 1254:     #my $td=&tv_interval($t0);
                   1255:     #&Apache::lonxml::debug("Spent $td seconds processing");
                   1256:     # always turn off debug messages
                   1257:     $Apache::lonxml::debug=0;
1.253     albertel 1258:     &unset_permissions();
1.145     albertel 1259:     return OK;
1.52      albertel 1260: 
1.1       albertel 1261: }
                   1262: 
                   1263: 1;
                   1264: __END__

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