File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.355: download - view: text, annotated - select for diffs
Mon Jun 29 15:42:07 2015 UTC (8 years, 11 months ago) by damieng
Branches: MAIN
CVS tags: HEAD
added implementation for <lm>

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

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