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

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

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