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

1.63      albertel    1: # The LearningOnline Network with CAPA
1.52      albertel    2: # The LON-CAPA Homework handler
1.63      albertel    3: #
1.359   ! musolffc    4: # $Id: lonhomework.pm,v 1.358 2015/10/05 02:35:40 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.321     www        50: use Apache::functionplotresponse();
1.169     albertel   51: use Apache::drawimage();
1.355     damieng    52: use Apache::loncapamath();
1.26      www        53: use Apache::Constants qw(:common);
1.83      albertel   54: use Apache::loncommon();
1.354     musolffc   55: use Apache::lonparmset();
1.146     albertel   56: use Apache::lonlocal;
1.179     albertel   57: use Time::HiRes qw( gettimeofday tv_interval );
1.282     albertel   58: use HTML::Entities();
                     59: use File::Copy();
1.188     foxr       60: 
1.189     albertel   61: # FIXME - improve commenting
1.188     foxr       62: 
1.43      albertel   63: 
1.69      harris41   64: BEGIN {
1.145     albertel   65:     &Apache::lonxml::register_insert();
1.43      albertel   66: }
                     67: 
1.188     foxr       68: 
1.276     foxr       69: =pod
                     70: 
                     71: =item set_bubble_lines()
                     72: 
                     73: Called at analysis time to set the bubble lines
                     74: hash for the problem.. This should be called in the
                     75: end_problemtype tag in analysis mode.
                     76: 
                     77: We fetch the hash of part id counters from lonxml
                     78:     and push them into analyze:{part_id.bubble_lines}.
                     79: 
                     80: =cut
                     81: 
                     82: sub set_bubble_lines {
                     83:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
                     84: 
                     85:     foreach my $key (keys(%bubble_counters)) {
                     86: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
                     87: 	    $bubble_counters{"$key"};
                     88:     }
                     89: }
                     90: 
1.301     jms        91: #
                     92: # Decides what targets to render for.
                     93: # Implicit inputs:
                     94: #   Various session environment variables:
                     95: #      request.state -  published  - is a /res/ resource
                     96: #                       uploaded   - is a /uploaded/ resource
                     97: #                       contruct   - is a /priv/ resource
                     98: #      form.grade_target - a form parameter requesting a specific target
1.5       albertel   99: sub get_target {
1.204     albertel  100:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
                    101:     if( defined($env{'form.grade_target'})) {
                    102: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
1.188     foxr      103:     } else {
1.189     albertel  104: 	&Apache::lonxml::debug("form.grade_target <undefined>");
1.188     foxr      105:     }
1.204     albertel  106:     if (($env{'request.state'} eq "published") ||
                    107: 	($env{'request.state'} eq "uploaded")) {
                    108: 	if ( defined($env{'form.grade_target'}  ) 
                    109: 	     && ($env{'form.grade_target'} eq 'tex')) {
                    110: 	    return ($env{'form.grade_target'});
                    111: 	} elsif ( defined($env{'form.grade_target'}  ) 
1.145     albertel  112: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
1.207     albertel  113: 	    return ($env{'form.grade_target'});
1.244     albertel  114: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
                    115: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
                    116: 	    return ($env{'form.grade_target'});
1.320     raeburn   117: 	} elsif ($env{'form.grade_target'} eq 'answer') {
                    118:             if ($env{'form.answer_output_mode'} eq 'tex') {
                    119:                 return ($env{'form.grade_target'});
                    120:             }
                    121:         }
1.207     albertel  122: 	if ($env{'form.webgrade'} &&
1.244     albertel  123: 	    ($Apache::lonhomework::modifygrades eq 'F'
                    124: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
1.207     albertel  125: 	    return ('grade','webgrade');
1.145     albertel  126: 	}
1.204     albertel  127: 	if ( defined($env{'form.submitted'}) &&
                    128: 	     ( !defined($env{'form.newrandomization'}))) {
1.217     albertel  129: 	    return ('grade', 'web');
1.145     albertel  130: 	} else {
1.217     albertel  131: 	    return ('web');
1.145     albertel  132: 	}
1.204     albertel  133:     } elsif ($env{'request.state'} eq "construct") {
1.323     www       134: #
                    135: # We are in construction space, editing and testing problems
                    136: #
1.204     albertel  137: 	if ( defined($env{'form.grade_target'}) ) {
                    138: 	    return ($env{'form.grade_target'});
1.145     albertel  139: 	}
1.204     albertel  140: 	if ( defined($env{'form.preview'})) {
                    141: 	    if ( defined($env{'form.submitted'})) {
1.323     www       142: #
                    143: # We are doing a problem preview
                    144: #
1.145     albertel  145: 		return ('grade', 'web');
                    146: 	    } else {
                    147: 		return ('web');
                    148: 	    }
                    149: 	} else {
1.267     albertel  150: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
                    151: 		return ('grade','webgrade','answer');
1.324     www       152:             } elsif ($env{'form.problemmode'} eq 'view') {
                    153:                 return ('grade','web','answer');
1.323     www       154: 	    } elsif ($env{'form.problemmode'} eq 'saveview') {
                    155:                 return ('modified','web','answer');
                    156:             } elsif ($env{'form.problemmode'} eq 'discard') {
                    157:                 return ('web','answer');
                    158:             } elsif (($env{'form.problemmode'} eq 'saveedit') ||
                    159:                      ($env{'form.problemmode'} eq 'undo')) {
                    160:                 return ('modified','no_output_web','edit');
                    161:             } elsif ($env{'form.problemmode'} eq 'edit') {
                    162: 		return ('no_output_web','edit');
1.145     albertel  163: 	    } else {
                    164: 		return ('web');
                    165: 	    }
1.323     www       166:         }
                    167: #
1.338     raeburn   168: # End of Authoring Space
1.323     www       169: #
1.15      albertel  170:     }
1.323     www       171: #
                    172: # Huh? We are nowhere, so do nothing.
                    173: #
1.145     albertel  174:     return ();
1.5       albertel  175: }
                    176: 
1.3       albertel  177: sub setup_vars {
1.145     albertel  178:     my ($target) = @_;
                    179:     return ';'
1.11      albertel  180: #  return ';$external::target='.$target.';';
1.2       albertel  181: }
                    182: 
1.200     albertel  183: sub proctor_checked_in {
1.226     albertel  184:     my ($slot_name,$slot,$type)=@_;
                    185:     my @possible_proctors=split(",",$slot->{'proctor'});
                    186:     
1.248     albertel  187:     return 1 if (!@possible_proctors);
                    188: 
1.226     albertel  189:     my $key;
                    190:     if ($type eq 'Task') {
1.230     albertel  191: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
                    192: 	$key ="resource.$version.0.checkedin";
1.226     albertel  193:     } elsif ($type eq 'problem') {
                    194: 	$key ='resource.0.checkedin';
                    195:     }
1.249     albertel  196:     # backward compatability, used to be username@domain, 
                    197:     # now is username:domain
                    198:     my $who = $Apache::lonhomework::history{$key};
                    199:     if ($who !~ /:/) {
                    200: 	$who =~ tr/@/:/;
                    201:     }     
1.226     albertel  202:     foreach my $possible (@possible_proctors) { 
1.249     albertel  203: 	if ($who eq $possible
1.226     albertel  204: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
1.202     albertel  205: 	    return 1;
                    206: 	}
                    207:     }
1.226     albertel  208:     
1.200     albertel  209:     return 0;
                    210: }
                    211: 
