File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.395: download - view: text, annotated - select for diffs
Sat Jun 28 14:35:00 2025 UTC (2 days, 11 hours ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6623. Grace period after due date during which problem can be viewed
  and submissions can be made for partial credit. Work in progress.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Homework handler
    3: #
    4: # $Id: lonhomework.pm,v 1.395 2025/06/28 14:35:00 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","overduedate","answerdate") {
  604: 	    $lastdate = $date;
  605: 	    if ($temp eq 'duedate') {
  606: 		$date = &due_date($id,$symb);
  607:             } elsif ($temp eq 'overduedate') {
  608:                 $date = &overdue_date($id,$symb);
  609: 	    } else {
  610: 		$date = &Apache::lonnet::EXT("resource.$id.$temp",$symb);
  611: 	    }
  612: 	    
  613: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type",$symb);
  614: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
  615: 		$date     =~ /^(con_lost|no_such_host)/) {
  616: 		$status='UNAVAILABLE';
  617: 		$date=&mt("may open later.");
  618: 		return($status,$date);
  619: 	    }
  620: 	    if ($thistype eq 'date_interval') {
  621: 		if ($temp eq 'opendate') {
  622: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)-$date;
  623: 		}
  624: 		if ($temp eq 'answerdate') {
  625: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)+$date;
  626: 		}
  627: 	    }
  628: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
  629: 	    if ($date eq '') {
  630: 		$date = &mt("an unknown date"); $passed = 0;
  631: 	    } elsif ($date eq 'con_lost') {
  632: 		$date = &mt("an indeterminate date"); $passed = 0;
  633: 	    } else {
  634: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
  635: 		$date = &Apache::lonlocal::locallocaltime($date);
  636: 	    }
  637: 	    if (!$passed) { $type=$temp; last; }
  638: 	}
  639: 	&Apache::lonxml::debug("have :$type:$passed:");
  640: 	if ($passed) {
  641: 	    $status='SHOW_ANSWER';
  642: 	    $datemsg=$date;
  643: 	} elsif ($type eq 'opendate') {
  644: 	    $status='CLOSED';
  645: 	    $datemsg = &mt('will open on [_1]',$date);
  646: 	} elsif ($type eq 'duedate') {
  647: 	    $status='CAN_ANSWER';
  648: 	    $datemsg = &mt('is due at [_1]',$date);
  649:         } elsif ($type eq 'overduedate') {
  650:             $status='CAN_ANSWER';
  651:             $datemsg = &mt('past-due grace period until [_1]',$date);
  652: 	} elsif ($type eq 'answerdate') {
  653: 	    $status='CLOSED';
  654: 	    $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
  655:                                $lastdate,$date);
  656: 	}
  657:     }
  658:     if ($status eq 'CAN_ANSWER' ||
  659: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
  660: 	#check #tries, and if correct.
  661: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
  662: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries",$symb);
  663: 	if ( $tries eq '' ) { $tries = '0'; }
  664: 	if ( $maxtries eq '' && 
  665: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
  666: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
  667: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
  668: 	if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
  669: 	      && (&show_problem_status()) ) {
  670:             if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
  671:                 (&Apache::lonnet::EXT("resource.$id.retrypartial",$symb) !~/^1|on|yes$/i)) {
  672: 	        $status = 'CANNOT_ANSWER';
  673:             }
  674:         } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
  675: 	    $status = 'CANNOT_ANSWER';
  676: 	}
  677: 	if ($status eq 'CANNOT_ANSWER'
  678: 	    && &show_answer_problem_status()) {
  679: 	    $status = 'SHOW_ANSWER';
  680: 	}
  681:     }
  682:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
  683: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval",$symb);
  684: 	&Apache::lonxml::debug("looking for interval @interval");
  685: 	if ($interval[0]=~ /^\d+/) {
  686: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
  687: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
  688: 	    if (!$first_access) {
  689: 		$status='NOT_YET_VIEWED';
  690: 		my $due_date = &due_date($id,$symb);
  691: 		my $seconds_left = $due_date - time;
  692: 		my ($timelimit) = ($interval[0] =~ /^(\d+)/);
  693: 		if ($seconds_left > $timelimit || $due_date eq '') {
  694: 		    $seconds_left = $timelimit;
  695: 		}
  696: 		$datemsg=&seconds_to_human_length($seconds_left);
  697: 	    }
  698: 	}
  699:     }
  700: 
  701:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
  702:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
  703:   #    return ('UNCHECKEDOUT','needs to be checked out');
  704:   #}
  705: 
  706:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
  707:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
  708: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
  709: 	$status='CAN_ANSWER';
  710: 	$datemsg=&mt('is closed but you are allowed to view it');
  711:     }
  712: 
  713:     return ($status,$datemsg);
  714: }
  715: # this should work exactly like the copy in lonnavmaps.pm
  716: sub due_date {
  717:     my ($part_id,$symb,$udom,$uname)=@_;
  718:     my $date;
  719:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
  720: 				       $udom,$uname);
  721:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
  722:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
  723: 				       $udom,$uname);
  724:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
  725:     if ($interval[0] =~ /\d+/) {
  726: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
  727: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
  728: 	if (defined($first_access)) {
  729: 	    my ($timelimit) = ($interval[0] =~ /^(\d+)/);
  730: 	    my $interval = $first_access+$timelimit;
  731: 	    $date = (!$due_date || $interval < $due_date) ? $interval
  732:                                                           : $due_date;
  733: 	} else {
  734: 	    $date = $due_date;
  735: 	}
  736:     } else {
  737: 	$date = $due_date;
  738:     }
  739:     return $date;
  740: }
  741: 
  742: sub overdue_date {
  743:     my ($part_id,$symb,$udom,$uname)=@_;
  744:     my $date;
  745:     my $duedate= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
  746:                                        $udom,$uname);
  747:     if ($duedate ne '') {
  748:         my $grace = &Apache::lonnet::EXT("resource.$part_id.grace",$symb,
  749:                                          $udom,$uname);
  750:         if ($grace) {
  751:             my $grace_end = (split(/,/,$grace))[-1];
  752:             my ($offset) = split(/:/,$grace_end,2);
  753:             if ($offset > 0) {
  754:                 $date = $offset + $duedate;
  755:             }
  756:         } 
  757:     }
  758:     return $date;
  759: }
  760: 
  761: sub partial_credit_overdue {
  762:     my ($part_id,$symb,$udom,$uname)=@_;
  763:     my $reduction;
  764:     my $duedate = &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
  765:                                        $udom,$uname);
  766:     if ($duedate) {
  767:         my $grace = &Apache::lonnet::EXT("resource.$part_id.grace",$symb,
  768:                                          $udom,$uname); 
  769:         if ($grace) {
  770:             my $lateness = time - $duedate;
  771:             if ($lateness > 0) {
  772:                 my ($start,$end,$startfrac,$endfrac,$usegrad);
  773:                 $start = 0;
  774:                 $startfrac = 1.0;
  775:                 $usegrad = 0;
  776:                 foreach my $item (split(/,/,$grace)) {
  777:                     my ($offset,$frac,$grad) = split(/:/,$item);
  778:                     if ($lateness > $offset) {
  779:                         $start = $offset;
  780:                         $startfrac = $frac;
  781:                         next;
  782:                     } elsif ($lateness <= $offset) {
  783:                         $end = $offset;
  784:                         $endfrac = $frac;
  785:                         $usegrad = $grad;
  786:                         last;
  787:                     }
  788:                 }
  789:                 if ($end) {
  790:                     if (($end == $start) || ($startfrac == $endfrac)) {
  791:                         $reduction = $endfrac;
  792:                     } elsif ($end - $start > 0) {
  793:                         if (($endfrac <= 1.0) && ($endfrac >= 0)) {
  794:                             $reduction = $endfrac;
  795:                             if ($usegrad) {
  796:                                 my $decline = $startfrac - $endfrac;
  797:                                 my $fraction = ($lateness - $start)/($end - $start);
  798:                                 if (($fraction <= 1) && ($fraction >= 0)) {
  799:                                     my $value = $startfrac - ($decline*$fraction);
  800:                                     $reduction = sprintf("%.2f", $value);
  801:                                 }
  802:                             }
  803:                         }
  804:                     }
  805:                 }
  806:             }
  807:         }
  808:     }
  809:     return $reduction;
  810: }
  811: 
  812: sub seconds_to_human_length {
  813:     my ($length)=@_;
  814: 
  815:     my $seconds=$length%60; $length=int($length/60);
  816:     my $minutes=$length%60; $length=int($length/60);
  817:     my $hours=$length%24;   $length=int($length/24);
  818:     my $days=$length;
  819: 
  820:     my $timestr;
  821:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
  822:     if ($hours > 0) { $timestr.=($timestr?", ":"").
  823: 			  &mt('[quant,_1,hour]',$hours); }
  824:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
  825: 			    &mt('[quant,_1,minute]',$minutes); }
  826:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
  827: 			    &mt('[quant,_1,second]',$seconds); }
  828:     return $timestr;
  829: }
  830: 
  831: sub showhash {
  832:     my (%hash) = @_;
  833:     &showhashsubset(\%hash,'.');
  834:     return '';
  835: }
  836: 
  837: sub showarray {
  838:     my ($array)=@_;
  839:     my $string="(";
  840:     foreach my $elm (@{ $array }) {
  841: 	if (ref($elm) eq 'ARRAY') {
  842: 	    $string.=&showarray($elm);
  843: 	} elsif (ref($elm) eq 'HASH') {
  844: 	    $string.= "HASH --- \n<br />";
  845: 	    $string.= &showhashsubset($elm,'.');
  846: 	} else {
  847: 	    $string.="$elm,"
  848: 	}
  849:     }
  850:     chop($string);
  851:     $string.=")";
  852:     return $string;
  853: }
  854: 
  855: sub showhashsubset {
  856:     my ($hash,$keyre) = @_;
  857:     my $resultkey;
  858:     foreach $resultkey (sort(keys(%$hash))) {
  859: 	if ($resultkey !~ /$keyre/) { next; }
  860: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
  861: 	    &Apache::lonxml::debug("$resultkey ---- ".
  862: 				   &showarray($$hash{$resultkey}));
  863: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
  864: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  865: 	    &showhashsubset($$hash{$resultkey},'.');
  866: 	} else {
  867: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  868: 	}
  869:     }
  870:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
  871:     return '';
  872: }
  873: 
  874: sub setuppermissions {
  875:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
  876:     unless ($Apache::lonhomework::browse eq 'F') {
  877:         $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'}); 
  878:     }
  879:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
  880:     if (! $viewgrades && 
  881: 	exists($env{'request.course.sec'}) && 
  882: 	$env{'request.course.sec'} !~ /^\s*$/) {
  883: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
  884:                                                '/'.$env{'request.course.sec'});
  885:         if ($viewgrades) {
  886:             $Apache::lonhomework::viewgradessec = $env{'request.course.sec'};
  887:         }
  888:     }
  889:     $Apache::lonhomework::viewgrades = $viewgrades;
  890: 
  891:     if ($Apache::lonhomework::browse eq 'F' && 
  892: 	$env{'form.devalidatecourseresdata'} eq 'on') {
  893: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
  894: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
  895: 					      $env{"course.$courseid.domain"});
  896:     }
  897: 
  898:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
  899:     if (! $modifygrades && 
  900: 	exists($env{'request.course.sec'}) && 
  901: 	$env{'request.course.sec'} !~ /^\s*$/) {
  902: 	$modifygrades = 
  903: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
  904: 				     '/'.$env{'request.course.sec'});
  905:         if ($modifygrades) {
  906:             $Apache::lonhomework::modifygradessec = $env{'request.course.sec'};
  907:         }
  908:     }
  909:     $Apache::lonhomework::modifygrades = $modifygrades;
  910: 
  911:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
  912:     if (! $queuegrade && 
  913: 	exists($env{'request.course.sec'}) && 
  914: 	$env{'request.course.sec'} !~ /^\s*$/) {
  915: 	$queuegrade = 
  916: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
  917: 				     '/'.$env{'request.course.sec'});
  918:     }
  919:     $Apache::lonhomework::queuegrade = $queuegrade;
  920:     return '';
  921: }
  922: 
  923: sub unset_permissions {
  924:     undef($Apache::lonhomework::queuegrade);
  925:     undef($Apache::lonhomework::modifygrades);
  926:     undef($Apache::lonhomework::modifygradessec);
  927:     undef($Apache::lonhomework::viewgrades);
  928:     undef($Apache::lonhomework::viewgradessec);
  929:     undef($Apache::lonhomework::browse);
  930: }
  931: 
  932: sub setupheader {
  933:     my $request=$_[0];
  934:     &Apache::loncommon::content_type($request,'text/html');
  935:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
  936: 	&Apache::loncommon::no_cache($request);
  937:     }
  938: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
  939: #							  'lastrevisiondate'));
  940:     $request->send_http_header;
  941:     return OK if $request->header_only;
  942:     return ''
  943: }
  944: 
  945: sub handle_save_or_undo {
  946:     my ($request,$problem,$result,$getobjref) = @_;
  947: 
  948:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
  949:     my $filebak =$file.".bak";
  950:     my $filetmp =$file.".tmp";
  951:     my $error=0;
  952:     if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
  953: 	my $error=0;
  954: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
  955: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
  956: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
  957: 	if (!$error) {
  958: 	    &Apache::lonxml::info("<p><b>".
  959: 				  &mt("Undid changes, Switched [_1] and [_2]",
  960: 				      '<span class="LC_filename">'.$filebak.
  961: 				      '</span>',
  962: 				      '<span class="LC_filename">'.$file.
  963: 				      '</span>')."</b></p>");
  964: 	} else {
  965: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
  966: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
  967: 				      '<span class="LC_filename">'.
  968: 				      $filebak.'</span>',
  969: 				      '<span class="LC_filename">'.
  970: 				      $file.'</span>')."</span></p>");
  971: 	    $error=1;
  972: 	}
  973:     } else {
  974:         &Apache::lonnet::correct_line_ends($result);
  975: 
  976: 	my $fs=Apache::File->new(">$filebak");
  977: 	if (defined($fs)) {
  978: 	    print $fs $$problem;
  979: 	} else {
  980: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
  981: 				  &mt("Unable to make backup [_1]",
  982: 				      '<span class="LC_filename">'.
  983: 				      $filebak.'</span>')."</span>");
  984: 	    $error=2;
  985: 	}
  986: 	my $fh=Apache::File->new(">$file");
  987: 	if (defined($fh)) {
  988: 	    print $fh $$result;
  989:             if (ref($getobjref) eq 'SCALAR') {
  990:                 if ($file =~ m{([^/]+)\.(html?)$}) {
  991:                     my $fname = $1;
  992:                     my $ext = $2;
  993:                     my $path = $file;
  994:                     $path =~ s/\Q$fname\E\.\Q$ext\E$//; 
  995:                     my (%allfiles,%codebase);
  996:                     &Apache::lonnet::extract_embedded_items($file,\%allfiles,
  997:                                                            \%codebase,$result);
  998:                     if (keys(%allfiles) > 0) {
  999:                         my $url = $request->uri;
 1000:                         my $state = <<STATE;
 1001:     <input type="hidden" name="action" value="upload_embedded" />
 1002:     <input type="hidden" name="url" value="$url" />
 1003: STATE
 1004:                         $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
 1005:                                       "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
 1006:                                       "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
 1007:                                       &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
 1008:                                       {'error_on_invalid_names'   => 1,
 1009:                                        'ignore_remote_references' => 1,});
 1010:                     }
 1011:                 }
 1012:             }
 1013: 	} else {
 1014: 	    &Apache::lonxml::info('<span class="LC_error">'.
 1015: 				  &mt("Unable to write to [_1]",
 1016: 				      '<span class="LC_filename">'.
 1017: 				      $file.'</span>').
 1018: 				  '</span>');
 1019: 	    $error|=4;
 1020: 	}
 1021:     }
 1022:     return $error;
 1023: }
 1024: 
 1025: sub analyze_header {
 1026:     my ($request) = @_;
 1027:     my $js = &Apache::lonxml::setmode_javascript();
 1028: 
 1029:     # Breadcrumbs
 1030:     my $text = 'Authoring Space';
 1031:     my $href = &Apache::loncommon::authorspace($request->uri);
 1032:     if ($env{'request.course.id'}) {
 1033:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1034:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1035:         if ($href eq "/priv/$cdom/$cnum/") {
 1036:             $text = 'Course Authoring Space';
 1037:         }
 1038:     }
 1039:     my $brcrum = [{'href' => $href,
 1040:                    'text' => $text},
 1041:                   {'href' => '',
 1042:                    'text' => 'Problem Testing'},
 1043:                   {'href' => '',
 1044:                    'text' => 'Analyzing a problem'}];
 1045: 
 1046:     my $result =
 1047:         &Apache::loncommon::start_page('Analyzing a problem',
 1048:                                        $js,
 1049:                                        {'bread_crumbs' => $brcrum,})
 1050:        .&Apache::loncommon::head_subbox(
 1051:                 &Apache::loncommon::CSTR_pageheader());
 1052:     my %lt = &Apache::lonlocal::texthash(
 1053:                  edit => 'Edit',
 1054:                  editxml => 'EditXML',
 1055:              );
 1056:     $result .= 
 1057: 	    '<form name="lonhomework" method="post" action="'.
 1058: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
 1059:             '<input type="hidden" name="problemmode" value="'.
 1060:             $env{'form.problemmode'}.'" />'.
 1061: 	    &Apache::structuretags::remember_problem_state().'
 1062:             <div class="LC_edit_problem_analyze_header">';
 1063:      my %editors = &Apache::loncommon::permitted_editors();
 1064:      foreach my $item ('editxml','edit') {
 1065:          next unless ($editors{$item});
 1066:          $result .= '<input type="button" name="submitmode" value="'.$lt{$item}.'" '.
 1067:                     'onclick="javascript:setmode(this.form,'."'$item'".')" />'.
 1068:                     "\n";
 1069:      }
 1070:      $result .=
 1071:             '<hr />
 1072:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
 1073:             'onclick="javascript:setmode(this.form,'."'view'".')" />
 1074:             <hr />
 1075:             </div>'
 1076:             .&Apache::lonxml::message_location().
 1077:             '</form>';
 1078:     &Apache::lonxml::add_messages(\$result);
 1079:     $request->print($result);
 1080:     $request->rflush();
 1081: }
 1082: 
 1083: sub analyze_footer {
 1084:     my ($request) = @_;
 1085:     $request->print(&Apache::loncommon::end_page());
 1086:     $request->rflush();
 1087: }
 1088: 
 1089: sub analyze {
 1090:     my ($request,$file) = @_;
 1091:     &Apache::lonxml::debug("Analyze");
 1092:     my $result;
 1093:     my %overall;
 1094:     my %seedexample;
 1095:     my %allparts;
 1096:     my $rndseed=$env{'form.rndseed'};
 1097:     &analyze_header($request);
 1098:     my %prog_state=
 1099: 	&Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
 1100:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
 1101: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
 1102: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
 1103:         my $thisseed=$i+$rndseed;
 1104: 	my $subresult=&Apache::lonnet::ssi($request->uri,
 1105: 					   ('grade_target' => 'analyze'),
 1106: 					   ('rndseed' => $thisseed));
 1107: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
 1108: 	my %analyze=&Apache::lonnet::str2hash($subresult);
 1109: 	my @parts;
 1110:         if (ref($analyze{'parts'}) eq 'ARRAY') {
 1111: 	    @parts=@{ $analyze{'parts'} };
 1112: 	}
 1113: 	foreach my $part (@parts) {
 1114: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
 1115: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
 1116: 		$analyze{$part.'.type'} eq 'stringresponse'	||
 1117: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
 1118: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
 1119: 		    my $i=0;
 1120: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
 1121: 			push( @{ $overall{$part.'.answer'}[$i] },
 1122: 			      $answer_part);
 1123: 			my $concatanswer= join("\0",@{ $answer_part });
 1124: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
 1125: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
 1126: 			}
 1127: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
 1128: 			    $thisseed;
 1129: 			$i++;
 1130: 		    }
 1131: 		}
 1132: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
 1133: 		    my $answer_part = 
 1134: 			['<span class="LC_error">'.&mt('Error').'</span>'];
 1135: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
 1136: 			$thisseed;
 1137: 		    push( @{ $overall{$part.'.answer'}[0] },
 1138: 			  $answer_part);
 1139: 		}
 1140: 	    }
 1141: 	}
 1142:     }
 1143:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
 1144:     $request->print('<hr />'
 1145:                    .'<h3>'
 1146:                    .&mt('List of possible answers')
 1147:                    .'</h3>'
 1148:     );
 1149:     foreach my $part (sort(keys(%allparts))) {
 1150:         if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
 1151:             (@{$overall{$part.'.answer'}} > 0)) {
 1152: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
 1153: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
 1154:                 $request->print(&Apache::loncommon::start_data_table()
 1155:                                .&Apache::loncommon::start_data_table_header_row()
 1156:                                .'<th colspan="'.($num_cols+1).'">'
 1157:                                .&mt('Part').' '.$part
 1158:                 );
 1159: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
 1160: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
 1161: 		}
 1162: 		$request->print('</th>'
 1163:                                .&Apache::loncommon::end_data_table_header_row()
 1164:                 );
 1165: 		my %frequency;
 1166: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
 1167: 		    $frequency{join("\0",@{ $answer })}++;
 1168: 		}
 1169:                 $request->print(&Apache::loncommon::start_data_table_header_row()
 1170:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
 1171:                                .'<th>'.&mt('Frequency').'<br />'
 1172:                                .'('.&mt('click for example').')</th>'
 1173:                                .&Apache::loncommon::end_data_table_header_row()
 1174:                 );
 1175: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
 1176:                     $request->print(&Apache::loncommon::start_data_table_row()
 1177:                                    .'<td>'
 1178:                                    .join('</td><td>',split("\0",$answer))
 1179: 				   .'</td>'
 1180:                                    .'<td>'
 1181:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
 1182: 				   .'</td>'
 1183:                                    .&Apache::loncommon::end_data_table_row()
 1184:                     );
 1185: 		}
 1186:                 $request->print(&Apache::loncommon::end_data_table());
 1187: 	    }
 1188: 	} else {
 1189:             $request->print('<p class="LC_warning">'
 1190:                            .&mt('Response [_1] is not analyzable at this time.',$part)
 1191: 			   .'</p>'
 1192:             );
 1193: 	}
 1194:     }
 1195:     if (scalar(keys(%allparts)) == 0 ) {
 1196:         $request->print('<p class="LC_warning">'
 1197:                        .&mt('Found no analyzable responses in this problem.'
 1198:                            .' Currently only Numerical, Formula and String response styles are supported.')
 1199:                        .'</p>'
 1200:         );
 1201:     }
 1202:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
 1203:     &analyze_footer($request);
 1204:     &Apache::lonhomework::showhash(%overall);
 1205:     return $result;
 1206: }
 1207: 
 1208: {
 1209:     my $show_problem_status;
 1210:     sub reset_show_problem_status {
 1211: 	undef($show_problem_status);
 1212:     }
 1213: 
 1214:     sub set_show_problem_status {
 1215: 	my ($new_status) = @_;
 1216: 	$show_problem_status = lc($new_status);
 1217:     }
 1218: 
 1219:     sub hide_problem_status {
 1220: 	return ($show_problem_status eq 'no'
 1221: 		|| $show_problem_status eq 'no_feedback_ever');
 1222:     }
 1223: 
 1224:     sub show_problem_status {
 1225: 	return ($show_problem_status eq 'yes'
 1226: 		|| $show_problem_status eq 'answer'
 1227: 		|| $show_problem_status eq '');
 1228:     }
 1229:     
 1230:     sub show_some_problem_status {
 1231: 	return ($show_problem_status eq 'no');
 1232:     }
 1233: 
 1234:     sub show_no_problem_status {
 1235: 	return ($show_problem_status eq 'no_feedback_ever');
 1236:     }
 1237:   
 1238:     sub show_answer_problem_status {
 1239: 	return ($show_problem_status eq 'answer');
 1240:     }
 1241: }
 1242: 
 1243: sub editxmlmode {
 1244:     my ($request,$file) = @_;
 1245:     my $result;
 1246:     my $problem=&Apache::lonnet::getfile($file);
 1247:     if ($problem eq -1) {
 1248: 	&Apache::lonxml::error(
 1249:             '<p class="LC_error">'
 1250:            .&mt('Unable to find [_1]',
 1251:                 '<span class="LC_filename">'.$file.'</span>')
 1252:            .'</p>');
 1253: 
 1254: 	$problem='';
 1255:     }
 1256:     if (($env{'form.problemmode'} eq 'saveeditxml') ||
 1257:         ($env{'form.problemmode'} eq 'saveviewxml') ||
 1258:         ($env{'form.problemmode'} eq 'undoxml')) {
 1259: 	my $error=&handle_save_or_undo($request,\$problem,
 1260: 				       \$env{'form.editxmltext'});
 1261: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
 1262:     }
 1263:     &Apache::lonhomework::showhashsubset(\%env,'^form');
 1264:     if ($env{'form.problemmode'} eq 'saveviewxml') {
 1265: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
 1266: 	$env{'form.problemmode'}='view';
 1267: 	&renderpage($request,$file);
 1268:     } else {
 1269: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
 1270: 	if ($cols > 80) { $cols = 80; }
 1271: 	if ($cols < 70) { $cols = 70; }
 1272: 	if ($rows < 20) { $rows = 20; }
 1273: 	my $js =
 1274: 	    &Apache::edit::js_change_detection(). 
 1275: 	    &Apache::loncommon::resize_textarea_js().
 1276:             &Apache::lonxml::setmode_javascript().
 1277:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
 1278: 
 1279:     # Breadcrumbs
 1280:     my $text = 'Authoring Space';
 1281:     my $href = &Apache::loncommon::authorspace($request->uri);
 1282:     if ($env{'request.course.id'}) {
 1283:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1284:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1285:         if ($href eq "/priv/$cdom/$cnum/") {
 1286:             $text = 'Course Authoring Space';
 1287:         }
 1288:     }
 1289:     my $brcrum = [{'href' => $href,
 1290:                    'text' => $text},
 1291:                   {'href' => '',
 1292:                    'text' => 'Problem Editing'}];
 1293: 
 1294: 	my $start_page = 
 1295: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
 1296: 					   {'no_auto_mt_title' => 1,
 1297: 					    'only_body'        => 0,
 1298: 					    'add_entries'      => {
 1299: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
 1300: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
 1301:                                                                   },
 1302:                                                 'bread_crumbs' => $brcrum,
 1303:                                              });
 1304: 
 1305:     $result=$start_page
 1306:            .&Apache::loncommon::head_subbox(
 1307:                 &Apache::loncommon::CSTR_pageheader());
 1308: 	$result.=&renderpage($request,$file,['no_output_web'],1).
 1309:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
 1310: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
 1311: 	    &Apache::structuretags::remember_problem_state().'
 1312:             <div class="LC_edit_problem_header">
 1313:               <div class="LC_edit_problem_header_title">'.
 1314:                 &mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').
 1315:               '</div><div class="LC_edit_actionbar" id="actionbar">';
 1316: 
 1317:     $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
 1318:                   &Apache::structuretags::problem_edit_buttons('editxml');
 1319:     $result.='<div>';
 1320: 
 1321:     $result .= '<ol class="LC_primary_menu" style="display:inline-block;font-size:90%;vertical-align:middle;">';
 1322: 
 1323:     my $nocodemirror = &Apache::loncommon::nocodemirror();
 1324:     unless ($nocodemirror) {
 1325:         # dropdown menus
 1326:         $result .= Apache::lonmenu::create_submenu("#", "",
 1327:             &mt("Problem Templates"), template_dropdown_datastructure());
 1328: 
 1329:         $result .= Apache::lonmenu::create_submenu("#", "",
 1330:             &mt("Response Types"), responseblock_dropdown_datastructure());
 1331: 
 1332:         $result .= Apache::lonmenu::create_submenu("#", "",
 1333:             &mt("Conditional Blocks"), conditional_scripting_datastructure());
 1334: 
 1335:         $result .= Apache::lonmenu::create_submenu("#", "",
 1336:             &mt("Miscellaneous"), misc_datastructure());
 1337:     }
 1338: 
 1339:     $result .= Apache::lonmenu::create_submenu("#", "",
 1340:         &mt("Help") . ' <img src="/adm/help/help.png" alt="' . &mt("Help") .
 1341:         '" style="vertical-align:text-bottom; height: auto; margin:0; "/>',
 1342:         helpmenu_datastructure(),"");
 1343: 
 1344:     $result.="</ol></div>";
 1345: 
 1346:     $result .= '</div></div>' .
 1347:         &Apache::lonxml::message_location() .
 1348:         &Apache::loncommon::xmleditor_js() .
 1349:         '<textarea ' . &Apache::edit::element_change_detection() .
 1350:         ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" ' .
 1351:         ' name="editxmltext" id="LC_editxmltext">' .
 1352:         &HTML::Entities::encode($problem,'<>&"') .
 1353:         '</textarea> <div id="LC_aftertextarea"> </div> </form>';
 1354: 
 1355:     my $resource = $env{'request.ambiguous'};
 1356:     unless ($nocodemirror) {
 1357:         $result .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined-xml.css">
 1358:         <script src="/adm/codemirror/codemirror-compressed-xml.js"></script>
 1359:         <script>
 1360:             CodeMirror.defineMode("mixedmode", function(config) {
 1361:                 return CodeMirror.multiplexingMode(
 1362:                     CodeMirror.getMode(config, "xml"),
 1363:                     {
 1364:                         open: "\<script type=\"loncapa/perl\"\>", close: "\</script\>",
 1365:                         mode: CodeMirror.getMode(config, "perl"),
 1366:                         delimStyle: "tag",
 1367:                     }
 1368:               );
 1369:             });
 1370:             var cm = CodeMirror.fromTextArea(document.getElementById("LC_editxmltext"),
 1371:             {
 1372:                 mode: "mixedmode",
 1373:                 lineWrapping: true,
 1374:                 lineNumbers: true,
 1375:                 tabSize: 4,
 1376:                 indentUnit: 4,
 1377: 
 1378:                 autoCloseTags: true,
 1379:                 autoCloseBrackets: true,
 1380:                 height: "auto",
 1381:                 styleActiveLine: true,
 1382: 
 1383:                 extraKeys: {
 1384:                     "Tab": "indentMore",
 1385:                     "Shift-Tab": "indentLess",
 1386:                 }
 1387:             });
 1388:             restoreScrollPosition("'.$resource.'");
 1389:         </script>';
 1390:     }
 1391: 
 1392:     $result .= &Apache::loncommon::end_page();
 1393:     &Apache::lonxml::add_messages(\$result);
 1394:     $request->print($result);
 1395:     }
 1396:     return '';
 1397: }
 1398: 
 1399: #
 1400: #    Render the page in whatever target desired.
 1401: #
 1402: sub renderpage {
 1403:     my ($request,$file,$targets,$return_string,$donebuttonmsg,$viewasuser,$symb) = @_;
 1404: 
 1405:     my @targets = @{$targets || [&get_target()]};
 1406:     &Apache::lonhomework::showhashsubset(\%env,'form.');
 1407:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
 1408: 
 1409:     my $overall_result;
 1410:     foreach my $target (@targets) {
 1411: 	# FIXME need to do something intelligent when a problem goes
 1412:         # from viewable to not viewable due to map conditions
 1413: 	#&setuppermissions();
 1414: 	#if (   $Apache::lonhomework::browse ne '2'
 1415: 	#    && $Apache::lonhomework::browse ne 'F' ) {
 1416: 	#    $request->print(" You most likely shouldn't see me.");
 1417: 	#}
 1418: 	#my $t0 = [&gettimeofday()];
 1419: 	my $output=1;
 1420: 	if ($target eq 'no_output_web') {
 1421: 	    $target = 'web'; $output=0;
 1422: 	}
 1423: 	my $problem=&Apache::lonnet::getfile($file);
 1424: 	my $result;
 1425: 	if ($problem eq -1) {
 1426: 	    $problem='';
 1427: 	    my $filename=(split('/',$file))[-1];
 1428: 	    my $error =
 1429: 		'<p class="LC_error">'
 1430:                .&mt('Unable to find [_1]',
 1431: 			   '<span class="LC_filename">'.$filename.'</span>')
 1432: 		."</p>";
 1433: 	    $result.=
 1434: 		&Apache::loncommon::simple_error_page($request,'Not available',
 1435: 						      $error,{'no_auto_mt_msg' => 1});
 1436: 	    return;
 1437: 	}
 1438: 
 1439: 	my %mystyle;
 1440: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
 1441: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
 1442: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
 1443: 
 1444:         if (($target eq 'web') && ($viewasuser ne '') && ($symb ne '')) {
 1445:             $env{'request.user_in_effect'} = $viewasuser;
 1446:         }
 1447: 
 1448: 	&Apache::lonxml::debug("Should be parsing now");
 1449: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
 1450: 					     &setup_vars($target),%mystyle);
 1451: 	&finished_parsing();
 1452: 	if (!$output) { $result = ''; }
 1453: 	#$request->print("Result follows:");
 1454: 	if ($target eq 'modified') {
 1455: 	    &handle_save_or_undo($request,\$problem,\$result);
 1456: 	} else {
 1457: 	    if ($target eq 'analyze') {
 1458: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
 1459: 		undef(%Apache::lonhomework::analyze);
 1460: 	    } elsif ($target eq 'web') {
 1461:                 if ($donebuttonmsg) {
 1462:                     $result =~ s{</body>}{};
 1463:                     $result.= &Apache::loncommon::confirmwrapper(&Apache::lonhtmlcommon::confirm_success($donebuttonmsg,1))."\n</body>";
 1464:                 }
 1465:             }
 1466: 	    #my $td=&tv_interval($t0);
 1467: 	    #if ( $Apache::lonxml::debug) {
 1468: 	    #$result =~ s:</body>::;
 1469: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
 1470: 	    #}
 1471: #	    $request->print($result);
 1472: 	    $overall_result.=$result;
 1473:             if (($target eq 'web') && ($viewasuser ne '') && ($symb ne '')) {
 1474:                 my ($vuname,$vudom) = split(/:/,$viewasuser);
 1475:                 $overall_result .= &Apache::grades::view_as_user($symb,$vuname,$vudom).
 1476:                                    '</body></html>';
 1477:             }
 1478: #	    $request->rflush();
 1479: 	}
 1480:         if (($target eq 'web') && ($viewasuser ne '') && ($symb ne '')) {
 1481:             undef($env{'request.user_in_effect'});
 1482:         }
 1483: 	#$request->print(":Result ends");
 1484: 	#my $td=&tv_interval($t0);
 1485:     }
 1486:     if (!$return_string) {
 1487: 	&Apache::lonxml::add_messages(\$overall_result);
 1488: 	$request->print($overall_result);   
 1489: 	$request->rflush();
 1490:     } else {
 1491: 	return $overall_result;
 1492:     }
 1493: }
 1494: 
 1495: sub finished_parsing {
 1496:     undef($Apache::lonhomework::parsing_a_problem);
 1497:     undef($Apache::lonhomework::parsing_a_task);
 1498: }
 1499: 
 1500: # function extracted from get_template_html
 1501: # returns "key" -> list
 1502: # key: path of template
 1503: # value 1: title
 1504: # value 2: category
 1505: # value 3: name of help topic ???
 1506: sub get_template_list{
 1507:     my ($extension) = @_;
 1508: 
 1509:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
 1510:                      '/templates/*.'.$extension);
 1511:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
 1512:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
 1513:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
 1514:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
 1515:     return @files;
 1516: }
 1517: 
 1518: sub get_template_html {
 1519:     my ($extension) = @_;
 1520:     my $result;
 1521:     my @allnames;
 1522:     &Apache::lonxml::debug("Looking for :$extension:");
 1523:     my $glob_extension  = $extension;
 1524:     if ($extension eq 'survey' || $extension eq 'exam') {
 1525: 	$glob_extension = 'problem';
 1526:     }
 1527:     my @files = &get_template_list($extension);
 1528:     my ($midpoint,$seconddiv,$numfiles);
 1529:     my @noexamplelink = ('blank.problem','blank.library','script.library');
 1530:     $numfiles = 0;
 1531:     foreach my $file (@files) {
 1532:         next if ($file->[1] !~ /\S/);
 1533:         $numfiles ++;
 1534:     }
 1535:     if ($numfiles > 0) {
 1536:         $result = '<div class="LC_left_float">';
 1537:         $midpoint = int($numfiles/2);
 1538:         if ($numfiles%2) {
 1539:             $midpoint ++;
 1540:         }
 1541:     }
 1542:     my $count = 0;
 1543:     my $currentcategory='';
 1544:     my $first = 1;
 1545:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1546:     foreach my $file (@files) {
 1547: 	next if ($file->[1] !~ /\S/);
 1548:         if ($file->[2] ne $currentcategory) {
 1549:            $currentcategory=$file->[2];
 1550:            if ((!$seconddiv) && ($count >= $midpoint)) {
 1551:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
 1552:                $seconddiv = 1;
 1553:            } elsif (!$first) {
 1554:                $result.='</div>'."\n";
 1555:            } else {
 1556:                $first = 0;
 1557:            }
 1558:            $result.= '<div class="LC_Box">'."\n"
 1559:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
 1560:            $count++;
 1561:         }
 1562: 	$result .=
 1563: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
 1564: 	    $file->[1].'</label>';
 1565:         if ($file->[3]) {
 1566:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
 1567:         }
 1568:         # Provide example link
 1569:         my $filename=$file->[0];
 1570:         $filename=~s{^\Q$londocroot\E}{};
 1571:         if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
 1572:             $result .= ' <span class="LC_fontsize_small">'
 1573:                       .&Apache::loncommon::modal_link(
 1574:                            $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
 1575:                       .'</span>';
 1576:         }
 1577:         $result .= '<br />'."\n";
 1578:         $count ++;
 1579:     }
 1580:     if ($numfiles > 0) {
 1581:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
 1582:     }
 1583:     return $result;
 1584: }
 1585: 
 1586: sub newproblem {
 1587:     my ($request) = @_;
 1588: 
 1589:     if ($env{'form.mode'} eq 'blank'){
 1590:         my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1591:         my $templatefilename =
 1592:             $request->dir_config('lonIncludes').'/templates/blank.problem';
 1593:         &File::Copy::copy($templatefilename,$dest);
 1594:         &renderpage($request,$dest);
 1595:         return;
 1596:     }
 1597:     my $errormsg;
 1598:     if ($env{'form.template'}) {
 1599:         my $file;
 1600:         my ($extension) = ($env{'form.template'} =~ /\.(\w+)$/);
 1601:         if ($extension) {
 1602:             my @files = &get_template_list($extension);
 1603:             foreach my $poss (@files) {
 1604:                 if (ref($poss) eq 'ARRAY') {
 1605:                     if ($env{'form.template'} eq $poss->[0]) {
 1606:                         $file = $env{'form.template'};
 1607:                         last;
 1608:                     }
 1609:                 }
 1610:             }
 1611:             if ($file) {
 1612: 	        my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1613: 	        &File::Copy::copy($file,$dest);
 1614: 	        &renderpage($request,$dest);
 1615: 	        return;
 1616:             } else {
 1617:                 $errormsg = '<p class="LC_error">'.&mt('Invalid template file.').'</p>';
 1618:             }
 1619:         } else {
 1620:             $errormsg = '<p class="LC_error">'.&mt('Invalid template file; template needs to be a .problem, .library, or .task file.').'</p>';
 1621:         }
 1622:     }
 1623: 
 1624:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
 1625:     &Apache::lonxml::debug("Looking for :$extension:");
 1626:     my $templatelist=&get_template_html($extension);
 1627:     if ($env{'form.newfile'} && !$templatelist) {
 1628: 	# no templates found
 1629: 	my $templatefilename =
 1630: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
 1631: 	&Apache::lonxml::debug("$templatefilename");
 1632: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1633: 	&File::Copy::copy($templatefilename,$dest);
 1634: 	&renderpage($request,$dest);
 1635:     } else {
 1636: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
 1637: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1638: 	my $instructions;
 1639:         my $text = 'Authoring Space';
 1640:         my $href = &Apache::loncommon::authorspace($request->uri);
 1641:         if ($env{'request.course.id'}) {
 1642:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1643:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1644:             if ($href eq "/priv/$cdom/$cnum/") {
 1645:                 $text = 'Course Authoring Space';
 1646:             }
 1647:         }
 1648:         my $brcrum = [{'href' => $href,
 1649:                        'text' => $text},
 1650:                       {'href' => '',
 1651:                        'text' => "Create New $extension"}];
 1652: 	my $start_page = 
 1653:             &Apache::loncommon::start_page("Create New $extension",
 1654:                                            undef,
 1655:                                            {'bread_crumbs' => $brcrum,});
 1656: 	$request->print(
 1657:         $start_page
 1658:        .&Apache::loncommon::head_subbox(
 1659:                 &Apache::loncommon::CSTR_pageheader())
 1660:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
 1661: $errormsg
 1662: ".&mt("The requested file [_1] currently does not exist.",
 1663:       '<span class="LC_filename">'.$url.'</span>').'
 1664: <p class="LC_info">
 1665: '.&mt("To create a new $extension, select a template from the".
 1666:       " list below. Then click on the \"Create $extension\" button.").'
 1667: </p><div><form action="'.$url.'" method="post">');
 1668: 
 1669: 	if (defined($templatelist)) {
 1670: 	    $request->print($templatelist);
 1671: 	}
 1672: 	$request->print('<br /><input type="submit" name="newfile" value="'.
 1673: 			&mt("Create $extension").'" />');
 1674: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
 1675:     }
 1676:     return;
 1677: }
 1678: 
 1679: sub update_construct_style {
 1680:     if ($env{'request.state'} eq "construct"
 1681: 	&& $env{'form.problemmode'} eq 'view' 
 1682: 	&&  defined($env{'form.submitted'})
 1683: 	&& !defined($env{'form.resetdata'})
 1684: 	&& !defined($env{'form.newrandomization'})) {
 1685: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
 1686: 	    ||$env{'form.clear_style_file'}) {
 1687: 	    &Apache::lonnet::delenv('construct.style');
 1688: 	} elsif ($env{'form.style_file'} 
 1689: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
 1690: 	    &Apache::lonnet::appenv({'construct.style' => 
 1691: 				        $env{'form.style_file'}});
 1692: 	}
 1693:     }
 1694: }
 1695: 
 1696: #
 1697: # Sets interval for current user so time left will be zero, either for the entire folder
 1698: # containing the current resource, or just the resource, depending on value of first item
 1699: # in interval array retrieved from EXT("resource.0.interval");
 1700: #
 1701: sub zero_timer {
 1702:     my ($symb) = @_;
 1703:     my ($hastimeleft,$first_access,$now);
 1704:     my @interval=&Apache::lonnet::EXT("resource.0.interval",$symb);
 1705:     if (@interval > 1) {
 1706:         if ($interval[1] eq 'course') {
 1707:             return ('fail',&mt('Ending of timed events not supported for intervals set course-wide'));
 1708:         } else {
 1709:             my $now = time;
 1710:             my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
 1711:             if ($first_access > 0) {
 1712:                 my ($timelimit,$donesuffix) = split(/_/,$interval[0],2);
 1713:                 if ($donesuffix =~ /^done(?:|\:[^\:]+\:)(.*)$/) {
 1714:                     my ($dummy,$proctor,$secret) = split(/_/,$1);
 1715:                     if (($proctor) && ($secret ne '')) {
 1716:                         my $key = $env{'form.LC_interval_done_proctorpass'};
 1717:                         $key =~ s/^\s+//;
 1718:                         $key =~ s/\s+$//;
 1719:                         if ($env{'form.LC_interval_done_proctorpass'} ne $secret) {
 1720:                             return ('fail',
 1721:                                    &mt('Incorrect key entered by proctor'));
 1722:                         }
 1723:                     }
 1724:                     if ($first_access+$timelimit > $now) {
 1725:                         my $done_time = $now - $first_access;
 1726:                         my $snum = 1;
 1727:                         if ($interval[1] eq 'map') {
 1728:                             $snum = 2;
 1729:                         }
 1730:                         my $result =
 1731:                             &Apache::lonparmset::storeparm_by_symb_inner($symb,'0_interval',
 1732:                                                                          $snum,$done_time,
 1733:                                                                          'date_interval',
 1734:                                                                          $env{'user.name'},
 1735:                                                                          $env{'user.domain'});
 1736:                         if ($result eq '') {
 1737:                             # Record action in "User Notes"
 1738:                             &Apache::lonmsg::store_instructor_comment(
 1739:                                 'Pressed Done button for symb:<br />'.$symb,
 1740:                                 $env{'user.name'}, $env{'user.domain'});
 1741:                             return ('ok');
 1742:                         } else {
 1743:                             return ('fail',&mt('Error ending timed event: [_1]',$result));
 1744:                         }
 1745:                     } else {
 1746:                         return ('fail',&mt('Timed event already ended'));
 1747:                     }
 1748:                 } else {
 1749:                     return ('fail',&mt('Timed event can not be ended before the time limit'));
 1750:                 }
 1751:             } else {
 1752:                 return ('fail',&mt('Timer not yet started for this timed event'));
 1753:             }
 1754:         }
 1755:     } else {
 1756:         return ('fail',&mt('No timer in use'));
 1757:     }
 1758:     return();
 1759: }
 1760: 
 1761: sub handler {
 1762:     #my $t0 = [&gettimeofday()];
 1763:     my $request=$_[0];
 1764: 
 1765:     $Apache::lonxml::request=$request;
 1766:     $Apache::lonxml::debug=$env{'user.debug'};
 1767:     $env{'request.uri'}=$request->uri;
 1768:     &setuppermissions();
 1769: 
 1770: # -------------------------------------- Flag and buffer for registered cleanup
 1771:     $registered_cleanup=0;
 1772:     undef(@Apache::lonhomework::ltipassback);
 1773: 
 1774:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1775: 
 1776:     #check if we know where we are
 1777:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) {
 1778: 	# if we are browsing we might not be able to know where we are
 1779: 	if ($Apache::lonhomework::browse ne 'F' &&
 1780: 	    $env{'request.state'} ne "construct") {
 1781: 	    #should know where we are, so ask
 1782: 	    &unset_permissions();
 1783: 	    $request->internal_redirect('/adm/ambiguous');
 1784: 	    return OK;
 1785: 	}
 1786:     }
 1787:     if (&setupheader($request)) {
 1788: 	&unset_permissions();
 1789: 	return OK;
 1790:     }
 1791: 
 1792:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
 1793:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
 1794:     my ($symb) = &Apache::lonnet::whichuser();
 1795:     &Apache::lonxml::debug('symb is '.$symb);
 1796:     if ($env{'request.state'} eq "construct") {
 1797: 	if ( -e $file ) {
 1798: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1799: 						    ['problemmode']);
 1800: 	    if (!(defined $env{'form.problemmode'})) {
 1801: 		#first visit to problem in construction space
 1802: 		$env{'form.problemmode'}= 'view';
 1803: 		&renderpage($request,$file);
 1804: 	    } elsif (($env{'form.problemmode'} eq 'editxml') || 
 1805:                      ($env{'form.problemmode'} eq 'saveeditxml') ||
 1806:                      ($env{'form.problemmode'} eq 'saveviewxml') ||
 1807:                      ($env{'form.problemmode'} eq 'undoxml')) {
 1808:                 my %editors = &Apache::loncommon::permitted_editors();
 1809:                 if (($editors{'xml'}) || ($env{'form.problemmode'} eq 'saveviewxml') || ($env{'form.problemmode'} eq 'undoxml')) {
 1810: 		    &editxmlmode($request,$file);
 1811:                 } else {
 1812:                     &update_construct_style();
 1813:                     &renderpage($request,$file);
 1814:                 }
 1815: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
 1816: 		&analyze($request,$file);
 1817: 	    } else {
 1818: 		&update_construct_style();
 1819: 		&renderpage($request,$file);
 1820: 	    }
 1821: 	} else {
 1822: 		&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1823: 						    ['mode']);
 1824: 	    # requested file doesn't exist in contruction space
 1825: 	    &newproblem($request);
 1826: 	}
 1827:     } else {
 1828:         # Set the event timer to zero if the "done button" was clicked.  The button is
 1829:         # part of the doneButton form created in lonmenu.pm
 1830:         my ($donebuttonresult,$donemsg,$viewasuser);
 1831:         if ($symb && $env{'form.LC_interval_done'} eq 'true') {  
 1832:             ($donebuttonresult,$donemsg) = &zero_timer($symb);
 1833:             undef($env{'form.LC_interval_done'});
 1834:             undef($env{'form.LC_interval_done_proctorpass'});
 1835:         }
 1836:         if (($env{'form.LC_viewas'} ne '') && $symb && $env{'request.course.id'} &&
 1837:             ($Apache::lonhomework::viewgrades || $Apache::lonhomework::modifygrades)) {
 1838:             if ($env{'form.LC_viewas'} =~ /^($match_username):($match_domain)$/) {
 1839:                 my ($possuname,$possudom) = ($1,$2);
 1840:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1841:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1842:                 my ($canview,$posssec);
 1843:                 if ($env{'request.course.sec'} ne '') {
 1844:                     if ($Apache::lonhomework::modifygradessec eq $env{'request.course.sec'}) {
 1845:                         $canview = 'section';
 1846:                         $posssec = $env{'request.course.sec'};
 1847:                     } elsif ($Apache::lonhomework::viewgradessec eq $env{'request.course.sec'}) {
 1848:                         $canview = 'section';
 1849:                         $posssec = $env{'request.course.sec'};
 1850:                     }
 1851:                 }
 1852:                 my $crstype = &Apache::loncommon::course_type();
 1853:                 if (&Apache::loncourseuser::is_course_user($possudom,$possuname,$cdom,$cnum,
 1854:                                                            $canview,$crstype,$posssec)) {
 1855:                     $viewasuser = $possuname.':'.$possudom;
 1856:                 }
 1857:             }
 1858:             undef($env{'form.LC_viewas'});
 1859:         }
 1860: 	# just render the page normally outside of construction space
 1861: 	&Apache::lonxml::debug("not construct");
 1862: 	&renderpage($request,$file,undef,undef,$donemsg,$viewasuser,$symb);
 1863:         if (@Apache::lonhomework::ltipassback) {
 1864:             unless ($registered_cleanup) {
 1865:                 my $handlers = $request->get_handlers('PerlCleanupHandler');
 1866:                 $request->set_handlers('PerlCleanupHandler' =>
 1867:                                        [\&do_ltipassback,@{$handlers}]);
 1868:                 $registered_cleanup=1;
 1869:             }
 1870:         }
 1871:     }
 1872:     #my $td=&tv_interval($t0);
 1873:     #&Apache::lonxml::debug("Spent $td seconds processing");
 1874:     # always turn off debug messages
 1875:     $Apache::lonxml::debug=0;
 1876:     &unset_permissions();
 1877:     return OK;
 1878: 
 1879: }
 1880: 
 1881: sub template_dropdown_datastructure {
 1882:     # gathering the all templates and their path, title, category and help topic
 1883:     my @templates = get_template_list('problem');
 1884:     # template category => title
 1885:     my %tmplthash = ();
 1886:     # template title => path
 1887:     my %tmpltcontent = ();
 1888: 	
 1889:     foreach my $template (@templates){
 1890:         # put in hash if the template is not empty
 1891:         unless ($template->[1] eq ''){
 1892:             push(@{$tmplthash{$template->[2]}}, $template->[1]);
 1893:             push(@{$tmpltcontent{$template->[1]}},$template->[0]);
 1894:         }
 1895:     }
 1896: 
 1897: 	my $catList = [];
 1898:     foreach my $cat (sort keys %tmplthash) {
 1899: 		my $catItems = [];
 1900:         foreach my $title (sort @{$tmplthash{$cat}}) {
 1901:             my $path = $tmpltcontent{$title}->[0];
 1902:             my $code;
 1903:             open(FH, "<$path");
 1904:             while(<FH>){
 1905:                 $code.= $_ unless $_ =~ /(<problem>)|(<\/problem>)/;
 1906:             }
 1907:             close(FH);
 1908: 
 1909: 			if ($code ne '') {				
 1910:                 my $href = 'javascript:insertText(\'' . &convert_for_js(&HTML::Entities::encode($code,'<>&"')) . '\')';
 1911: 				my $currItem = [$href, $title, undef];
 1912: 				push @{$catItems}, $currItem;
 1913: 			}
 1914:         }
 1915: 		push @{$catList}, [$catItems, $cat, undef];
 1916:     }
 1917: 
 1918:     return $catList;
 1919: }
 1920: 
 1921: sub responseblock_dropdown_datastructure {
 1922: 	
 1923: 	my $mathCat = [
 1924: 		[
 1925: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_formularesponse())) . "\')", &mt("Formula Response"), undef],
 1926: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_functionplotresponse())) . "\')", &mt("Function Plot Response"), undef],
 1927: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_mathresponse())) . "\')", &mt("Math Response"), undef],
 1928: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_numericalresponse())) . "\')", &mt("Numerical Response"), undef]
 1929: 		], 
 1930: 		&mt("Math"), 
 1931: 		undef
 1932: 	];
 1933: 
 1934: 	my $miscCat = [		
 1935: 		[
 1936:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_imageresponse())) . "\')", &mt("Click on Image"), undef],
 1937:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_customresponse())) . "\')", &mt("Custom Response"), undef],
 1938:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_externalresponse())) . "\')", &mt("External Response"), undef],
 1939:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_matchresponse())) . "\')", &mt("Match Two Lists"), undef],
 1940:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_radiobuttonresponse())) . "\')", &mt("One out of N statements"), undef],
 1941:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_optionresponse())) . "\')", &mt("Select from Options"), undef], 
 1942: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_rankresponse())) . "\')", &mt("Rank Values"), undef]
 1943: 		],
 1944: 		&mt("Miscellaneous"),
 1945: 		undef
 1946: 	];
 1947: 
 1948: 	my $chemCat = [
 1949: 		[
 1950: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_reactionresponse())) . "\')", &mt("Chemical Reaction"), undef],
 1951: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicresponse())) . "\')", &mt("Organic Chemical Structure"), undef]
 1952: 		],
 1953: 		&mt("Chemistry"),
 1954: 		undef
 1955: 	];
 1956: 
 1957: 	my $textCat = [
 1958: 		[
 1959: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_stringresponse())) . "\')", &mt("String Response"), undef],
 1960: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_essayresponse())) . "\')", &mt("Essay"), undef]
 1961: 		],
 1962: 		&mt("Text"),
 1963: 		undef
 1964: 	];
 1965: 
 1966:     return [$mathCat, $miscCat, $chemCat, $textCat];
 1967: }
 1968: 
 1969: 
 1970: sub conditional_scripting_datastructure {
 1971: # TODO: corresponding routines should be used for the javascript:insertText parts
 1972: # instead of the placeholder routine default_xml_tag with the tags
 1973: # e.g. &default_xml_tag("postanswerdate") should be replaced with a routine which
 1974: # returns the corresponding content for this case
 1975: 
 1976: #TODO translated is currently temporarily here, another solution should be found where the
 1977: # needed string can be retrieved
 1978: 
 1979: 	my $translatedTag = '
 1980: <translated>
 1981:     <lang which="en"></lang>
 1982:     <lang which="default"></lang>
 1983: </translated>';
 1984:     return [
 1985: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode($translatedTag)) . "\')", &mt("Translated Block"), undef],
 1986: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("block"))) . "\')", &mt("Conditional Block"), undef],
 1987: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("postanswerdate"))) . "\')", &mt("After Answer Date Block"), undef],
 1988: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("preduedate"))) . "\')", &mt("Before Due Date Block"), undef],
 1989: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("solved"))) . "\')", &mt("Block For After Solved"), undef],
 1990: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("notsolved"))) . "\')", &mt("Block For When Not Solved"), undef]
 1991:         ];
 1992: }
 1993: 
 1994: sub misc_datastructure {
 1995:     return [
 1996:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_img())) . "\')", &mt("Image"), undef],
 1997:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::lonplot::insert_gnuplot())) . "\')", &mt("GNU Plot"), undef],
 1998:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicstructure())) . "\')", &mt("Organic Structure"), undef],
 1999:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_script())) . "\')", &mt("Script Block"), undef],
 2000:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("allow"))) . "\')", &mt("File Dependencies"), undef],
 2001:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("import"))) . "\')", &mt("Import a File"), undef],
 2002:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::londefdef::insert_meta())) . "\')", &mt("Custom Metadata"), undef],
 2003:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("part"))) . "\')", &mt("Problem Part"), undef]
 2004:     ];
 2005: }
 2006: 
 2007: # helper routine for the datastructure building subroutines
 2008: sub default_xml_tag {
 2009: 	my ($tag) = @_;
 2010: 	return "\n<$tag></$tag>";
 2011: }
 2012: 
 2013: 
 2014: sub helpmenu_datastructure {
 2015: 
 2016: 	# filename, title, width, height
 2017: 	my $helpers = [
 2018: 		['Problem_LON-CAPA_Functions.hlp', &mt('Script Functions'), 800, 600],
 2019: 		['Greek_Symbols.hlp', &mt('Greek Symbols'), 500, 600],
 2020:  		['Other_Symbols.hlp', &mt('Other Symbols'), 500, 600],
 2021: 		['Authoring_Output_Tags.hlp', &mt('Output Tags'), 800, 600],
 2022: 		['Authoring_Multilingual_Problems.hlp', 
 2023: 			&mt('How to create problems in different languages'), 800, 600],
 2024: 		['loncapa.html', &mt('Language reference'), 800, 600],
 2025: 	];
 2026: 
 2027: 	my $help_structure = [];
 2028: 
 2029: 	foreach my $count (0..(scalar(@{$helpers})-1)) {
 2030: 		my $filename = $helpers->[$count]->[0];
 2031: 		my $title = $helpers->[$count]->[1];
 2032: 		my $width = $helpers->[$count]->[2];
 2033:                 my $height = $helpers->[$count]->[3];
 2034:                 if ($width eq '') {
 2035:                     $width = 500;
 2036:                 }
 2037:                 if ($height eq '') {
 2038:                     $height = 600;
 2039:                 }
 2040: 		my $href = &HTML::Entities::encode("javascript:openMyModal('/adm/help/$filename',$width,$height,'yes');");
 2041: 		push @{$help_structure}, [$href, $title, undef];
 2042: 	}
 2043: 
 2044: 	return $help_structure;
 2045: }
 2046: 
 2047: # we need substitution to not break javascript code
 2048: sub convert_for_js {
 2049:     my $return = shift;
 2050:         $return =~ s|script|ESCAPEDSCRIPT|g;
 2051:         $return =~ s|\\|\\\\|g;
 2052:         $return =~ s|\n|\\r\\n|g;
 2053:         $return =~ s|'|\\'|g;
 2054: 		$return =~ s|&#39;|\\&#39;|g;
 2055:     return $return;
 2056: }
 2057: 
 2058: sub do_ltipassback {
 2059:     if (@Apache::lonhomework::ltipassback) {
 2060:         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 2061:         my $ip = &Apache::lonnet::get_host_ip($lonhost);
 2062:         foreach my $item (@Apache::lonhomework::ltipassback) {
 2063:             &Apache::lonhomework::run_passback($item,$lonhost,$ip);
 2064:         }
 2065:         undef(@Apache::lonhomework::ltipassback);
 2066:     }
 2067:     return OK;
 2068: }
 2069: 
 2070: sub run_passback {
 2071:     my ($item,$lonhost,$ip) = @_;
 2072:     if (ref($item) eq 'HASH') {
 2073:         if ((ref($item->{'lti'}) eq 'HASH') && ($item->{'cid'} =~ /^($match_domain)_($match_courseid)$/)) {
 2074:             my ($cdom,$cnum) = ($1,$2);
 2075:             my $msgformat = $item->{'lti'}->{'passbackformat'};
 2076:             my $sigmethod = 'HMAC-SHA1';
 2077:             my $ltinum = $item->{'ltinum'};
 2078:             my $id = $item->{'pbid'};
 2079:             my $url = $item->{'pburl'};
 2080:             my $type = $item->{'pbtype'};
 2081:             my $pbscope = $item->{'pbscope'};
 2082:             my $map = $item->{'pbmap'};
 2083:             my $symb = $item->{'pbsymb'};
 2084:             my $uname = $item->{'uname'};
 2085:             my $udom = $item->{'udom'};
 2086:             my $uhome = $item->{'uhome'};
 2087:             my $usec = $item->{'usec'};
 2088:             my $keynum = $item->{'lti'}->{'cipher'};
 2089:             my $crsdef = $item->{'crsdef'};
 2090:             my $scoretype = $item->{'format'};
 2091:             my $scope = $item->{'scope'};
 2092:             my $clientip = $item->{'clientip'};
 2093:             my ($total,$possible,%total_by_symb,%possible_by_symb);
 2094:             if ((exists($item->{'total_s'})) && (ref($item->{'total_s'}) eq 'HASH')) {
 2095:                 %total_by_symb = %{$item->{'total_s'}};
 2096:                 if ($pbscope eq 'resource') {
 2097:                     if (exists($total_by_symb{$symb})) {
 2098:                         $total = $total_by_symb{$symb};
 2099:                     } else {
 2100:                         $total = $item->{'total'};
 2101:                     }
 2102:                 }
 2103:             } elsif ($pbscope eq 'resource') {
 2104:                 $total = $item->{'total'};
 2105:             }
 2106:             if ((exists($item->{'possible_s'})) && (ref($item->{'possible_s'}) eq 'HASH')) {
 2107:                 %possible_by_symb = %{$item->{'possible_s'}};
 2108:                 if ($pbscope eq 'resource') {
 2109:                     if (exists($possible_by_symb{$symb})) {
 2110:                         $possible = $possible_by_symb{$symb};
 2111:                     } else {
 2112:                         $possible = $item->{'possible'};
 2113:                     }
 2114:                 }
 2115:             } elsif ($pbscope eq 'resource') {
 2116:                 $possible = $item->{'possible'};
 2117:             }
 2118:             if (($pbscope eq 'map') || ($pbscope eq 'nonrec')) {
 2119:                 if ((keys(%total_by_symb)) && (keys(%possible_by_symb))) {
 2120:                     ($total,$possible) =
 2121:                     &get_lti_score($uname,$udom,$usec,$map,$pbscope,\%total_by_symb,\%possible_by_symb);
 2122:                 } else {
 2123:                    ($total,$possible) = &get_lti_score($uname,$udom,$usec,$map,$pbscope);
 2124:                 }
 2125:             } elsif ($pbscope eq 'course') {
 2126:                 ($total,$possible) = &get_lti_score($uname,$udom,$usec);
 2127:             }
 2128:             $item->{'total'} = $total;
 2129:             $item->{'possible'} = $possible;
 2130:             if (($id ne '') && ($url ne '') && ($possible)) {
 2131:                 my ($sent,$score,$code,$result) =
 2132:                     &LONCAPA::ltiutils::send_grade($cdom,$cnum,$crsdef,$type,$ltinum,$keynum,$id,
 2133:                                                    $url,$scoretype,$sigmethod,$msgformat,$total,$possible);
 2134:                 $item->{'score'} = $score;
 2135:                 my ($linkprotector,$linkuri,$no_passback,$appname);
 2136:                 if ($item->{'linkprot'}) {
 2137:                     ($linkprotector,$linkuri) = split(/:/,$item->{'linkprot'});
 2138:                 }
 2139:                 if ($sent) {
 2140:                     if ($code == 200) {
 2141:                         if ($item->{'linkprot'}) {
 2142:                             my $skey = join("\0",($linkuri,$linkprotector,$scope));
 2143:                             my $namespace = $cdom.'_'.$cnum.'_lp_passback';
 2144:                             my $store = {
 2145:                                           'score' => $score,
 2146:                                           'ip' => $ip,
 2147:                                           'host' => $Apache::lonnet::perlvar{'lonHostID'},
 2148:                                           'protector' => $linkprotector,
 2149:                                           'deeplink' => $linkuri,
 2150:                                           'scope' => $scope,
 2151:                                           'url' => $url,
 2152:                                           'id' => $id,
 2153:                                           'clientip' => $clientip,
 2154:                                           'whodoneit' => $env{'user.name'}.':'.$env{'user.domain'},
 2155:                                         };
 2156:                             my $value='';
 2157:                             foreach my $key (keys(%{$store})) {
 2158:                                 $value.=&escape($key).'='.&Apache::lonnet::freeze_escape($store->{$key}).'&';
 2159:                             }
 2160:                             $value=~s/\&$//;
 2161:                             &Apache::lonnet::courselog(&escape($linkuri).':'.$uname.':'.$udom.':EXPORT:'.$value);
 2162:                             &Apache::lonnet::store_userdata({'score' => $score},$skey,$namespace,$udom,$uname,$ip);
 2163:                         }
 2164:                     } else {
 2165:                         if ($item->{'linkprot'}) {
 2166:                            $no_passback = "Passback response was $code ($result).";
 2167:                         }
 2168:                     }
 2169:                 } else {
 2170:                     if ($item->{'linkprot'}) {
 2171:                         $no_passback = 'No passback of scores.';
 2172:                     }
 2173:                 }
 2174:                 if ($no_passback) {
 2175:                     if ($item->{'linkprot'}) {
 2176:                         my ($ltinum,$ltitype) = ($linkprotector =~ /^(\d+)(c|d)$/);
 2177:                         if ($ltitype eq 'c') {
 2178:                             my %lti = &Apache::lonnet::get_course_lti($cnum,$cdom,'provider');
 2179:                             if (ref($lti{$ltinum}) eq 'HASH') {
 2180:                                 $appname = $lti{$ltinum}{'name'};
 2181:                             }
 2182:                         } elsif ($ltitype eq 'd') {
 2183:                             my %lti = &Apache::lonnet::get_domain_lti($cdom,'linkprot');
 2184:                             if (ref($lti{$ltinum}) eq 'HASH') {
 2185:                                 $appname = $lti{$ltinum}{'name'};
 2186:                             }
 2187:                         }
 2188:                         $no_passback .= " LTI launcher $linkprotector ($appname) for $linkuri (${cdom}_${cnum})";
 2189:                         &Apache::lonnet::logthis($no_passback." for $uname:$udom");
 2190:                         &Apache::lonnet::log($udom,$uname,$uhome,"$no_passback score=$score total=$total poss=$possible");
 2191:                         if ($item->{'linkprot'}) {
 2192:                             my $pendingkey = &Time::HiRes::time().':'.$uname.':'.$udom.':'.
 2193:                                              "$linkuri\0$linkprotector\0$scope";
 2194:                             &Apache::lonnet::put('linkprot_passback_pending',{$pendingkey => $item},$cdom,$cnum);
 2195:                         }
 2196:                     }
 2197:                 }
 2198:             }
 2199:         }
 2200:     }
 2201:     return;
 2202: }
 2203: 
 2204: sub get_lti_score {
 2205:     my ($uname,$udom,$usec,$mapurl,$pbscope,$totals,$possibles) = @_;
 2206:     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom,$usec);
 2207:     if (ref($navmap)) {
 2208:         my $iterator;
 2209:         if ($mapurl ne '') {
 2210:             my $map = $navmap->getResourceByUrl($mapurl);
 2211:             if (ref($map)) {
 2212:                 my $firstres = $map->map_start();
 2213:                 my $finishres = $map->map_finish();
 2214:                 my $recursive = 1;
 2215:                 if ($pbscope eq 'nonrec') {
 2216:                     $recursive = 0;
 2217:                 }
 2218:                 $iterator = $navmap->getIterator($firstres,$finishres,undef,$recursive);
 2219:             }
 2220:         } else {
 2221:             $iterator = $navmap->getIterator(undef,undef,undef,1);
 2222:         }
 2223:         if (ref($iterator)) {
 2224:             my $depth = 1;
 2225:             my $total = 0;
 2226:             my $possible = 0;
 2227:             my (%totals_by_symb,%possibles_by_symb);
 2228:             if (ref($totals) eq 'HASH') {
 2229:                 %totals_by_symb = %{$totals};
 2230:             }
 2231:             if (ref($possibles) eq 'HASH') {
 2232:                 %possibles_by_symb = %{$possibles};
 2233:             }
 2234:             $iterator->next(); # ignore first BEGIN_MAP
 2235:             my $curRes = $iterator->next();
 2236:             while ( $depth > 0 ) {
 2237:                 if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
 2238:                 if ($curRes == $iterator->END_MAP()) { $depth--; }
 2239:                 if (ref($curRes) && $curRes->is_gradable() && !$curRes->randomout) {
 2240:                     my $currsymb = $curRes->symb();
 2241:                     if (($currsymb) && (exists($totals_by_symb{$currsymb})) &&
 2242:                         (exists($possibles_by_symb{$currsymb}))) {
 2243:                         $total += $totals_by_symb{$currsymb};
 2244:                         $possible += $possibles_by_symb{$currsymb};
 2245:                     } else {
 2246:                         my $parts = $curRes->parts();
 2247:                         foreach my $part (@{$parts}) {
 2248:                             next if ($curRes->solved($part) eq 'excused');
 2249:                             $total += $curRes->weight($part) * $curRes->awarded($part);
 2250:                             $possible += $curRes->weight($part);
 2251:                         }
 2252:                     }
 2253:                 }
 2254:                 $curRes = $iterator->next();
 2255:             }
 2256:             if ($total > $possible) {
 2257:                 $total = $possible;
 2258:             }
 2259:             return ($total,$possible);
 2260:         }
 2261:     }
 2262:     return;
 2263: }
 2264: 
 2265: 1;
 2266: __END__

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