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

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

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