1.226     albertel  212: sub check_slot_access {
1.356     raeburn   213:     my ($id,$type,$symb)=@_;
1.226     albertel  214: 
1.207     albertel  215:     # does it pass normal muster
1.356     raeburn   216:     my ($status,$datemsg)=&check_access($id,$symb);
1.226     albertel  217:     
1.356     raeburn   218:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots",$symb);
1.251     albertel  219:     if ($useslots ne 'resource' && $useslots ne 'map' 
                    220: 	&& $useslots ne 'map_map') {
1.226     albertel  221: 	return ($status,$datemsg);
                    222:     }
                    223: 
1.358     raeburn   224:     my $checkin = 'resource.0.checkedin';
                    225:     my $version;
                    226:     if ($type eq 'Task') {
                    227:         $version=$Apache::lonhomework::history{'resource.version'};
                    228:         $checkin = "resource.$version.0.checkedin";
                    229:     }
                    230:     my $checkedin = $Apache::lonhomework::history{$checkin};
                    231:     my ($returned_slot,$slot_name,$checkinslot,$ipused,$blockip,$now,$ip);
                    232:     $now = time;
                    233:     $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                    234: 
                    235:     if ($checkedin) {
                    236:         $checkinslot = $Apache::lonhomework::history{"$checkin.slot"};
                    237:         my %slot=&Apache::lonnet::get_slot($checkinslot);
                    238:         if ($slot{'iptied'}) {
                    239:             $ipused = $Apache::lonhomework::history{"$checkin.ip"};
                    240:             unless (($ip ne '') && ($ipused eq $ip)) {
                    241:                 $blockip = $slot{'iptied'};
                    242:                 $slot_name = $checkinslot;
                    243:                 $returned_slot = \%slot;
                    244:             }
                    245:         }
                    246:     }
                    247: 
                    248:     if ($status eq 'SHOW_ANSWER') {
                    249:         if ($blockip eq 'answer') {
                    250:             return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
                    251:         } else {
                    252:             return ($status,$datemsg);
                    253:         }
                    254:     } 
                    255: 
                    256:     if ($status eq 'CLOSED' ||
1.200     albertel  257: 	$status eq 'INVALID_ACCESS' ||
                    258: 	$status eq 'UNAVAILABLE') {
                    259: 	return ($status,$datemsg);
                    260:     }
1.204     albertel  261:     if ($env{'request.state'} eq "construct") {
1.203     albertel  262: 	return ($status,$datemsg);
                    263:     }
1.226     albertel  264:     
                    265:     if ($type eq 'Task') {
1.358     raeburn   266: 	if ($checkedin &&
1.230     albertel  267: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
1.358     raeburn   268: 	    if ($blockip eq 'answer') {
                    269:                 return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
                    270:             } else {
                    271: 	        return ('SHOW_ANSWER');
                    272:             }
                    273:         }
1.207     albertel  274:     }
1.226     albertel  275: 
1.356     raeburn   276:     my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent",$symb);
                    277:     my $available = &Apache::lonnet::EXT("resource.0.available",$symb);
1.288     raeburn   278:     my @slots= (split(':',$availablestudent),split(':',$available));
1.210     albertel  279: 
1.200     albertel  280: #    if (!@slots) {
                    281: #	return ($status,$datemsg);
                    282: #    }
1.358     raeburn   283:     undef($returned_slot);
                    284:     undef($slot_name);
1.200     albertel  285:     my $slotstatus='NOT_IN_A_SLOT';
1.334     raeburn   286:     my $num_usable_slots = 0;
1.358     raeburn   287:     if (!$symb) {
                    288:         ($symb) = &Apache::lonnet::whichuser();
                    289:     }
1.210     albertel  290:     foreach my $slot (@slots) {
1.241     albertel  291: 	$slot =~ s/(^\s*|\s*$)//g;
1.201     albertel  292: 	&Apache::lonxml::debug("getting $slot");
1.200     albertel  293: 	my %slot=&Apache::lonnet::get_slot($slot);
1.201     albertel  294: 	&Apache::lonhomework::showhash(%slot);
1.334     raeburn   295:         next if ($slot{'endtime'} < $now);
                    296:         $num_usable_slots ++;
                    297: 	if ($slot{'starttime'} < $now &&
                    298: 	    $slot{'endtime'} > $now &&
1.297     raeburn   299: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
1.358     raeburn   300:             if ($slot{'iptied'}) {
                    301:                 if ($env{'request.course.id'}) {
                    302:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    303:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    304:                     if ($slot eq $checkinslot) {
                    305:                         if ($ip eq $ipused) {
                    306:                             &Apache::lonxml::debug("$slot is good");
                    307:                             $slotstatus ='NEEDS_CHECKIN'; 
                    308:                         } else {
                    309:                             $slotstatus = 'NEED_DIFFERENT_IP';
                    310:                             $slot_name = $slot;
                    311:                             $returned_slot = \%slot;
                    312:                             last;
                    313:                         }
                    314:                     } elsif ($ip) {
                    315:                         my $uniqkey = "$slot\0$symb\0$ip";
                    316:                         my %used_ip = &Apache::lonnet::get('slot_uniqueips',[$uniqkey],$cdom,$cnum);
                    317:                         if ($used_ip{$uniqkey}) {
                    318:                             $slotstatus = 'NEED_DIFFERENT_IP';
                    319:                         } else {
                    320:                             &Apache::lonxml::debug("$slot is good");
                    321:                             $slotstatus ='NEEDS_CHECKIN';
                    322:                         }
                    323:                     }
                    324:                 }
                    325:             } else {
                    326: 	        &Apache::lonxml::debug("$slot is good");
                    327: 	        $slotstatus='NEEDS_CHECKIN';
                    328:             }
                    329:             if ($slotstatus eq 'NEEDS_CHECKIN') {
                    330: 	        $returned_slot=\%slot;
                    331: 	        $slot_name=$slot;
                    332: 	        last;
                    333:             }
                    334:         }
1.200     albertel  335:     }
1.202     albertel  336:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
1.226     albertel  337: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
1.322     raeburn   338: 	&Apache::lonxml::debug("proctor checked in");
                    339: 	$slotstatus=$status;
1.200     albertel  340:     }
1.226     albertel  341: 
1.358     raeburn   342:     my ($is_correct,$got_grade);
1.226     albertel  343:     if ($type eq 'Task') {
1.230     albertel  344: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
1.231     albertel  345: 	$got_grade = 
                    346: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
                    347: 	     =~ /^(?:pass|fail)$/);
1.235     albertel  348: 	$is_correct =  
                    349: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
                    350: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
1.226     albertel  351:     } elsif ($type eq 'problem') {
1.252     albertel  352: 	$got_grade  = 1;
                    353: 	$is_correct =
                    354: 	    ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
1.226     albertel  355:     }
                    356:     
1.235     albertel  357:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
                    358:     
1.243     albertel  359:     # no slot is currently open, and has been checked in for this version
                    360:     # but hasn't got a grade, therefore must be awaiting a grade
                    361:     if (!defined($slot_name)
                    362: 	&& $checkedin 
1.236     albertel  363: 	&& !$got_grade) {
                    364: 	return ('WAITING_FOR_GRADE');
                    365:     }
                    366: 
1.309     raeburn   367:     # Previously used slot is no longer open, and has been checked in for this version.
                    368:     # However, the problem is not closed, and potentially, another slot might be
                    369:     # used to gain access to it to work on it, until the due date is reached, and the
                    370:     # problem then becomes CLOSED.  Therefore return the slotstatus - 
1.358     raeburn   371:     # (which will be one of: NOT_IN_A_SLOT, RESERVABLE, RESERVABLE_LATER, or NOTRESERVABLE).
1.334     raeburn   372:     if (!defined($slot_name) && $type eq 'problem') {
                    373:         if ($slotstatus eq 'NOT_IN_A_SLOT') {
                    374:             if (!$num_usable_slots) {
                    375:                 if ($env{'request.course.id'}) {
                    376:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    377:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.356     raeburn   378:                     unless ($symb) {
                    379:                         ($symb)=&Apache::lonnet::whichuser();
                    380:                     }
1.334     raeburn   381:                     $slotstatus = 'NOTRESERVABLE';
                    382:                     my ($reservable_now_order,$reservable_now,$reservable_future_order,
                    383:                         $reservable_future) = 
                    384:                         &Apache::loncommon::get_future_slots($cnum,$cdom,$now,$symb);
                    385:                     if ((ref($reservable_now_order) eq 'ARRAY') && (ref($reservable_now) eq 'HASH')) {
                    386:                         if (@{$reservable_now_order} > 0) {
                    387:                             $slotstatus = 'RESERVABLE';
                    388:                             $datemsg = $reservable_now->{$reservable_now_order->[-1]}{'endreserve'};
                    389:                         }
                    390:                     }
                    391:                     unless ($slotstatus eq 'RESERVABLE') {
                    392:                         if ((ref($reservable_future_order) eq 'ARRAY') && (ref($reservable_future) eq 'HASH')) {
                    393:                             if (@{$reservable_future_order} > 0) {
                    394:                                 $slotstatus = 'RESERVABLE_LATER';
                    395:                                 $datemsg = $reservable_future->{$reservable_future_order->[0]}{'startreserve'};
                    396:                             }
                    397:                         }
                    398:                     }
                    399:                 }
                    400:             }
                    401:         }
                    402:         return ($slotstatus,$datemsg);
1.252     albertel  403:     }
                    404: 
1.226     albertel  405:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
                    406: 	&& $checkedin ) {
                    407: 
1.231     albertel  408: 	if ($got_grade) {
1.358     raeburn   409:             if ($blockip eq 'answer') {
                    410:                 return ('NEED_DIFFERENT_IP','',$slot_name,$returned_slot,$ipused);
                    411:             } else {
                    412: 	        return ('SHOW_ANSWER');
                    413:             }
1.209     albertel  414: 	} else {
                    415: 	    return ('WAITING_FOR_GRADE');
                    416: 	}
1.226     albertel  417: 
1.207     albertel  418:     }
1.255     albertel  419: 
1.358     raeburn   420:     if (($is_correct) && ($blockip ne 'answer')) {
1.255     albertel  421: 	if ($type eq 'problem') {
                    422: 	    return ($status);
                    423: 	}
1.235     albertel  424: 	return ('SHOW_ANSWER');
                    425:     }
1.255     albertel  426: 
1.225     albertel  427:     if ( $status eq 'CANNOT_ANSWER' && 
1.358     raeburn   428: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT' &&
                    429:           $slotstatus ne 'NEED_DIFFERENT_IP') ) {
1.225     albertel  430: 	return ($status,$datemsg);
                    431:     }
1.358     raeburn   432:     return ($slotstatus,$datemsg,$slot_name,$returned_slot,$ipused);
1.198     albertel  433: }
1.200     albertel  434: 
1.301     jms       435: # JB, 9/24/2002: Any changes in this function may require a change
                    436: # in lonnavmaps::resource::getDateStatus.
1.53      www       437: sub check_access {
1.356     raeburn   438:     my ($id,$symb) = @_;
1.145     albertel  439:     my $date ='';
                    440:     my $status;
                    441:     my $datemsg = '';
                    442:     my $lastdate = '';
                    443:     my $type;
                    444:     my $passed;
                    445: 
1.204     albertel  446:     if ($env{'request.state'} eq "construct") {
                    447: 	if ($env{'form.problemstate'}) {
                    448: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
1.277     albertel  449: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
                    450: 			&& &hide_problem_status())) {
1.168     albertel  451: 		    return ('CANNOT_ANSWER',
1.174     www       452: 			    &mt('is in this state due to author settings.'));
1.167     albertel  453: 		}
1.165     albertel  454: 	    } else {
1.204     albertel  455: 		return ($env{'form.problemstate'},
1.174     www       456: 			&mt('is in this state due to author settings.'));
1.165     albertel  457: 	    }
                    458: 	}
