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

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

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