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

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

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