1.145     albertel  459: 	&Apache::lonxml::debug("in construction ignoring dates");
                    460: 	$status='CAN_ANSWER';
1.146     albertel  461: 	$datemsg=&mt('is in under construction');
1.163     albertel  462: #	return ($status,$datemsg);
1.145     albertel  463:     }
                    464: 
                    465:     &Apache::lonxml::debug("checking for part :$id:");
                    466:     &Apache::lonxml::debug("time:".time);
1.152     albertel  467: 
1.356     raeburn   468:     unless ($symb) {
                    469:         ($symb)=&Apache::lonnet::whichuser();
                    470:     }
1.212     albertel  471:     &Apache::lonxml::debug("symb:".$symb);
                    472:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
1.204     albertel  473:     if ($env{'request.state'} ne "construct") {
1.356     raeburn   474:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc",$symb);
1.297     raeburn   475: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
1.163     albertel  476: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
                    477: 	    $status='INVALID_ACCESS';
                    478: 	    $date=&mt("can not be accessed from your location.");
1.145     albertel  479: 	    return($status,$date);
                    480: 	}
1.327     raeburn   481: 	if ($env{'form.grade_imsexport'}) {
                    482:             if (($env{'request.course.id'}) && 
                    483:                 (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
                    484:                 return ('SHOW_ANSWER');
                    485:             }
                    486:         }
1.226     albertel  487: 	foreach my $temp ("opendate","duedate","answerdate") {
1.163     albertel  488: 	    $lastdate = $date;
1.247     albertel  489: 	    if ($temp eq 'duedate') {
1.356     raeburn   490: 		$date = &due_date($id,$symb);
1.247     albertel  491: 	    } else {
1.356     raeburn   492: 		$date = &Apache::lonnet::EXT("resource.$id.$temp",$symb);
1.247     albertel  493: 	    }
                    494: 	    
1.356     raeburn   495: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type",$symb);
1.163     albertel  496: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
                    497: 		$date     =~ /^(con_lost|no_such_host)/) {
                    498: 		$status='UNAVAILABLE';
                    499: 		$date=&mt("may open later.");
                    500: 		return($status,$date);
                    501: 	    }
                    502: 	    if ($thistype eq 'date_interval') {
                    503: 		if ($temp eq 'opendate') {
1.356     raeburn   504: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)-$date;
1.163     albertel  505: 		}
                    506: 		if ($temp eq 'answerdate') {
1.356     raeburn   507: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)+$date;
1.163     albertel  508: 		}
1.145     albertel  509: 	    }
1.163     albertel  510: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
                    511: 	    if ($date eq '') {
                    512: 		$date = &mt("an unknown date"); $passed = 0;
                    513: 	    } elsif ($date eq 'con_lost') {
                    514: 		$date = &mt("an indeterminate date"); $passed = 0;
                    515: 	    } else {
                    516: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
1.274     www       517: 		$date = &Apache::lonlocal::locallocaltime($date);
1.145     albertel  518: 	    }
1.163     albertel  519: 	    if (!$passed) { $type=$temp; last; }
1.145     albertel  520: 	}
1.163     albertel  521: 	&Apache::lonxml::debug("have :$type:$passed:");
                    522: 	if ($passed) {
                    523: 	    $status='SHOW_ANSWER';
                    524: 	    $datemsg=$date;
                    525: 	} elsif ($type eq 'opendate') {
                    526: 	    $status='CLOSED';
1.343     bisitz    527: 	    $datemsg = &mt('will open on [_1]',$date);
1.163     albertel  528: 	} elsif ($type eq 'duedate') {
                    529: 	    $status='CAN_ANSWER';
1.343     bisitz    530: 	    $datemsg = &mt('is due at [_1]',$date);
1.163     albertel  531: 	} elsif ($type eq 'answerdate') {
                    532: 	    $status='CLOSED';
1.343     bisitz    533: 	    $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
                    534:                                $lastdate,$date);
1.145     albertel  535: 	}
                    536:     }
1.212     albertel  537:     if ($status eq 'CAN_ANSWER' ||
                    538: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
1.145     albertel  539: 	#check #tries, and if correct.
                    540: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
1.356     raeburn   541: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries",$symb);
1.145     albertel  542: 	if ( $tries eq '' ) { $tries = '0'; }
1.164     albertel  543: 	if ( $maxtries eq '' && 
1.204     albertel  544: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
1.164     albertel  545: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
1.145     albertel  546: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
1.331     raeburn   547: 	if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
                    548: 	      && (&show_problem_status()) ) {
1.333     raeburn   549:             if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
1.356     raeburn   550:                 (&Apache::lonnet::EXT("resource.$id.retrypartial",$symb) !~/^1|on|yes$/i)) {
1.331     raeburn   551: 	        $status = 'CANNOT_ANSWER';
                    552:             }
                    553:         } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
1.145     albertel  554: 	    $status = 'CANNOT_ANSWER';
                    555: 	}
1.285     albertel  556: 	if ($status eq 'CANNOT_ANSWER'
                    557: 	    && &show_answer_problem_status()) {
                    558: 	    $status = 'SHOW_ANSWER';
                    559: 	}
1.121     albertel  560:     }
1.181     albertel  561:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
1.356     raeburn   562: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval",$symb);
1.286     albertel  563: 	&Apache::lonxml::debug("looking for interval @interval");
                    564: 	if ($interval[0]) {
1.356     raeburn   565: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
1.177     albertel  566: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
                    567: 	    if (!$first_access) {
                    568: 		$status='NOT_YET_VIEWED';
1.356     raeburn   569: 		my $due_date = &due_date($id,$symb);
1.256     albertel  570: 		my $seconds_left = $due_date - time;
1.286     albertel  571: 		if ($seconds_left > $interval[0] || $due_date eq '') {
                    572: 		    $seconds_left = $interval[0];
1.256     albertel  573: 		}
                    574: 		$datemsg=&seconds_to_human_length($seconds_left);
1.177     albertel  575: 	    }
                    576: 	}
                    577:     }
1.247     albertel  578: 
1.133     albertel  579:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
                    580:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
                    581:   #    return ('UNCHECKEDOUT','needs to be checked out');
                    582:   #}
1.54      www       583: 
1.145     albertel  584:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
                    585:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
                    586: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
                    587: 	$status='CAN_ANSWER';
1.146     albertel  588: 	$datemsg=&mt('is closed but you are allowed to view it');
1.145     albertel  589:     }
1.106     albertel  590: 
1.145     albertel  591:     return ($status,$datemsg);
1.20      albertel  592: }
1.301     jms       593: # this should work exactly like the copy in lonnavmaps.pm
1.246     albertel  594: sub due_date {
1.250     albertel  595:     my ($part_id,$symb,$udom,$uname)=@_;
1.246     albertel  596:     my $date;
1.286     albertel  597:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
1.250     albertel  598: 				       $udom,$uname);
1.286     albertel  599:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
1.250     albertel  600:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
                    601: 				       $udom,$uname);
1.247     albertel  602:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
1.286     albertel  603:     if ($interval[0] =~ /\d+/) {
                    604: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
                    605: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
1.247     albertel  606: 	if (defined($first_access)) {
1.286     albertel  607: 	    my $interval = $first_access+$interval[0];
1.283     albertel  608: 	    $date = (!$due_date || $interval < $due_date) ? $interval
                    609:                                                           : $due_date;
1.247     albertel  610: 	} else {
                    611: 	    $date = $due_date;
                    612: 	}
                    613:     } else {
                    614: 	$date = $due_date;
1.246     albertel  615:     }
1.345     musolffc  616:     return $date;
1.246     albertel  617: }
                    618: 
1.192     albertel  619: sub seconds_to_human_length {
                    620:     my ($length)=@_;
                    621: 
                    622:     my $seconds=$length%60; $length=int($length/60);
                    623:     my $minutes=$length%60; $length=int($length/60);
                    624:     my $hours=$length%24;   $length=int($length/24);
                    625:     my $days=$length;
                    626: 
                    627:     my $timestr;
                    628:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
                    629:     if ($hours > 0) { $timestr.=($timestr?", ":"").
                    630: 			  &mt('[quant,_1,hour]',$hours); }
                    631:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
                    632: 			    &mt('[quant,_1,minute]',$minutes); }
                    633:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
                    634: 			    &mt('[quant,_1,second]',$seconds); }
                    635:     return $timestr;
                    636: }
                    637: 
1.41      albertel  638: sub showhash {
1.145     albertel  639:     my (%hash) = @_;
                    640:     &showhashsubset(\%hash,'.');
                    641:     return '';
1.79      albertel  642: }
                    643: 
1.106     albertel  644: sub showarray {
                    645:     my ($array)=@_;
                    646:     my $string="(";
                    647:     foreach my $elm (@{ $array }) {
1.193     albertel  648: 	if (ref($elm) eq 'ARRAY') {
                    649: 	    $string.=&showarray($elm);
                    650: 	} elsif (ref($elm) eq 'HASH') {
                    651: 	    $string.= "HASH --- \n<br />";
                    652: 	    $string.= &showhashsubset($elm,'.');
1.106     albertel  653: 	} else {
                    654: 	    $string.="$elm,"
                    655: 	}
                    656:     }
                    657:     chop($string);
                    658:     $string.=")";
                    659:     return $string;
                    660: }
                    661: 
1.79      albertel  662: sub showhashsubset {
1.145     albertel  663:     my ($hash,$keyre) = @_;
                    664:     my $resultkey;
1.346     raeburn   665:     foreach $resultkey (sort(keys(%$hash))) {
1.193     albertel  666: 	if ($resultkey !~ /$keyre/) { next; }
                    667: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
                    668: 	    &Apache::lonxml::debug("$resultkey ---- ".
                    669: 				   &showarray($$hash{$resultkey}));
                    670: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
                    671: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
                    672: 	    &showhashsubset($$hash{$resultkey},'.');
                    673: 	} else {
                    674: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
1.145     albertel  675: 	}
                    676:     }
                    677:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
                    678:     return '';
