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

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

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