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

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

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