File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.369: download - view: text, annotated - select for diffs
Fri Dec 22 02:00:39 2017 UTC (6 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Consumer
  Support for access control using slots, and also for time interval
  for external tools set to be "gradable".

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

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