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

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

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