File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.362: download - view: text, annotated - select for diffs
Mon May 30 02:45:32 2016 UTC (7 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6763. "Done" button.
  String saved for the Time-Limit (interval) parameter will no longer be a
  pure integer if use of the "done" button has been enabled.

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

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