File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.356: download - view: text, annotated - select for diffs
Fri Jul 17 19:11:09 2015 UTC (8 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Include countdown timer in composite page (i.e., .page), if all items
  with time left have the same amount of time remaining.

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

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