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

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

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