1.41      albertel  679: }
                    680: 
                    681: sub setuppermissions {
1.204     albertel  682:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
1.337     raeburn   683:     unless ($Apache::lonhomework::browse eq 'F') {
                    684:         $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'}); 
                    685:     }
1.204     albertel  686:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
1.145     albertel  687:     if (! $viewgrades && 
1.204     albertel  688: 	exists($env{'request.course.sec'}) && 
                    689: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    690: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
                    691:                                                '/'.$env{'request.course.sec'});
1.145     albertel  692:     }
1.244     albertel  693:     $Apache::lonhomework::viewgrades = $viewgrades;
                    694: 
1.185     albertel  695:     if ($Apache::lonhomework::browse eq 'F' && 
1.204     albertel  696: 	$env{'form.devalidatecourseresdata'} eq 'on') {
1.261     albertel  697: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
1.204     albertel  698: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
                    699: 					      $env{"course.$courseid.domain"});
1.185     albertel  700:     }
1.244     albertel  701: 
1.205     albertel  702:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
                    703:     if (! $modifygrades && 
                    704: 	exists($env{'request.course.sec'}) && 
                    705: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    706: 	$modifygrades = 
                    707: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                    708: 				     '/'.$env{'request.course.sec'});
                    709:     }
                    710:     $Apache::lonhomework::modifygrades = $modifygrades;
1.244     albertel  711: 
                    712:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
                    713:     if (! $queuegrade && 
                    714: 	exists($env{'request.course.sec'}) && 
                    715: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    716: 	$queuegrade = 
                    717: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
                    718: 				     '/'.$env{'request.course.sec'});
                    719:     }
                    720:     $Apache::lonhomework::queuegrade = $queuegrade;
1.205     albertel  721:     return '';
1.41      albertel  722: }
                    723: 
1.253     albertel  724: sub unset_permissions {
                    725:     undef($Apache::lonhomework::queuegrade);
                    726:     undef($Apache::lonhomework::modifygrades);
                    727:     undef($Apache::lonhomework::viewgrades);
                    728:     undef($Apache::lonhomework::browse);
                    729: }
                    730: 
1.41      albertel  731: sub setupheader {
1.120     albertel  732:     my $request=$_[0];
1.197     albertel  733:     &Apache::loncommon::content_type($request,'text/html');
1.120     albertel  734:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
                    735: 	&Apache::loncommon::no_cache($request);
                    736:     }
1.196     albertel  737: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                    738: #							  'lastrevisiondate'));
1.120     albertel  739:     $request->send_http_header;
                    740:     return OK if $request->header_only;
                    741:     return ''
1.41      albertel  742: }
1.35      albertel  743: 
1.47      albertel  744: sub handle_save_or_undo {
1.338     raeburn   745:     my ($request,$problem,$result,$getobjref) = @_;
1.323     www       746: 
1.145     albertel  747:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
                    748:     my $filebak =$file.".bak";
                    749:     my $filetmp =$file.".tmp";
                    750:     my $error=0;
1.323     www       751:     if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel  752: 	my $error=0;
1.284     albertel  753: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
                    754: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
                    755: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
1.145     albertel  756: 	if (!$error) {
1.266     albertel  757: 	    &Apache::lonxml::info("<p><b>".
                    758: 				  &mt("Undid changes, Switched [_1] and [_2]",
                    759: 				      '<span class="LC_filename">'.$filebak.
                    760: 				      '</span>',
                    761: 				      '<span class="LC_filename">'.$file.
                    762: 				      '</span>')."</b></p>");
1.145     albertel  763: 	} else {
1.266     albertel  764: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
                    765: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
                    766: 				      '<span class="LC_filename">'.
                    767: 				      $filebak.'</span>',
                    768: 				      '<span class="LC_filename">'.
                    769: 				      $file.'</span>')."</span></p>");
1.145     albertel  770: 	    $error=1;
                    771: 	}
1.52      albertel  772:     } else {
1.262     banghart  773:         &Apache::lonnet::correct_line_ends($result);
1.323     www       774: 
1.145     albertel  775: 	my $fs=Apache::File->new(">$filebak");
                    776: 	if (defined($fs)) {
                    777: 	    print $fs $$problem;
                    778: 	} else {
1.266     albertel  779: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
                    780: 				  &mt("Unable to make backup [_1]",
                    781: 				      '<span class="LC_filename">'.
                    782: 				      $filebak.'</span>')."</span>");
1.145     albertel  783: 	    $error=2;
                    784: 	}
                    785: 	my $fh=Apache::File->new(">$file");
                    786: 	if (defined($fh)) {
                    787: 	    print $fh $$result;
1.338     raeburn   788:             if (ref($getobjref) eq 'SCALAR') {
                    789:                 if ($file =~ m{([^/]+)\.(html?)$}) {
                    790:                     my $fname = $1;
                    791:                     my $ext = $2;
                    792:                     my $path = $file;
                    793:                     $path =~ s/\Q$fname\E\.\Q$ext\E$//; 
                    794:                     my (%allfiles,%codebase);
                    795:                     &Apache::lonnet::extract_embedded_items($file,\%allfiles,
                    796:                                                            \%codebase,$result);
                    797:                     if (keys(%allfiles) > 0) {
                    798:                         my $url = $request->uri;
                    799:                         my $state = <<STATE;
                    800:     <input type="hidden" name="action" value="upload_embedded" />
                    801:     <input type="hidden" name="url" value="$url" />
                    802: STATE
                    803:                         $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
                    804:                                       "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
                    805:                                       "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
                    806:                                       &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
                    807:                                       {'error_on_invalid_names'   => 1,
                    808:                                        'ignore_remote_references' => 1,});
                    809:                     }
                    810:                 }
                    811:             }
1.145     albertel  812: 	} else {
1.266     albertel  813: 	    &Apache::lonxml::info('<span class="LC_error">'.
                    814: 				  &mt("Unable to write to [_1]",
                    815: 				      '<span class="LC_filename">'.
                    816: 				      $file.'</span>').
                    817: 				  '</span>');
1.145     albertel  818: 	    $error|=4;
                    819: 	}
1.52      albertel  820:     }
1.145     albertel  821:     return $error;
1.64      albertel  822: }
                    823: 
1.101     albertel  824: sub analyze_header {
                    825:     my ($request) = @_;
1.289     raeburn   826:     my $js = &Apache::structuretags::setmode_javascript();
1.312     bisitz    827: 
                    828:     # Breadcrumbs
1.330     raeburn   829:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn   830:                    'text' => 'Authoring Space'},
1.312     bisitz    831:                   {'href' => '',
                    832:                    'text' => 'Problem Testing'},
                    833:                   {'href' => '',
                    834:                    'text' => 'Analyzing a problem'}];
                    835: 
1.238     albertel  836:     my $result =
1.312     bisitz    837:         &Apache::loncommon::start_page('Analyzing a problem',
                    838:                                        $js,
                    839:                                        {'bread_crumbs' => $brcrum,})
1.311     bisitz    840:        .&Apache::loncommon::head_subbox(
                    841:                 &Apache::loncommon::CSTR_pageheader());
1.238     albertel  842:     $result .= 
1.347     golterma  843: 	    '<form name="lonhomework" method="post" action="'.
1.204     albertel  844: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.289     raeburn   845:             '<input type="hidden" name="problemmode" value="'.
                    846:             $env{'form.problemmode'}.'" />'.
1.179     albertel  847: 	    &Apache::structuretags::remember_problem_state().'
1.278     albertel  848:             <div class="LC_edit_problem_analyze_header">
1.289     raeburn   849:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
                    850:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
                    851:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
                    852:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
1.313     bisitz    853:             <hr />
1.289     raeburn   854:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
                    855:             'onclick="javascript:setmode(this.form,'."'view'".')" />
1.313     bisitz    856:             <hr />
1.347     golterma  857:             </div>'
                    858:             .&Apache::lonxml::message_location().
                    859:             '</form>';
1.171     albertel  860:     &Apache::lonxml::add_messages(\$result);
1.101     albertel  861:     $request->print($result);
                    862:     $request->rflush();
                    863: }
                    864: 
1.109     albertel  865: sub analyze_footer {
                    866:     my ($request) = @_;
1.237     albertel  867:     $request->print(&Apache::loncommon::end_page());
1.109     albertel  868:     $request->rflush();
                    869: }
                    870: 
1.74      albertel  871: sub analyze {
1.101     albertel  872:     my ($request,$file) = @_;
                    873:     &Apache::lonxml::debug("Analyze");
                    874:     my $result;
                    875:     my %overall;
1.219     www       876:     my %seedexample;
1.101     albertel  877:     my %allparts;
1.204     albertel  878:     my $rndseed=$env{'form.rndseed'};
1.101     albertel  879:     &analyze_header($request);
1.114     albertel  880:     my %prog_state=
1.335     www       881: 	&Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
1.204     albertel  882:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
1.335     www       883: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
1.182     albertel  884: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
1.219     www       885:         my $thisseed=$i+$rndseed;
1.101     albertel  886: 	my $subresult=&Apache::lonnet::ssi($request->uri,
                    887: 					   ('grade_target' => 'analyze'),
1.219     www       888: 					   ('rndseed' => $thisseed));
1.101     albertel  889: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    890: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.114     albertel  891: 	my @parts;
1.336     raeburn   892:         if (ref($analyze{'parts'}) eq 'ARRAY') {
1.114     albertel  893: 	    @parts=@{ $analyze{'parts'} };
                    894: 	}
1.101     albertel  895: 	foreach my $part (@parts) {
                    896: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
1.109     albertel  897: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
                    898: 		$analyze{$part.'.type'} eq 'stringresponse'	||
                    899: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
1.263     albertel  900: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
                    901: 		    my $i=0;
                    902: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
                    903: 			push( @{ $overall{$part.'.answer'}[$i] },
                    904: 			      $answer_part);
                    905: 			my $concatanswer= join("\0",@{ $answer_part });
                    906: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
1.266     albertel  907: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
1.263     albertel  908: 			}
                    909: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
                    910: 			    $thisseed;
                    911: 			$i++;
                    912: 		    }
