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

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

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