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

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

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