1.219     www       913: 		}
1.275     albertel  914: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
                    915: 		    my $answer_part = 
                    916: 			['<span class="LC_error">'.&mt('Error').'</span>'];
                    917: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
                    918: 			$thisseed;
                    919: 		    push( @{ $overall{$part.'.answer'}[0] },
                    920: 			  $answer_part);
                    921: 		}
1.101     albertel  922: 	    }
                    923: 	}
                    924:     }
1.335     www       925:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
1.313     bisitz    926:     $request->print('<hr />'
1.308     bisitz    927:                    .'<h3>'
                    928:                    .&mt('List of possible answers')
                    929:                    .'</h3>'
                    930:     );
1.134     albertel  931:     foreach my $part (sort(keys(%allparts))) {
1.336     raeburn   932:         if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
                    933:             (@{$overall{$part.'.answer'}} > 0)) {
1.263     albertel  934: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
                    935: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
1.308     bisitz    936:                 $request->print(&Apache::loncommon::start_data_table()
                    937:                                .&Apache::loncommon::start_data_table_header_row()
                    938:                                .'<th colspan="'.($num_cols+1).'">'
                    939:                                .&mt('Part').' '.$part
                    940:                 );
1.263     albertel  941: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
1.308     bisitz    942: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
1.263     albertel  943: 		}
1.308     bisitz    944: 		$request->print('</th>'
                    945:                                .&Apache::loncommon::end_data_table_header_row()
                    946:                 );
1.263     albertel  947: 		my %frequency;
                    948: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
                    949: 		    $frequency{join("\0",@{ $answer })}++;
                    950: 		}
1.308     bisitz    951:                 $request->print(&Apache::loncommon::start_data_table_header_row()
                    952:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
                    953:                                .'<th>'.&mt('Frequency').'<br />'
                    954:                                .'('.&mt('click for example').')</th>'
                    955:                                .&Apache::loncommon::end_data_table_header_row()
                    956:                 );
1.263     albertel  957: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
1.308     bisitz    958:                     $request->print(&Apache::loncommon::start_data_table_row()
                    959:                                    .'<td>'
                    960:                                    .join('</td><td>',split("\0",$answer))
                    961: 				   .'</td>'
                    962:                                    .'<td>'
                    963:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
                    964: 				   .'</td>'
                    965:                                    .&Apache::loncommon::end_data_table_row()
                    966:                     );
1.263     albertel  967: 		}
1.308     bisitz    968:                 $request->print(&Apache::loncommon::end_data_table());
1.109     albertel  969: 	    }
                    970: 	} else {
1.307     bisitz    971:             $request->print('<p class="LC_warning">'
                    972:                            .&mt('Response [_1] is not analyzable at this time.',$part)
                    973: 			   .'</p>'
                    974:             );
1.101     albertel  975: 	}
                    976:     }
1.130     albertel  977:     if (scalar(keys(%allparts)) == 0 ) {
1.307     bisitz    978:         $request->print('<p class="LC_warning">'
                    979:                        .&mt('Found no analyzable responses in this problem.'
                    980:                            .' Currently only Numerical, Formula and String response styles are supported.')
                    981:                        .'</p>'
                    982:         );
1.130     albertel  983:     }
1.114     albertel  984:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1.109     albertel  985:     &analyze_footer($request);
1.101     albertel  986:     &Apache::lonhomework::showhash(%overall);
                    987:     return $result;
1.74      albertel  988: }
                    989: 
1.277     albertel  990: {
                    991:     my $show_problem_status;
                    992:     sub reset_show_problem_status {
                    993: 	undef($show_problem_status);
                    994:     }
                    995: 
                    996:     sub set_show_problem_status {
                    997: 	my ($new_status) = @_;
                    998: 	$show_problem_status = lc($new_status);
                    999:     }
                   1000: 
                   1001:     sub hide_problem_status {
                   1002: 	return ($show_problem_status eq 'no'
                   1003: 		|| $show_problem_status eq 'no_feedback_ever');
                   1004:     }
                   1005: 
                   1006:     sub show_problem_status {
                   1007: 	return ($show_problem_status eq 'yes'
1.285     albertel 1008: 		|| $show_problem_status eq 'answer'
1.277     albertel 1009: 		|| $show_problem_status eq '');
                   1010:     }
                   1011:     
                   1012:     sub show_some_problem_status {
                   1013: 	return ($show_problem_status eq 'no');
                   1014:     }
                   1015: 
                   1016:     sub show_no_problem_status {
                   1017: 	return ($show_problem_status eq 'no_feedback_ever');
                   1018:     }
1.285     albertel 1019:   
                   1020:     sub show_answer_problem_status {
                   1021: 	return ($show_problem_status eq 'answer');
                   1022:     }
1.277     albertel 1023: }
                   1024: 
1.64      albertel 1025: sub editxmlmode {
1.145     albertel 1026:     my ($request,$file) = @_;
                   1027:     my $result;
                   1028:     my $problem=&Apache::lonnet::getfile($file);
                   1029:     if ($problem eq -1) {
1.305     bisitz   1030: 	&Apache::lonxml::error(
1.328     bisitz   1031:             '<p class="LC_error">'
1.305     bisitz   1032:            .&mt('Unable to find [_1]',
                   1033:                 '<span class="LC_filename">'.$file.'</span>')
1.328     bisitz   1034:            .'</p>');
1.305     bisitz   1035: 
1.145     albertel 1036: 	$problem='';
                   1037:     }
1.323     www      1038:     if (($env{'form.problemmode'} eq 'saveeditxml') ||
1.347     golterma 1039:         ($env{'form.problemmode'} eq 'saveviewxml') ||
1.323     www      1040:         ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel 1041: 	my $error=&handle_save_or_undo($request,\$problem,
1.204     albertel 1042: 				       \$env{'form.editxmltext'});
1.145     albertel 1043: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
                   1044:     }
1.204     albertel 1045:     &Apache::lonhomework::showhashsubset(\%env,'^form');
1.323     www      1046:     if ($env{'form.problemmode'} eq 'saveviewxml') {
1.204     albertel 1047: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
1.289     raeburn  1048: 	$env{'form.problemmode'}='view';
1.145     albertel 1049: 	&renderpage($request,$file);
                   1050:     } else {
                   1051: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
                   1052: 	if ($cols > 80) { $cols = 80; }
                   1053: 	if ($cols < 70) { $cols = 70; }
                   1054: 	if ($rows < 20) { $rows = 20; }
1.269     albertel 1055: 	my $js =
                   1056: 	    &Apache::edit::js_change_detection(). 
1.289     raeburn  1057: 	    &Apache::loncommon::resize_textarea_js().
1.296     raeburn  1058:             &Apache::structuretags::setmode_javascript().
1.298     foxr     1059:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
1.312     bisitz   1060: 
                   1061:     # Breadcrumbs
1.330     raeburn  1062:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn  1063:                    'text' => 'Authoring Space'},
1.312     bisitz   1064:                   {'href' => '',
                   1065:                    'text' => 'Problem Editing'}];
                   1066: 
1.238     albertel 1067: 	my $start_page = 
1.269     albertel 1068: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
                   1069: 					   {'no_auto_mt_title' => 1,
1.318     droeschl 1070: 					    'only_body'        => 0,
1.269     albertel 1071: 					    'add_entries'      => {
                   1072: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
                   1073: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1.323     www      1074:                                                                   },
1.312     bisitz   1075:                                                 'bread_crumbs' => $brcrum,
1.323     www      1076:                                              });
1.311     bisitz   1077: 
                   1078:     $result=$start_page
                   1079:            .&Apache::loncommon::head_subbox(
                   1080:                 &Apache::loncommon::CSTR_pageheader());
                   1081: 	$result.=&renderpage($request,$file,['no_output_web'],1).
1.310     bisitz   1082:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
1.204     albertel 1083: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.179     albertel 1084: 	    &Apache::structuretags::remember_problem_state().'
1.347     golterma 1085:             <div class="LC_edit_problem_header">
                   1086:               <div class="LC_edit_problem_header_title">'.
                   1087:                 &mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').
                   1088:               '</div><div class="LC_edit_actionbar" id="actionbar">';
                   1089: 
1.352     droeschl 1090:     $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
1.348     droeschl 1091:                   &Apache::structuretags::problem_edit_buttons('editxml');
1.352     droeschl 1092:     $result.='<div>';
1.347     golterma 1093: 
1.352     droeschl 1094:     $result .= '<ol class="LC_primary_menu" style="display:inline-block;font-size:90%;vertical-align:middle;">';
                   1095: 
                   1096:     unless ($env{'environment.nocodemirror'}) {
                   1097:         # dropdown menus
                   1098:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1099:             &mt("Problem Templates"), template_dropdown_datastructure());
                   1100: 
                   1101:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1102:             &mt("Response Types"), responseblock_dropdown_datastructure());
                   1103: 
                   1104:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1105:             &mt("Conditional Blocks"), conditional_scripting_datastructure());
                   1106: 
                   1107:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1108:             &mt("Miscellaneous"), misc_datastructure());
                   1109:     }
