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

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

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