File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.383: download - view: text, annotated - select for diffs
Wed Feb 21 19:50:21 2024 UTC (2 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Update hash key names for consistency with changes in structuretags 1.575

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

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