1.351     droeschl 1110: 
                   1111:     $result .= Apache::lonmenu::create_submenu("#", "", 
                   1112:         &mt("Help") . ' <img src="/adm/help/help.png" alt="' . &mt("Help") .
                   1113:         '" style="vertical-align:text-bottom; height: auto; margin:0; "/>', 
1.352     droeschl 1114:         helpmenu_datastructure(),"");
1.351     droeschl 1115: 
                   1116:     $result.="</ol></div>";
1.323     www      1117:          
1.352     droeschl 1118:     $result .= '</div></div>' . 
                   1119:         &Apache::lonxml::message_location() .
                   1120:         &Apache::loncommon::xmleditor_js() .
                   1121:         '<textarea ' . &Apache::edit::element_change_detection() .
                   1122:         ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" ' .
                   1123:         ' name="editxmltext" id="LC_editxmltext">' .
                   1124:         &HTML::Entities::encode($problem,'<>&"') .
                   1125:         '</textarea> <div id="LC_aftertextarea"> </div> </form>';
                   1126: 
                   1127:     my $resource = $env{'request.ambiguous'};
                   1128:     unless($env{'environment.nocodemirror'}){
                   1129:         $result .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined-xml.css">
                   1130:         <script src="/adm/codemirror/codemirror-compressed-xml.js"></script>
                   1131:         <script>
                   1132:             CodeMirror.defineMode("mixedmode", function(config) {
                   1133:                 return CodeMirror.multiplexingMode(
                   1134:                     CodeMirror.getMode(config, "xml"),
                   1135:                     {
                   1136:                         open: "\<script type=\"loncapa/perl\"\>", close: "\</script\>",
                   1137:                         mode: CodeMirror.getMode(config, "perl"),
                   1138:                         delimStyle: "tag",
                   1139:                     }
                   1140:               );
                   1141:             });
                   1142:             var cm = CodeMirror.fromTextArea(document.getElementById("LC_editxmltext"),
                   1143:             {
                   1144:                 mode: "mixedmode",
                   1145:                 lineWrapping: true,
                   1146:                 lineNumbers: true,
                   1147:                 tabSize: 4,
                   1148:                 indentUnit: 4,
                   1149: 
                   1150:                 autoCloseTags: true,
                   1151:                 autoCloseBrackets: true,
                   1152:                 height: "auto",
                   1153:                 styleActiveLine: true,
                   1154:                 
                   1155:                 extraKeys: {
                   1156:                     "Tab": "indentMore",
                   1157:                     "Shift-Tab": "indentLess",
                   1158:                 }
                   1159:             });
                   1160:             restoreScrollPosition("'.$resource.'");
                   1161:         </script>';
                   1162:     }
                   1163: 
                   1164:     $result .= &Apache::loncommon::end_page();
                   1165:     &Apache::lonxml::add_messages(\$result);
                   1166:     $request->print($result);
1.145     albertel 1167:     }
                   1168:     return '';
1.47      albertel 1169: }
1.189     albertel 1170: 
1.301     jms      1171: #
                   1172: #    Render the page in whatever target desired.
                   1173: #
1.41      albertel 1174: sub renderpage {
1.213     albertel 1175:     my ($request,$file,$targets,$return_string) = @_;
1.52      albertel 1176: 
1.211     albertel 1177:     my @targets = @{$targets || [&get_target()]};
1.204     albertel 1178:     &Apache::lonhomework::showhashsubset(\%env,'form.');
1.145     albertel 1179:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
1.268     albertel 1180: 
1.171     albertel 1181:     my $overall_result;
1.145     albertel 1182:     foreach my $target (@targets) {
1.183     albertel 1183: 	# FIXME need to do something intelligent when a problem goes
                   1184:         # from viewable to not viewable due to map conditions
                   1185: 	#&setuppermissions();
                   1186: 	#if (   $Apache::lonhomework::browse ne '2'
                   1187: 	#    && $Apache::lonhomework::browse ne 'F' ) {
                   1188: 	#    $request->print(" You most likely shouldn't see me.");
                   1189: 	#}
1.145     albertel 1190: 	#my $t0 = [&gettimeofday()];
1.211     albertel 1191: 	my $output=1;
                   1192: 	if ($target eq 'no_output_web') {
                   1193: 	    $target = 'web'; $output=0;
                   1194: 	}
1.145     albertel 1195: 	my $problem=&Apache::lonnet::getfile($file);
1.222     albertel 1196: 	my $result;
1.145     albertel 1197: 	if ($problem eq -1) {
1.260     albertel 1198: 	    $problem='';
1.222     albertel 1199: 	    my $filename=(split('/',$file))[-1];
1.260     albertel 1200: 	    my $error =
1.347     golterma 1201: 		'<p class="LC_error">'
                   1202:                .&mt('Unable to find [_1]',
                   1203: 			   '<span class="LC_filename">'.$filename.'</span>')
                   1204: 		."</p>";
1.260     albertel 1205: 	    $result.=
                   1206: 		&Apache::loncommon::simple_error_page($request,'Not available',
1.340     bisitz   1207: 						      $error,{'no_auto_mt_msg' => 1});
1.260     albertel 1208: 	    return;
1.145     albertel 1209: 	}
1.52      albertel 1210: 
1.145     albertel 1211: 	my %mystyle;
                   1212: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
                   1213: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
1.204     albertel 1214: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
1.145     albertel 1215: 
                   1216: 	&Apache::lonxml::debug("Should be parsing now");
1.222     albertel 1217: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
                   1218: 					     &setup_vars($target),%mystyle);
1.273     albertel 1219: 	&finished_parsing();
1.214     albertel 1220: 	if (!$output) { $result = ''; }
1.145     albertel 1221: 	#$request->print("Result follows:");
                   1222: 	if ($target eq 'modified') {
                   1223: 	    &handle_save_or_undo($request,\$problem,\$result);
                   1224: 	} else {
                   1225: 	    if ($target eq 'analyze') {
                   1226: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
                   1227: 		undef(%Apache::lonhomework::analyze);
                   1228: 	    }
                   1229: 	    #my $td=&tv_interval($t0);
                   1230: 	    #if ( $Apache::lonxml::debug) {
                   1231: 	    #$result =~ s:</body>::;
                   1232: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
                   1233: 	    #}
1.171     albertel 1234: #	    $request->print($result);
                   1235: 	    $overall_result.=$result;
                   1236: #	    $request->rflush();
1.145     albertel 1237: 	}
                   1238: 	#$request->print(":Result ends");
                   1239: 	#my $td=&tv_interval($t0);
1.52      albertel 1240:     }
1.213     albertel 1241:     if (!$return_string) {
                   1242: 	&Apache::lonxml::add_messages(\$overall_result);
                   1243: 	$request->print($overall_result);   
                   1244: 	$request->rflush();   
                   1245:     } else {
                   1246: 	return $overall_result;
                   1247:     }
1.41      albertel 1248: }
                   1249: 
1.273     albertel 1250: sub finished_parsing {
                   1251:     undef($Apache::lonhomework::parsing_a_problem);
                   1252:     undef($Apache::lonhomework::parsing_a_task);
                   1253: }
                   1254: 
1.347     golterma 1255: # function extracted from get_template_html
                   1256: # returns "key" -> list
                   1257: # key: path of template
                   1258: # value 1: title
                   1259: # value 2: category
                   1260: # value 3: name of help topic ???
                   1261: sub get_template_list{
                   1262:     my ($extension) = @_;
                   1263:     
                   1264:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
                   1265:                      '/templates/*.'.$extension);
                   1266:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
                   1267:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
                   1268:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
                   1269:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
                   1270:     return @files;
                   1271: }
                   1272: 
                   1273: sub get_template_html {
1.282     albertel 1274:     my ($extension) = @_;
1.145     albertel 1275:     my $result;
                   1276:     my @allnames;
                   1277:     &Apache::lonxml::debug("Looking for :$extension:");
1.282     albertel 1278:     my $glob_extension  = $extension;
                   1279:     if ($extension eq 'survey' || $extension eq 'exam') {
                   1280: 	$glob_extension = 'problem';
                   1281:     }
1.347     golterma 1282:     my @files = &get_template_list($extension);
1.287     raeburn  1283:     my ($midpoint,$seconddiv,$numfiles);
1.341     bisitz   1284:     my @noexamplelink = ('blank.problem','blank.library','script.library');
1.287     raeburn  1285:     $numfiles = 0;
                   1286:     foreach my $file (@files) {
                   1287:         next if ($file->[1] !~ /\S/);
                   1288:         $numfiles ++;
                   1289:     }
                   1290:     if ($numfiles > 0) {
                   1291:         $result = '<div class="LC_left_float">';
                   1292:         $midpoint = int($numfiles/2);
                   1293:         if ($numfiles%2) {
                   1294:             $midpoint ++;
                   1295:         }
                   1296:     }
                   1297:     my $count = 0;
1.292     www      1298:     my $currentcategory='';
1.314     bisitz   1299:     my $first = 1;
1.329     raeburn  1300:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.282     albertel 1301:     foreach my $file (@files) {
                   1302: 	next if ($file->[1] !~ /\S/);
1.292     www      1303:         if ($file->[2] ne $currentcategory) {
                   1304:            $currentcategory=$file->[2];
                   1305:            if ((!$seconddiv) && ($count >= $midpoint)) {
1.314     bisitz   1306:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
1.292     www      1307:                $seconddiv = 1;
1.314     bisitz   1308:            } elsif (!$first) {
                   1309:                $result.='</div>'."\n";
                   1310:            } else {
                   1311:                $first = 0;
1.292     www      1312:            }
1.314     bisitz   1313:            $result.= '<div class="LC_Box">'."\n"
                   1314:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
1.293     www      1315:            $count++;
1.292     www      1316:         }
1.282     albertel 1317: 	$result .=
                   1318: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
1.292     www      1319: 	    $file->[1].'</label>';
                   1320:         if ($file->[3]) {
                   1321:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
                   1322:         }
1.341     bisitz   1323:         # Provide example link
1.292     www      1324:         my $filename=$file->[0];
1.329     raeburn  1325:         $filename=~s{^\Q$londocroot\E}{};
1.344     raeburn  1326:         if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
                   1327:             $result .= ' <span class="LC_fontsize_small">'
                   1328:                       .&Apache::loncommon::modal_link(
                   1329:                            $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
                   1330:                       .'</span>';
                   1331:         }
1.341     bisitz   1332:         $result .= '<br />'."\n";
1.287     raeburn  1333:         $count ++;
                   1334:     }
                   1335:     if ($numfiles > 0) {
1.314     bisitz   1336:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
1.42      albertel 1337:     }
1.145     albertel 1338:     return $result;
1.42      albertel 1339: }
                   1340: 
                   1341: sub newproblem {
1.65      matthew  1342:     my ($request) = @_;
1.282     albertel 1343: 
1.347     golterma 1344: 	if ($env{'form.mode'} eq 'blank'){
                   1345:         my $dest = &Apache::lonnet::filelocation("",$request->uri);
                   1346:         &File::Copy::copy('/home/httpd/html/res/adm/includes/templates/blank.problem',$dest);
                   1347:         &renderpage($request,$dest);
                   1348:         return;
                   1349:     }
1.282     albertel 1350:     if ($env{'form.template'}) {
                   1351: 	my $file = $env{'form.template'};
1.65      matthew  1352: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1353: 	&File::Copy::copy($file,$dest);
1.65      matthew  1354: 	&renderpage($request,$dest);
1.282     albertel 1355: 	return;
                   1356:     }
                   1357: 
                   1358:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
                   1359:     &Apache::lonxml::debug("Looking for :$extension:");
1.347     golterma 1360:     my $templatelist=&get_template_html($extension);
1.282     albertel 1361:     if ($env{'form.newfile'} && !$templatelist) {
                   1362: 	# no templates found
1.131     albertel 1363: 	my $templatefilename =
1.258     albertel 1364: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
1.131     albertel 1365: 	&Apache::lonxml::debug("$templatefilename");
                   1366: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1367: 	&File::Copy::copy($templatefilename,$dest);
1.131     albertel 1368: 	&renderpage($request,$dest);
1.85      albertel 1369:     } else {
1.176     albertel 1370: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
1.65      matthew  1371: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.128     albertel 1372: 	my $errormsg;
1.85      albertel 1373: 	my $instructions;
1.330     raeburn  1374:         my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn  1375:                        'text' => 'Authoring Space'},
1.312     bisitz   1376:                       {'href' => '',
                   1377:                        'text' => "Create New $extension"}];
1.240     albertel 1378: 	my $start_page = 
1.312     bisitz   1379:             &Apache::loncommon::start_page("Create New $extension",
                   1380:                                            undef,
                   1381:                                            {'bread_crumbs' => $brcrum,});
1.311     bisitz   1382: 	$request->print(
                   1383:         $start_page
                   1384:        .&Apache::loncommon::head_subbox(
                   1385:                 &Apache::loncommon::CSTR_pageheader())
                   1386:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
1.128     albertel 1387: $errormsg
1.258     albertel 1388: ".&mt("The requested file [_1] currently does not exist.",
1.329     raeburn  1389:       '<span class="LC_filename">'.$url.'</span>').'
1.314     bisitz   1390: <p class="LC_info">
                   1391: '.&mt("To create a new $extension, select a template from the".
                   1392:       " list below. Then click on the \"Create $extension\" button.").'
                   1393: </p><div><form action="'.$url.'" method="post">');
1.258     albertel 1394: 
1.85      albertel 1395: 	if (defined($templatelist)) {
1.282     albertel 1396: 	    $request->print($templatelist);
1.85      albertel 1397: 	}
1.282     albertel 1398: 	$request->print('<br /><input type="submit" name="newfile" value="'.
                   1399: 			&mt("Create $extension").'" />');
1.314     bisitz   1400: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
1.65      matthew  1401:     }
1.282     albertel 1402:     return;
1.42      albertel 1403: }
                   1404: 
1.268     albertel 1405: sub update_construct_style {
                   1406:     if ($env{'request.state'} eq "construct"
1.289     raeburn  1407: 	&& $env{'form.problemmode'} eq 'view' 
1.268     albertel 1408: 	&&  defined($env{'form.submitted'})
                   1409: 	&& !defined($env{'form.resetdata'})
                   1410: 	&& !defined($env{'form.newrandomization'})) {
                   1411: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
                   1412: 	    ||$env{'form.clear_style_file'}) {
1.303     raeburn  1413: 	    &Apache::lonnet::delenv('construct.style');
1.268     albertel 1414: 	} elsif ($env{'form.style_file'} 
                   1415: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
1.291     raeburn  1416: 	    &Apache::lonnet::appenv({'construct.style' => 
                   1417: 				        $env{'form.style_file'}});
1.268     albertel 1418: 	}
                   1419:     }
                   1420: }
                   1421: 
1.354     musolffc 1422: #
                   1423: # Sets interval for current user so time left will be zero, either for the entire folder 
                   1424: # containing the current resource, or just the resource, depending on value of first item
                   1425: # in interval array retrieved from EXT("resource.0.interval");
                   1426: #
                   1427: sub zero_timer {
                   1428:     my ($symb) = @_;
                   1429:     my ($hastimeleft,$first_access,$now);
1.356     raeburn  1430:     my @interval=&Apache::lonnet::EXT("resource.0.interval",$symb);
1.354     musolffc 1431:     if (@interval > 1) {
                   1432:         if ($interval[1] eq 'course') {
                   1433:             return;
                   1434:         } else {
                   1435:             my $now = time;
                   1436:             my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
                   1437:             if ($first_access > 0) {
1.357     raeburn  1438:                 my ($timelimit) = split(/_/,$interval[0]);
                   1439:                 if ($first_access+$timelimit > $now) {
1.354     musolffc 1440:                     my $done_time = $now - $first_access;
                   1441:                     my $snum = 1;
                   1442:                     if ($interval[1] eq 'map') {
                   1443:                         $snum = 2;
                   1444:                     }
                   1445:                     my $result = 
                   1446:                         &Apache::lonparmset::storeparm_by_symb_inner($symb,'0_interval',
                   1447:                                                                      $snum,$done_time,
                   1448:                                                                      'date_interval',
                   1449:                                                                      $env{'user.name'},
                   1450:                                                                      $env{'user.domain'});
1.359   ! musolffc 1451:                         # Record action in "User Notes"
        !          1452:                         &Apache::lonmsg::store_instructor_comment(
        !          1453:                             'Pressed Done button for symb:<br />'.$symb,
        !          1454:                             $env{'user.name'}, $env{'user.domain'});
1.354     musolffc 1455:                     return $result;
                   1456:                 }
                   1457:             }
                   1458:         }
                   1459:     }
                   1460:     return;
                   1461: }
1.268     albertel 1462: 
1.41      albertel 1463: sub handler {
1.145     albertel 1464:     #my $t0 = [&gettimeofday()];
                   1465:     my $request=$_[0];
1.354     musolffc 1466: 
1.223     albertel 1467:     $Apache::lonxml::request=$request;
1.204     albertel 1468:     $Apache::lonxml::debug=$env{'user.debug'};
                   1469:     $env{'request.uri'}=$request->uri;
1.180     albertel 1470:     &setuppermissions();
1.193     albertel 1471: 
1.145     albertel 1472:     my $file=&Apache::lonnet::filelocation("",$request->uri);
                   1473: 
                   1474:     #check if we know where we are
1.350     raeburn  1475:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) {
1.145     albertel 1476: 	# if we are browsing we might not be able to know where we are
1.173     albertel 1477: 	if ($Apache::lonhomework::browse ne 'F' && 
1.204     albertel 1478: 	    $env{'request.state'} ne "construct") {
1.145     albertel 1479: 	    #should know where we are, so ask
1.253     albertel 1480: 	    &unset_permissions();
                   1481: 	    $request->internal_redirect('/adm/ambiguous');
                   1482: 	    return OK;
1.145     albertel 1483: 	}
                   1484:     }
1.253     albertel 1485:     if (&setupheader($request)) {
                   1486: 	&unset_permissions();
                   1487: 	return OK;
                   1488:     }
1.354     musolffc 1489: 
1.244     albertel 1490:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1.204     albertel 1491:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1.261     albertel 1492:     my ($symb) = &Apache::lonnet::whichuser();
1.145     albertel 1493:     &Apache::lonxml::debug('symb is '.$symb);
1.204     albertel 1494:     if ($env{'request.state'} eq "construct") {
1.145     albertel 1495: 	if ( -e $file ) {
                   1496: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1497: 						    ['problemmode']);
1.204     albertel 1498: 	    if (!(defined $env{'form.problemmode'})) {
1.145     albertel 1499: 		#first visit to problem in construction space
1.289     raeburn  1500: 		$env{'form.problemmode'}= 'view';
1.145     albertel 1501: 		&renderpage($request,$file);
1.323     www      1502: 	    } elsif (($env{'form.problemmode'} eq 'editxml') || 
                   1503:                      ($env{'form.problemmode'} eq 'saveeditxml') ||
                   1504:                      ($env{'form.problemmode'} eq 'saveviewxml') ||
                   1505:                      ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel 1506: 		&editxmlmode($request,$file);
1.289     raeburn  1507: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
1.145     albertel 1508: 		&analyze($request,$file);
                   1509: 	    } else {
1.268     albertel 1510: 		&update_construct_style();
1.145     albertel 1511: 		&renderpage($request,$file);
                   1512: 	    }
                   1513: 	} else {
1.347     golterma 1514: 		&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1515: 						    ['mode']);
1.145     albertel 1516: 	    # requested file doesn't exist in contruction space
                   1517: 	    &newproblem($request);
                   1518: 	}
                   1519:     } else {
1.354     musolffc 1520:         # Set the event timer to zero if the "done button" was clicked.  The button is
                   1521:         # part of the doneButton form created in lonmenu.pm
                   1522:         if ($symb && $env{'form.LC_interval_done'} eq 'true') {  
                   1523:             &zero_timer($symb);
                   1524:             undef($env{'form.LC_interval_done'});
                   1525:         }
1.145     albertel 1526: 	# just render the page normally outside of construction space
                   1527: 	&Apache::lonxml::debug("not construct");
1.52      albertel 1528: 	&renderpage($request,$file);
1.41      albertel 1529:     }
1.145     albertel 1530:     #my $td=&tv_interval($t0);
                   1531:     #&Apache::lonxml::debug("Spent $td seconds processing");
                   1532:     # always turn off debug messages
                   1533:     $Apache::lonxml::debug=0;
1.253     albertel 1534:     &unset_permissions();
1.145     albertel 1535:     return OK;
1.52      albertel 1536: 
1.1       albertel 1537: }
                   1538: 
1.352     droeschl 1539: sub template_dropdown_datastructure {
                   1540:     # gathering the all templates and their path, title, category and help topic
                   1541:     my @templates = get_template_list('problem');
                   1542:     # template category => title
                   1543:     my %tmplthash = ();
                   1544:     # template title => path
                   1545:     my %tmpltcontent = ();
                   1546: 	
                   1547:     foreach my $template (@templates){
                   1548:         # put in hash if the template is not empty
                   1549:         unless ($template->[1] eq ''){
                   1550:             push(@{$tmplthash{$template->[2]}}, $template->[1]);
                   1551:             push(@{$tmpltcontent{$template->[1]}},$template->[0]);
                   1552:         }
                   1553:     }
                   1554: 
                   1555: 	my $catList = [];
                   1556:     foreach my $cat (sort keys %tmplthash) {
                   1557: 		my $catItems = [];
                   1558:         foreach my $title (sort @{$tmplthash{$cat}}) {
                   1559:             my $path = $tmpltcontent{$title}->[0];
                   1560:             my $code;
                   1561:             open(FH, "<$path");
                   1562:             while(<FH>){
                   1563:                 $code.= $_ unless $_ =~ /(<problem>)|(<\/problem>)/;
                   1564:             }
                   1565:             close(FH);
                   1566: 
                   1567: 			if ($code ne '') {				
                   1568:                 my $href = 'javascript:insertText(\'' . &convert_for_js(&HTML::Entities::encode($code,'<>&"')) . '\')';
                   1569: 				my $currItem = [$href, $title, undef];
                   1570: 				push @{$catItems}, $currItem;
                   1571: 			}
                   1572:         }
                   1573: 		push @{$catList}, [$catItems, $cat, undef];
                   1574:     }
                   1575: 
                   1576:     return $catList;
                   1577: }
                   1578: 
                   1579: sub responseblock_dropdown_datastructure {
                   1580: 	
                   1581: 	my $mathCat = [
                   1582: 		[
                   1583: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_formularesponse())) . "\')", &mt("Formula Response"), undef],
                   1584: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_functionplotresponse())) . "\')", &mt("Function Plot Response"), undef],
                   1585: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_mathresponse())) . "\')", &mt("Math Response"), undef],
                   1586: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_numericalresponse())) . "\')", &mt("Numerical Response"), undef]
                   1587: 		], 
                   1588: 		&mt("Math"), 
                   1589: 		undef
                   1590: 	];
                   1591: 
                   1592: 	my $miscCat = [		
                   1593: 		[
                   1594:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_imageresponse())) . "\')", &mt("Click on Image"), undef],
                   1595:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_customresponse())) . "\')", &mt("Custom Response"), undef],
                   1596:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_externalresponse())) . "\')", &mt("External Response"), undef],
                   1597:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_matchresponse())) . "\')", &mt("Match Two Lists"), undef],
                   1598:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_radiobuttonresponse())) . "\')", &mt("One out of N statements"), undef],
                   1599:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_optionresponse())) . "\')", &mt("Select from Options"), undef], 
                   1600: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_rankresponse())) . "\')", &mt("Rank Values"), undef]
                   1601: 		],
                   1602: 		&mt("Miscellaneous"),
                   1603: 		undef
                   1604: 	];
                   1605: 
                   1606: 	my $chemCat = [
                   1607: 		[
                   1608: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_reactionresponse())) . "\')", &mt("Chemical Reaction"), undef],
                   1609: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicresponse())) . "\')", &mt("Organic Chemical Structure"), undef]
                   1610: 		],
                   1611: 		&mt("Chemistry"),
                   1612: 		undef
                   1613: 	];
                   1614: 
                   1615: 	my $textCat = [
                   1616: 		[
                   1617: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_stringresponse())) . "\')", &mt("String Response"), undef],
                   1618: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_essayresponse())) . "\')", &mt("Essay"), undef]
                   1619: 		],
                   1620: 		&mt("Text"),
                   1621: 		undef
                   1622: 	];
                   1623: 
                   1624:     return [$mathCat, $miscCat, $chemCat, $textCat];
                   1625: }
                   1626: 
                   1627: 
                   1628: sub conditional_scripting_datastructure {
                   1629: # TODO: corresponding routines should be used for the javascript:insertText parts
                   1630: # instead of the placeholder routine default_xml_tag with the tags
                   1631: # e.g. &default_xml_tag("postanswerdate") should be replaced with a routine which
                   1632: # returns the corresponding content for this case
                   1633: 
                   1634: #TODO translated is currently temporarily here, another solution should be found where the
                   1635: # needed string can be retrieved
                   1636: 
                   1637: 	my $translatedTag = '
                   1638: <translated>
                   1639:     <lang which="en"></lang>
                   1640:     <lang which="default"></lang>
                   1641: </translated>';
                   1642:     return [
                   1643: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode($translatedTag)) . "\')", &mt("Translated Block"), undef],
                   1644: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("block"))) . "\')", &mt("Conditional Block"), undef],
                   1645: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("postanswerdate"))) . "\')", &mt("After Answer Date Block"), undef],
                   1646: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("preduedate"))) . "\')", &mt("Before Due Date Block"), undef],
                   1647: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("solved"))) . "\')", &mt("Block For After Solved"), undef],
                   1648: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("notsolved"))) . "\')", &mt("Block For When Not Solved"), undef]
                   1649:         ];
                   1650: }
                   1651: 
                   1652: sub misc_datastructure {
                   1653:     return [
                   1654:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_img())) . "\')", &mt("Image"), undef],
                   1655:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::lonplot::insert_gnuplot())) . "\')", &mt("GNU Plot"), undef],
                   1656:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicstructure())) . "\')", &mt("Organic Structure"), undef],
                   1657:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_script())) . "\')", &mt("Script Block"), undef],
                   1658:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("allow"))) . "\')", &mt("File Dependencies"), undef],
                   1659:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("import"))) . "\')", &mt("Import a File"), undef],
1.353     droeschl 1660:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::londefdef::insert_meta())) . "\')", &mt("Custom Metadata"), undef],
                   1661:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("part"))) . "\')", &mt("Problem Part"), undef]
1.352     droeschl 1662:     ];
                   1663: }
                   1664: 
                   1665: # helper routine for the datastructure building subroutines
                   1666: sub default_xml_tag {
                   1667: 	my ($tag) = @_;
                   1668: 	return "\n<$tag></$tag>";
                   1669: }
                   1670: 
                   1671: 
                   1672: sub helpmenu_datastructure {
                   1673: 
                   1674: 	my $width = 500;
                   1675: 	my $height = 600;
                   1676: 
                   1677: 	my $helpers = [
                   1678: 		['Problem_LON-CAPA_Functions', &mt('Script Functions')],
                   1679: 		['Greek_Symbols', &mt('Greek Symbols')],
                   1680:  		['Other_Symbols', &mt('Other Symbols')],
                   1681: 		['Authoring_Output_Tags', &mt('Output Tags')],
                   1682: 		['Authoring_Multilingual_Problems', 
                   1683: 			&mt('How to create problems in different languages')]
                   1684: 	];
                   1685: 
                   1686: 	my $help_structure = [];
                   1687: 
                   1688: 	foreach my $count (0..(scalar(@{$helpers})-1)) {
                   1689: 		my $filename = $helpers->[$count]->[0];
                   1690: 		my $title = $helpers->[$count]->[1];
                   1691: 		my $href = &HTML::Entities::encode("javascript:openMyModal('/adm/help/$filename.hlp',$width,$height,'yes');");
                   1692: 		push @{$help_structure}, [$href, $title, undef];
                   1693: 	}
                   1694: 
                   1695: 	return $help_structure;
                   1696: }
                   1697: 
                   1698: # we need substitution to not break javascript code
                   1699: sub convert_for_js {
                   1700:     my $return = shift;
                   1701:         $return =~ s|script|ESCAPEDSCRIPT|g;
                   1702:         $return =~ s|\\|\\\\|g;
                   1703:         $return =~ s|\n|\\r\\n|g;
                   1704:         $return =~ s|'|\\'|g;
                   1705: 		$return =~ s|&#39;|\\&#39;|g;
                   1706:     return $return;
                   1707: }
                   1708: 
1.1       albertel 1709: 1;
                   1710: __END__

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