File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.347: download - view: text, annotated - select for diffs
Mon Jan 19 15:35:53 2015 UTC (9 years, 4 months ago) by goltermann
Branches: MAIN
CVS tags: HEAD
authoring space overhaul
this update tries to improve the user experience of the authoring space.

added codemirror for xml editor and script tags in colorful editor
added possibility to deactivate codemirror in author settings
added dropdown menu to insert problem templates into xml editor (thanks to tobias reinhardt)
added feature of saving current scrollposition on save when editing problems
added possibility to fold blocks in colorful editor, this state will be saved and restored
added shortcuts to create empty problems, html files and directories

and other smaller features and bugfixes

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Homework handler
    3: #
    4: # $Id: lonhomework.pm,v 1.347 2015/01/19 15:35:53 goltermann 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::Constants qw(:common);
   53: use Apache::loncommon();
   54: use Apache::lonlocal;
   55: use Time::HiRes qw( gettimeofday tv_interval );
   56: use HTML::Entities();
   57: use File::Copy();
   58: 
   59: # FIXME - improve commenting
   60: 
   61: 
   62: BEGIN {
   63:     &Apache::lonxml::register_insert();
   64: }
   65: 
   66: 
   67: =pod
   68: 
   69: =item set_bubble_lines()
   70: 
   71: Called at analysis time to set the bubble lines
   72: hash for the problem.. This should be called in the
   73: end_problemtype tag in analysis mode.
   74: 
   75: We fetch the hash of part id counters from lonxml
   76:     and push them into analyze:{part_id.bubble_lines}.
   77: 
   78: =cut
   79: 
   80: sub set_bubble_lines {
   81:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
   82: 
   83:     foreach my $key (keys(%bubble_counters)) {
   84: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
   85: 	    $bubble_counters{"$key"};
   86:     }
   87: }
   88: 
   89: #
   90: # Decides what targets to render for.
   91: # Implicit inputs:
   92: #   Various session environment variables:
   93: #      request.state -  published  - is a /res/ resource
   94: #                       uploaded   - is a /uploaded/ resource
   95: #                       contruct   - is a /priv/ resource
   96: #      form.grade_target - a form parameter requesting a specific target
   97: sub get_target {
   98:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
   99:     if( defined($env{'form.grade_target'})) {
  100: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
  101:     } else {
  102: 	&Apache::lonxml::debug("form.grade_target <undefined>");
  103:     }
  104:     if (($env{'request.state'} eq "published") ||
  105: 	($env{'request.state'} eq "uploaded")) {
  106: 	if ( defined($env{'form.grade_target'}  ) 
  107: 	     && ($env{'form.grade_target'} eq 'tex')) {
  108: 	    return ($env{'form.grade_target'});
  109: 	} elsif ( defined($env{'form.grade_target'}  ) 
  110: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
  111: 	    return ($env{'form.grade_target'});
  112: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
  113: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
  114: 	    return ($env{'form.grade_target'});
  115: 	} elsif ($env{'form.grade_target'} eq 'answer') {
  116:             if ($env{'form.answer_output_mode'} eq 'tex') {
  117:                 return ($env{'form.grade_target'});
  118:             }
  119:         }
  120: 	if ($env{'form.webgrade'} &&
  121: 	    ($Apache::lonhomework::modifygrades eq 'F'
  122: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
  123: 	    return ('grade','webgrade');
  124: 	}
  125: 	if ( defined($env{'form.submitted'}) &&
  126: 	     ( !defined($env{'form.newrandomization'}))) {
  127: 	    return ('grade', 'web');
  128: 	} else {
  129: 	    return ('web');
  130: 	}
  131:     } elsif ($env{'request.state'} eq "construct") {
  132: #
  133: # We are in construction space, editing and testing problems
  134: #
  135: 	if ( defined($env{'form.grade_target'}) ) {
  136: 	    return ($env{'form.grade_target'});
  137: 	}
  138: 	if ( defined($env{'form.preview'})) {
  139: 	    if ( defined($env{'form.submitted'})) {
  140: #
  141: # We are doing a problem preview
  142: #
  143: 		return ('grade', 'web');
  144: 	    } else {
  145: 		return ('web');
  146: 	    }
  147: 	} else {
  148: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
  149: 		return ('grade','webgrade','answer');
  150:             } elsif ($env{'form.problemmode'} eq 'view') {
  151:                 return ('grade','web','answer');
  152: 	    } elsif ($env{'form.problemmode'} eq 'saveview') {
  153:                 return ('modified','web','answer');
  154:             } elsif ($env{'form.problemmode'} eq 'discard') {
  155:                 return ('web','answer');
  156:             } elsif (($env{'form.problemmode'} eq 'saveedit') ||
  157:                      ($env{'form.problemmode'} eq 'undo')) {
  158:                 return ('modified','no_output_web','edit');
  159:             } elsif ($env{'form.problemmode'} eq 'edit') {
  160: 		return ('no_output_web','edit');
  161: 	    } else {
  162: 		return ('web');
  163: 	    }
  164:         }
  165: #
  166: # End of Authoring Space
  167: #
  168:     }
  169: #
  170: # Huh? We are nowhere, so do nothing.
  171: #
  172:     return ();
  173: }
  174: 
  175: sub setup_vars {
  176:     my ($target) = @_;
  177:     return ';'
  178: #  return ';$external::target='.$target.';';
  179: }
  180: 
  181: sub proctor_checked_in {
  182:     my ($slot_name,$slot,$type)=@_;
  183:     my @possible_proctors=split(",",$slot->{'proctor'});
  184:     
  185:     return 1 if (!@possible_proctors);
  186: 
  187:     my $key;
  188:     if ($type eq 'Task') {
  189: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
  190: 	$key ="resource.$version.0.checkedin";
  191:     } elsif ($type eq 'problem') {
  192: 	$key ='resource.0.checkedin';
  193:     }
  194:     # backward compatability, used to be username@domain, 
  195:     # now is username:domain
  196:     my $who = $Apache::lonhomework::history{$key};
  197:     if ($who !~ /:/) {
  198: 	$who =~ tr/@/:/;
  199:     }     
  200:     foreach my $possible (@possible_proctors) { 
  201: 	if ($who eq $possible
  202: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
  203: 	    return 1;
  204: 	}
  205:     }
  206:     
  207:     return 0;
  208: }
  209: 
  210: sub check_slot_access {
  211:     my ($id,$type)=@_;
  212: 
  213:     # does it pass normal muster
  214:     my ($status,$datemsg)=&check_access($id);
  215:     
  216:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots");
  217:     if ($useslots ne 'resource' && $useslots ne 'map' 
  218: 	&& $useslots ne 'map_map') {
  219: 	return ($status,$datemsg);
  220:     }
  221: 
  222:     if ($status eq 'SHOW_ANSWER' ||
  223: 	$status eq 'CLOSED' ||
  224: 	$status eq 'INVALID_ACCESS' ||
  225: 	$status eq 'UNAVAILABLE') {
  226: 	return ($status,$datemsg);
  227:     }
  228:     if ($env{'request.state'} eq "construct") {
  229: 	return ($status,$datemsg);
  230:     }
  231:     
  232:     if ($type eq 'Task') {
  233: 	my $version=$Apache::lonhomework::history{'resource.version'};
  234: 	if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
  235: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
  236: 	    return ('SHOW_ANSWER');
  237: 	}
  238:     }
  239: 
  240:     my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent");
  241:     my $available = &Apache::lonnet::EXT("resource.0.available");
  242:     my @slots= (split(':',$availablestudent),split(':',$available));
  243: 
  244: #    if (!@slots) {
  245: #	return ($status,$datemsg);
  246: #    }
  247:     my $slotstatus='NOT_IN_A_SLOT';
  248:     my ($returned_slot,$slot_name);
  249:     my $now = time;
  250:     my $num_usable_slots = 0;
  251:     foreach my $slot (@slots) {
  252: 	$slot =~ s/(^\s*|\s*$)//g;
  253: 	&Apache::lonxml::debug("getting $slot");
  254: 	my %slot=&Apache::lonnet::get_slot($slot);
  255: 	&Apache::lonhomework::showhash(%slot);
  256:         next if ($slot{'endtime'} < $now);
  257:         $num_usable_slots ++;
  258: 	if ($slot{'starttime'} < $now &&
  259: 	    $slot{'endtime'} > $now &&
  260: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
  261: 	    &Apache::lonxml::debug("$slot is good");
  262: 	    $slotstatus='NEEDS_CHECKIN';
  263: 	    $returned_slot=\%slot;
  264: 	    $slot_name=$slot;
  265: 	    last;
  266:         } 
  267:     }
  268:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
  269: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
  270: 	&Apache::lonxml::debug("proctor checked in");
  271: 	$slotstatus=$status;
  272:     }
  273: 
  274:     my ($is_correct,$got_grade,$checkedin);
  275:     if ($type eq 'Task') {
  276: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
  277: 	$got_grade = 
  278: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
  279: 	     =~ /^(?:pass|fail)$/);
  280: 	$is_correct =  
  281: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
  282: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
  283: 	$checkedin =
  284: 	    $Apache::lonhomework::history{"resource.$version.0.checkedin"};
  285:     } elsif ($type eq 'problem') {
  286: 	$got_grade  = 1;
  287: 	$checkedin  = $Apache::lonhomework::history{"resource.0.checkedin"};
  288: 	$is_correct =
  289: 	    ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
  290:     }
  291:     
  292:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
  293:     
  294:     # no slot is currently open, and has been checked in for this version
  295:     # but hasn't got a grade, therefore must be awaiting a grade
  296:     if (!defined($slot_name)
  297: 	&& $checkedin 
  298: 	&& !$got_grade) {
  299: 	return ('WAITING_FOR_GRADE');
  300:     }
  301: 
  302:     # Previously used slot is no longer open, and has been checked in for this version.
  303:     # However, the problem is not closed, and potentially, another slot might be
  304:     # used to gain access to it to work on it, until the due date is reached, and the
  305:     # problem then becomes CLOSED.  Therefore return the slotstatus - 
  306:     # (which will be one of: NOT_IN_A_SLOT, RESERVABLE, RESERVABLE_LATER, or NOTRESERVABLE.
  307:     if (!defined($slot_name) && $type eq 'problem') {
  308:         if ($slotstatus eq 'NOT_IN_A_SLOT') {
  309:             if (!$num_usable_slots) {
  310:                 if ($env{'request.course.id'}) {
  311:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  312:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  313:                     my ($symb)=&Apache::lonnet::whichuser();
  314:                     $slotstatus = 'NOTRESERVABLE';
  315:                     my ($reservable_now_order,$reservable_now,$reservable_future_order,
  316:                         $reservable_future) = 
  317:                         &Apache::loncommon::get_future_slots($cnum,$cdom,$now,$symb);
  318:                     if ((ref($reservable_now_order) eq 'ARRAY') && (ref($reservable_now) eq 'HASH')) {
  319:                         if (@{$reservable_now_order} > 0) {
  320:                             $slotstatus = 'RESERVABLE';
  321:                             $datemsg = $reservable_now->{$reservable_now_order->[-1]}{'endreserve'};
  322:                         }
  323:                     }
  324:                     unless ($slotstatus eq 'RESERVABLE') {
  325:                         if ((ref($reservable_future_order) eq 'ARRAY') && (ref($reservable_future) eq 'HASH')) {
  326:                             if (@{$reservable_future_order} > 0) {
  327:                                 $slotstatus = 'RESERVABLE_LATER';
  328:                                 $datemsg = $reservable_future->{$reservable_future_order->[0]}{'startreserve'};
  329:                             }
  330:                         }
  331:                     }
  332:                 }
  333:             }
  334:         }
  335:         return ($slotstatus,$datemsg);
  336:     }
  337: 
  338:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
  339: 	&& $checkedin ) {
  340: 
  341: 	if ($got_grade) {
  342: 	    return ('SHOW_ANSWER');
  343: 	} else {
  344: 	    return ('WAITING_FOR_GRADE');
  345: 	}
  346: 
  347:     }
  348: 
  349:     if ( $is_correct) {
  350: 	if ($type eq 'problem') {
  351: 	    return ($status);
  352: 	}
  353: 	return ('SHOW_ANSWER');
  354:     }
  355: 
  356:     if ( $status eq 'CANNOT_ANSWER' && 
  357: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
  358: 	return ($status,$datemsg);
  359:     }
  360: 
  361:     return ($slotstatus,$datemsg,$slot_name,$returned_slot);
  362: }
  363: 
  364: # JB, 9/24/2002: Any changes in this function may require a change
  365: # in lonnavmaps::resource::getDateStatus.
  366: sub check_access {
  367:     my ($id) = @_;
  368:     my $date ='';
  369:     my $status;
  370:     my $datemsg = '';
  371:     my $lastdate = '';
  372:     my $type;
  373:     my $passed;
  374: 
  375:     if ($env{'request.state'} eq "construct") {
  376: 	if ($env{'form.problemstate'}) {
  377: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
  378: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
  379: 			&& &hide_problem_status())) {
  380: 		    return ('CANNOT_ANSWER',
  381: 			    &mt('is in this state due to author settings.'));
  382: 		}
  383: 	    } else {
  384: 		return ($env{'form.problemstate'},
  385: 			&mt('is in this state due to author settings.'));
  386: 	    }
  387: 	}
  388: 	&Apache::lonxml::debug("in construction ignoring dates");
  389: 	$status='CAN_ANSWER';
  390: 	$datemsg=&mt('is in under construction');
  391: #	return ($status,$datemsg);
  392:     }
  393: 
  394:     &Apache::lonxml::debug("checking for part :$id:");
  395:     &Apache::lonxml::debug("time:".time);
  396: 
  397:     my ($symb)=&Apache::lonnet::whichuser();
  398:     &Apache::lonxml::debug("symb:".$symb);
  399:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
  400:     if ($env{'request.state'} ne "construct") {
  401:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc");
  402: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
  403: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
  404: 	    $status='INVALID_ACCESS';
  405: 	    $date=&mt("can not be accessed from your location.");
  406: 	    return($status,$date);
  407: 	}
  408: 	if ($env{'form.grade_imsexport'}) {
  409:             if (($env{'request.course.id'}) && 
  410:                 (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
  411:                 return ('SHOW_ANSWER');
  412:             }
  413:         }
  414: 	foreach my $temp ("opendate","duedate","answerdate") {
  415: 	    $lastdate = $date;
  416: 	    if ($temp eq 'duedate') {
  417: 		$date = &due_date($id);
  418: 	    } else {
  419: 		$date = &Apache::lonnet::EXT("resource.$id.$temp");
  420: 	    }
  421: 	    
  422: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
  423: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
  424: 		$date     =~ /^(con_lost|no_such_host)/) {
  425: 		$status='UNAVAILABLE';
  426: 		$date=&mt("may open later.");
  427: 		return($status,$date);
  428: 	    }
  429: 	    if ($thistype eq 'date_interval') {
  430: 		if ($temp eq 'opendate') {
  431: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
  432: 		}
  433: 		if ($temp eq 'answerdate') {
  434: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
  435: 		}
  436: 	    }
  437: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
  438: 	    if ($date eq '') {
  439: 		$date = &mt("an unknown date"); $passed = 0;
  440: 	    } elsif ($date eq 'con_lost') {
  441: 		$date = &mt("an indeterminate date"); $passed = 0;
  442: 	    } else {
  443: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
  444: 		$date = &Apache::lonlocal::locallocaltime($date);
  445: 	    }
  446: 	    if (!$passed) { $type=$temp; last; }
  447: 	}
  448: 	&Apache::lonxml::debug("have :$type:$passed:");
  449: 	if ($passed) {
  450: 	    $status='SHOW_ANSWER';
  451: 	    $datemsg=$date;
  452: 	} elsif ($type eq 'opendate') {
  453: 	    $status='CLOSED';
  454: 	    $datemsg = &mt('will open on [_1]',$date);
  455: 	} elsif ($type eq 'duedate') {
  456: 	    $status='CAN_ANSWER';
  457: 	    $datemsg = &mt('is due at [_1]',$date);
  458: 	} elsif ($type eq 'answerdate') {
  459: 	    $status='CLOSED';
  460: 	    $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
  461:                                $lastdate,$date);
  462: 	}
  463:     }
  464:     if ($status eq 'CAN_ANSWER' ||
  465: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
  466: 	#check #tries, and if correct.
  467: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
  468: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
  469: 	if ( $tries eq '' ) { $tries = '0'; }
  470: 	if ( $maxtries eq '' && 
  471: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
  472: 	$Apache::lonhomework::results{'resource.'.$id.'.maxtries'}=$maxtries;
  473: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
  474: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
  475: 	if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
  476: 	      && (&show_problem_status()) ) {
  477:             if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
  478:                 (&Apache::lonnet::EXT("resource.$id.retrypartial") !~/^1|on|yes$/i)) {
  479: 	        $status = 'CANNOT_ANSWER';
  480:             }
  481:         } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
  482: 	    $status = 'CANNOT_ANSWER';
  483: 	}
  484: 	if ($status eq 'CANNOT_ANSWER'
  485: 	    && &show_answer_problem_status()) {
  486: 	    $status = 'SHOW_ANSWER';
  487: 	}
  488:     }
  489:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
  490: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval");
  491: 	&Apache::lonxml::debug("looking for interval @interval");
  492: 	if ($interval[0]) {
  493: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1]);
  494: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
  495: 	    if (!$first_access) {
  496: 		$status='NOT_YET_VIEWED';
  497: 		my $due_date = &due_date($id);
  498: 		my $seconds_left = $due_date - time;
  499: 		if ($seconds_left > $interval[0] || $due_date eq '') {
  500: 		    $seconds_left = $interval[0];
  501: 		}
  502: 		$datemsg=&seconds_to_human_length($seconds_left);
  503: 	    }
  504: 	}
  505:     }
  506: 
  507:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
  508:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
  509:   #    return ('UNCHECKEDOUT','needs to be checked out');
  510:   #}
  511: 
  512:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
  513:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
  514: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
  515: 	$status='CAN_ANSWER';
  516: 	$datemsg=&mt('is closed but you are allowed to view it');
  517:     }
  518: 
  519:     return ($status,$datemsg);
  520: }
  521: # this should work exactly like the copy in lonnavmaps.pm
  522: sub due_date {
  523:     my ($part_id,$symb,$udom,$uname)=@_;
  524:     my $date;
  525:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
  526: 				       $udom,$uname);
  527:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
  528:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
  529: 				       $udom,$uname);
  530:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
  531:     if ($interval[0] =~ /\d+/) {
  532: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
  533: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
  534: 	if (defined($first_access)) {
  535: 	    my $interval = $first_access+$interval[0];
  536: 	    $date = (!$due_date || $interval < $due_date) ? $interval
  537:                                                           : $due_date;
  538: 	} else {
  539: 	    $date = $due_date;
  540: 	}
  541:     } else {
  542: 	$date = $due_date;
  543:     }
  544:     return $date;
  545: }
  546: 
  547: sub seconds_to_human_length {
  548:     my ($length)=@_;
  549: 
  550:     my $seconds=$length%60; $length=int($length/60);
  551:     my $minutes=$length%60; $length=int($length/60);
  552:     my $hours=$length%24;   $length=int($length/24);
  553:     my $days=$length;
  554: 
  555:     my $timestr;
  556:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
  557:     if ($hours > 0) { $timestr.=($timestr?", ":"").
  558: 			  &mt('[quant,_1,hour]',$hours); }
  559:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
  560: 			    &mt('[quant,_1,minute]',$minutes); }
  561:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
  562: 			    &mt('[quant,_1,second]',$seconds); }
  563:     return $timestr;
  564: }
  565: 
  566: sub showhash {
  567:     my (%hash) = @_;
  568:     &showhashsubset(\%hash,'.');
  569:     return '';
  570: }
  571: 
  572: sub showarray {
  573:     my ($array)=@_;
  574:     my $string="(";
  575:     foreach my $elm (@{ $array }) {
  576: 	if (ref($elm) eq 'ARRAY') {
  577: 	    $string.=&showarray($elm);
  578: 	} elsif (ref($elm) eq 'HASH') {
  579: 	    $string.= "HASH --- \n<br />";
  580: 	    $string.= &showhashsubset($elm,'.');
  581: 	} else {
  582: 	    $string.="$elm,"
  583: 	}
  584:     }
  585:     chop($string);
  586:     $string.=")";
  587:     return $string;
  588: }
  589: 
  590: sub showhashsubset {
  591:     my ($hash,$keyre) = @_;
  592:     my $resultkey;
  593:     foreach $resultkey (sort(keys(%$hash))) {
  594: 	if ($resultkey !~ /$keyre/) { next; }
  595: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
  596: 	    &Apache::lonxml::debug("$resultkey ---- ".
  597: 				   &showarray($$hash{$resultkey}));
  598: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
  599: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  600: 	    &showhashsubset($$hash{$resultkey},'.');
  601: 	} else {
  602: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  603: 	}
  604:     }
  605:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
  606:     return '';
  607: }
  608: 
  609: sub setuppermissions {
  610:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
  611:     unless ($Apache::lonhomework::browse eq 'F') {
  612:         $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'}); 
  613:     }
  614:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
  615:     if (! $viewgrades && 
  616: 	exists($env{'request.course.sec'}) && 
  617: 	$env{'request.course.sec'} !~ /^\s*$/) {
  618: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
  619:                                                '/'.$env{'request.course.sec'});
  620:     }
  621:     $Apache::lonhomework::viewgrades = $viewgrades;
  622: 
  623:     if ($Apache::lonhomework::browse eq 'F' && 
  624: 	$env{'form.devalidatecourseresdata'} eq 'on') {
  625: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
  626: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
  627: 					      $env{"course.$courseid.domain"});
  628:     }
  629: 
  630:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
  631:     if (! $modifygrades && 
  632: 	exists($env{'request.course.sec'}) && 
  633: 	$env{'request.course.sec'} !~ /^\s*$/) {
  634: 	$modifygrades = 
  635: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
  636: 				     '/'.$env{'request.course.sec'});
  637:     }
  638:     $Apache::lonhomework::modifygrades = $modifygrades;
  639: 
  640:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
  641:     if (! $queuegrade && 
  642: 	exists($env{'request.course.sec'}) && 
  643: 	$env{'request.course.sec'} !~ /^\s*$/) {
  644: 	$queuegrade = 
  645: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
  646: 				     '/'.$env{'request.course.sec'});
  647:     }
  648:     $Apache::lonhomework::queuegrade = $queuegrade;
  649:     return '';
  650: }
  651: 
  652: sub unset_permissions {
  653:     undef($Apache::lonhomework::queuegrade);
  654:     undef($Apache::lonhomework::modifygrades);
  655:     undef($Apache::lonhomework::viewgrades);
  656:     undef($Apache::lonhomework::browse);
  657: }
  658: 
  659: sub setupheader {
  660:     my $request=$_[0];
  661:     &Apache::loncommon::content_type($request,'text/html');
  662:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
  663: 	&Apache::loncommon::no_cache($request);
  664:     }
  665: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
  666: #							  'lastrevisiondate'));
  667:     $request->send_http_header;
  668:     return OK if $request->header_only;
  669:     return ''
  670: }
  671: 
  672: sub handle_save_or_undo {
  673:     my ($request,$problem,$result,$getobjref) = @_;
  674: 
  675:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
  676:     my $filebak =$file.".bak";
  677:     my $filetmp =$file.".tmp";
  678:     my $error=0;
  679:     if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
  680: 	my $error=0;
  681: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
  682: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
  683: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
  684: 	if (!$error) {
  685: 	    &Apache::lonxml::info("<p><b>".
  686: 				  &mt("Undid changes, Switched [_1] and [_2]",
  687: 				      '<span class="LC_filename">'.$filebak.
  688: 				      '</span>',
  689: 				      '<span class="LC_filename">'.$file.
  690: 				      '</span>')."</b></p>");
  691: 	} else {
  692: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
  693: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
  694: 				      '<span class="LC_filename">'.
  695: 				      $filebak.'</span>',
  696: 				      '<span class="LC_filename">'.
  697: 				      $file.'</span>')."</span></p>");
  698: 	    $error=1;
  699: 	}
  700:     } else {
  701:         &Apache::lonnet::correct_line_ends($result);
  702: 
  703: 	my $fs=Apache::File->new(">$filebak");
  704: 	if (defined($fs)) {
  705: 	    print $fs $$problem;
  706: 	} else {
  707: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
  708: 				  &mt("Unable to make backup [_1]",
  709: 				      '<span class="LC_filename">'.
  710: 				      $filebak.'</span>')."</span>");
  711: 	    $error=2;
  712: 	}
  713: 	my $fh=Apache::File->new(">$file");
  714: 	if (defined($fh)) {
  715: 	    print $fh $$result;
  716:             if (ref($getobjref) eq 'SCALAR') {
  717:                 if ($file =~ m{([^/]+)\.(html?)$}) {
  718:                     my $fname = $1;
  719:                     my $ext = $2;
  720:                     my $path = $file;
  721:                     $path =~ s/\Q$fname\E\.\Q$ext\E$//; 
  722:                     my (%allfiles,%codebase);
  723:                     &Apache::lonnet::extract_embedded_items($file,\%allfiles,
  724:                                                            \%codebase,$result);
  725:                     if (keys(%allfiles) > 0) {
  726:                         my $url = $request->uri;
  727:                         my $state = <<STATE;
  728:     <input type="hidden" name="action" value="upload_embedded" />
  729:     <input type="hidden" name="url" value="$url" />
  730: STATE
  731:                         $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
  732:                                       "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
  733:                                       "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
  734:                                       &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
  735:                                       {'error_on_invalid_names'   => 1,
  736:                                        'ignore_remote_references' => 1,});
  737:                     }
  738:                 }
  739:             }
  740: 	} else {
  741: 	    &Apache::lonxml::info('<span class="LC_error">'.
  742: 				  &mt("Unable to write to [_1]",
  743: 				      '<span class="LC_filename">'.
  744: 				      $file.'</span>').
  745: 				  '</span>');
  746: 	    $error|=4;
  747: 	}
  748:     }
  749:     return $error;
  750: }
  751: 
  752: sub analyze_header {
  753:     my ($request) = @_;
  754:     my $js = &Apache::structuretags::setmode_javascript();
  755: 
  756:     # Breadcrumbs
  757:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
  758:                    'text' => 'Authoring Space'},
  759:                   {'href' => '',
  760:                    'text' => 'Problem Testing'},
  761:                   {'href' => '',
  762:                    'text' => 'Analyzing a problem'}];
  763: 
  764:     my $result =
  765:         &Apache::loncommon::start_page('Analyzing a problem',
  766:                                        $js,
  767:                                        {'bread_crumbs' => $brcrum,})
  768:        .&Apache::loncommon::head_subbox(
  769:                 &Apache::loncommon::CSTR_pageheader());
  770:     $result .= 
  771: 	    '<form name="lonhomework" method="post" action="'.
  772: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
  773:             '<input type="hidden" name="problemmode" value="'.
  774:             $env{'form.problemmode'}.'" />'.
  775: 	    &Apache::structuretags::remember_problem_state().'
  776:             <div class="LC_edit_problem_analyze_header">
  777:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
  778:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
  779:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
  780:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
  781:             <hr />
  782:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
  783:             'onclick="javascript:setmode(this.form,'."'view'".')" />
  784:             <hr />
  785:             </div>'
  786:             .&Apache::lonxml::message_location().
  787:             '</form>';
  788:     &Apache::lonxml::add_messages(\$result);
  789:     $request->print($result);
  790:     $request->rflush();
  791: }
  792: 
  793: sub analyze_footer {
  794:     my ($request) = @_;
  795:     $request->print(&Apache::loncommon::end_page());
  796:     $request->rflush();
  797: }
  798: 
  799: sub analyze {
  800:     my ($request,$file) = @_;
  801:     &Apache::lonxml::debug("Analyze");
  802:     my $result;
  803:     my %overall;
  804:     my %seedexample;
  805:     my %allparts;
  806:     my $rndseed=$env{'form.rndseed'};
  807:     &analyze_header($request);
  808:     my %prog_state=
  809: 	&Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
  810:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
  811: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
  812: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
  813:         my $thisseed=$i+$rndseed;
  814: 	my $subresult=&Apache::lonnet::ssi($request->uri,
  815: 					   ('grade_target' => 'analyze'),
  816: 					   ('rndseed' => $thisseed));
  817: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
  818: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  819: 	my @parts;
  820:         if (ref($analyze{'parts'}) eq 'ARRAY') {
  821: 	    @parts=@{ $analyze{'parts'} };
  822: 	}
  823: 	foreach my $part (@parts) {
  824: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
  825: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
  826: 		$analyze{$part.'.type'} eq 'stringresponse'	||
  827: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
  828: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
  829: 		    my $i=0;
  830: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
  831: 			push( @{ $overall{$part.'.answer'}[$i] },
  832: 			      $answer_part);
  833: 			my $concatanswer= join("\0",@{ $answer_part });
  834: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
  835: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
  836: 			}
  837: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
  838: 			    $thisseed;
  839: 			$i++;
  840: 		    }
  841: 		}
  842: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
  843: 		    my $answer_part = 
  844: 			['<span class="LC_error">'.&mt('Error').'</span>'];
  845: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
  846: 			$thisseed;
  847: 		    push( @{ $overall{$part.'.answer'}[0] },
  848: 			  $answer_part);
  849: 		}
  850: 	    }
  851: 	}
  852:     }
  853:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
  854:     $request->print('<hr />'
  855:                    .'<h3>'
  856:                    .&mt('List of possible answers')
  857:                    .'</h3>'
  858:     );
  859:     foreach my $part (sort(keys(%allparts))) {
  860:         if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
  861:             (@{$overall{$part.'.answer'}} > 0)) {
  862: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
  863: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
  864:                 $request->print(&Apache::loncommon::start_data_table()
  865:                                .&Apache::loncommon::start_data_table_header_row()
  866:                                .'<th colspan="'.($num_cols+1).'">'
  867:                                .&mt('Part').' '.$part
  868:                 );
  869: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
  870: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
  871: 		}
  872: 		$request->print('</th>'
  873:                                .&Apache::loncommon::end_data_table_header_row()
  874:                 );
  875: 		my %frequency;
  876: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
  877: 		    $frequency{join("\0",@{ $answer })}++;
  878: 		}
  879:                 $request->print(&Apache::loncommon::start_data_table_header_row()
  880:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
  881:                                .'<th>'.&mt('Frequency').'<br />'
  882:                                .'('.&mt('click for example').')</th>'
  883:                                .&Apache::loncommon::end_data_table_header_row()
  884:                 );
  885: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
  886:                     $request->print(&Apache::loncommon::start_data_table_row()
  887:                                    .'<td>'
  888:                                    .join('</td><td>',split("\0",$answer))
  889: 				   .'</td>'
  890:                                    .'<td>'
  891:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
  892: 				   .'</td>'
  893:                                    .&Apache::loncommon::end_data_table_row()
  894:                     );
  895: 		}
  896:                 $request->print(&Apache::loncommon::end_data_table());
  897: 	    }
  898: 	} else {
  899:             $request->print('<p class="LC_warning">'
  900:                            .&mt('Response [_1] is not analyzable at this time.',$part)
  901: 			   .'</p>'
  902:             );
  903: 	}
  904:     }
  905:     if (scalar(keys(%allparts)) == 0 ) {
  906:         $request->print('<p class="LC_warning">'
  907:                        .&mt('Found no analyzable responses in this problem.'
  908:                            .' Currently only Numerical, Formula and String response styles are supported.')
  909:                        .'</p>'
  910:         );
  911:     }
  912:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
  913:     &analyze_footer($request);
  914:     &Apache::lonhomework::showhash(%overall);
  915:     return $result;
  916: }
  917: 
  918: {
  919:     my $show_problem_status;
  920:     sub reset_show_problem_status {
  921: 	undef($show_problem_status);
  922:     }
  923: 
  924:     sub set_show_problem_status {
  925: 	my ($new_status) = @_;
  926: 	$show_problem_status = lc($new_status);
  927:     }
  928: 
  929:     sub hide_problem_status {
  930: 	return ($show_problem_status eq 'no'
  931: 		|| $show_problem_status eq 'no_feedback_ever');
  932:     }
  933: 
  934:     sub show_problem_status {
  935: 	return ($show_problem_status eq 'yes'
  936: 		|| $show_problem_status eq 'answer'
  937: 		|| $show_problem_status eq '');
  938:     }
  939:     
  940:     sub show_some_problem_status {
  941: 	return ($show_problem_status eq 'no');
  942:     }
  943: 
  944:     sub show_no_problem_status {
  945: 	return ($show_problem_status eq 'no_feedback_ever');
  946:     }
  947:   
  948:     sub show_answer_problem_status {
  949: 	return ($show_problem_status eq 'answer');
  950:     }
  951: }
  952: 
  953: sub editxmlmode {
  954:     my ($request,$file) = @_;
  955:     my $result;
  956:     my $problem=&Apache::lonnet::getfile($file);
  957:     if ($problem eq -1) {
  958: 	&Apache::lonxml::error(
  959:             '<p class="LC_error">'
  960:            .&mt('Unable to find [_1]',
  961:                 '<span class="LC_filename">'.$file.'</span>')
  962:            .'</p>');
  963: 
  964: 	$problem='';
  965:     }
  966:     if (($env{'form.problemmode'} eq 'saveeditxml') ||
  967:         ($env{'form.problemmode'} eq 'saveviewxml') ||
  968:         ($env{'form.problemmode'} eq 'undoxml')) {
  969: 	my $error=&handle_save_or_undo($request,\$problem,
  970: 				       \$env{'form.editxmltext'});
  971: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
  972:     }
  973:     &Apache::lonhomework::showhashsubset(\%env,'^form');
  974:     if ($env{'form.problemmode'} eq 'saveviewxml') {
  975: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
  976: 	$env{'form.problemmode'}='view';
  977: 	&renderpage($request,$file);
  978:     } else {
  979: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
  980: 	if ($cols > 80) { $cols = 80; }
  981: 	if ($cols < 70) { $cols = 70; }
  982: 	if ($rows < 20) { $rows = 20; }
  983: 	my $js =
  984: 	    &Apache::edit::js_change_detection(). 
  985: 	    &Apache::loncommon::resize_textarea_js().
  986:             &Apache::structuretags::setmode_javascript().
  987:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
  988: 
  989:     # Breadcrumbs
  990:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
  991:                    'text' => 'Authoring Space'},
  992:                   {'href' => '',
  993:                    'text' => 'Problem Editing'}];
  994: 
  995: 	my $start_page = 
  996: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
  997: 					   {'no_auto_mt_title' => 1,
  998: 					    'only_body'        => 0,
  999: 					    'add_entries'      => {
 1000: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
 1001: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
 1002:                                                                   },
 1003:                                                 'bread_crumbs' => $brcrum,
 1004:                                              });
 1005: 
 1006:     $result=$start_page
 1007:            .&Apache::loncommon::head_subbox(
 1008:                 &Apache::loncommon::CSTR_pageheader());
 1009: 	$result.=&renderpage($request,$file,['no_output_web'],1).
 1010:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
 1011: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
 1012: 	    &Apache::structuretags::remember_problem_state().'
 1013:             <div class="LC_edit_problem_header">
 1014:               <div class="LC_edit_problem_header_title">'.
 1015:                 &mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').
 1016:               '</div><div class="LC_edit_actionbar" id="actionbar">';
 1017: 
 1018:         $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
 1019:                   &Apache::structuretags::problem_actionbar_buttons('editxml');
 1020:         $result.='<div class="LC_edit_problem_discards">';
 1021: 
 1022: 		unless ($env{'environment.nocodemirror'}) {
 1023: 		# dropdown menues
 1024:     		$result .= '<ol class="LC_primary_menu LC_floatleft">'.
 1025:     		&Apache::lonmenu::create_submenu("#", "", &mt("Insert Menu"), &Apache::structuretags::insert_menu_datastructure(),"").'</ol>';
 1026: 		}
 1027:     $result .= '<ol class="LC_primary_menu LC_floatleft">'.
 1028:     Apache::lonmenu::create_submenu("#", "", &mt("Help"), &Apache::structuretags::helpmenu_datastructure(),"").'</ol>';
 1029:     $result.="</div>";
 1030:          
 1031:          $result.='<hr style="clear:both;visibility:hidden" /></div></div>'.&Apache::lonxml::message_location().
 1032:                   &Apache::loncommon::xmleditor_js().
 1033: 		  '<textarea '.&Apache::edit::element_change_detection().
 1034: 	              ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" '.
 1035: 		      ' name="editxmltext" id="LC_editxmltext">'.
 1036: 		      &HTML::Entities::encode($problem,'<>&"').'</textarea>
 1037:             <div id="LC_aftertextarea">
 1038:             </div>
 1039: 	        </form>';
 1040: 	    my $resource = $env{'request.ambiguous'};
 1041: 	    unless($env{'environment.nocodemirror'}){
 1042: 	        
 1043: 	        $result .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined-xml.css">
 1044: 	        <script src="/adm/codemirror/codemirror-compressed-xml.js"></script>
 1045: 	        <script>
 1046: 	            CodeMirror.defineMode("mixedmode", function(config) {
 1047: 	                return CodeMirror.multiplexingMode(
 1048: 	                    CodeMirror.getMode(config, "xml"),
 1049: 	                    {
 1050: 	                        open: "\<script type=\"loncapa/perl\"\>", close: "\</script\>",
 1051: 	                        mode: CodeMirror.getMode(config, "perl"),
 1052: 	                        delimStyle: "tag",
 1053: 	                    }
 1054: 	              );
 1055: 	            });
 1056: 	            var cm = CodeMirror.fromTextArea(document.getElementById("LC_editxmltext"),
 1057: 	            {
 1058: 	                mode: "mixedmode",
 1059: 	                lineWrapping: true,
 1060: 	                lineNumbers: true,
 1061: 	                tabSize: 4,
 1062: 	                indentUnit: 4,
 1063: 
 1064: 	                autoCloseTags: true,
 1065: 	                autoCloseBrackets: true,
 1066: 	                height: "auto",
 1067: 	                styleActiveLine: true,
 1068: 	                
 1069: 	                extraKeys: {
 1070: 	                    "Tab": "indentMore",
 1071: 	                    "Shift-Tab": "indentLess",
 1072: 	                }
 1073: 	            });
 1074: 	            restoreScrollPosition("'.$resource.'");
 1075: 	        </script>';
 1076: 	    }
 1077:         $result .= &Apache::loncommon::end_page();
 1078:         &Apache::lonxml::add_messages(\$result);
 1079:         $request->print($result);
 1080:     }
 1081:     return '';
 1082: }
 1083: 
 1084: #
 1085: #    Render the page in whatever target desired.
 1086: #
 1087: sub renderpage {
 1088:     my ($request,$file,$targets,$return_string) = @_;
 1089: 
 1090:     my @targets = @{$targets || [&get_target()]};
 1091:     &Apache::lonhomework::showhashsubset(\%env,'form.');
 1092:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
 1093: 
 1094:     my $overall_result;
 1095:     foreach my $target (@targets) {
 1096: 	# FIXME need to do something intelligent when a problem goes
 1097:         # from viewable to not viewable due to map conditions
 1098: 	#&setuppermissions();
 1099: 	#if (   $Apache::lonhomework::browse ne '2'
 1100: 	#    && $Apache::lonhomework::browse ne 'F' ) {
 1101: 	#    $request->print(" You most likely shouldn't see me.");
 1102: 	#}
 1103: 	#my $t0 = [&gettimeofday()];
 1104: 	my $output=1;
 1105: 	if ($target eq 'no_output_web') {
 1106: 	    $target = 'web'; $output=0;
 1107: 	}
 1108: 	my $problem=&Apache::lonnet::getfile($file);
 1109: 	my $result;
 1110: 	if ($problem eq -1) {
 1111: 	    $problem='';
 1112: 	    my $filename=(split('/',$file))[-1];
 1113: 	    my $error =
 1114: 		'<p class="LC_error">'
 1115:                .&mt('Unable to find [_1]',
 1116: 			   '<span class="LC_filename">'.$filename.'</span>')
 1117: 		."</p>";
 1118: 	    $result.=
 1119: 		&Apache::loncommon::simple_error_page($request,'Not available',
 1120: 						      $error,{'no_auto_mt_msg' => 1});
 1121: 	    return;
 1122: 	}
 1123: 
 1124: 	my %mystyle;
 1125: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
 1126: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
 1127: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
 1128: 
 1129: 	&Apache::lonxml::debug("Should be parsing now");
 1130: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
 1131: 					     &setup_vars($target),%mystyle);
 1132: 	&finished_parsing();
 1133: 	if (!$output) { $result = ''; }
 1134: 	#$request->print("Result follows:");
 1135: 	if ($target eq 'modified') {
 1136: 	    &handle_save_or_undo($request,\$problem,\$result);
 1137: 	} else {
 1138: 	    if ($target eq 'analyze') {
 1139: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
 1140: 		undef(%Apache::lonhomework::analyze);
 1141: 	    }
 1142: 	    #my $td=&tv_interval($t0);
 1143: 	    #if ( $Apache::lonxml::debug) {
 1144: 	    #$result =~ s:</body>::;
 1145: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
 1146: 	    #}
 1147: #	    $request->print($result);
 1148: 	    $overall_result.=$result;
 1149: #	    $request->rflush();
 1150: 	}
 1151: 	#$request->print(":Result ends");
 1152: 	#my $td=&tv_interval($t0);
 1153:     }
 1154:     if (!$return_string) {
 1155: 	&Apache::lonxml::add_messages(\$overall_result);
 1156: 	$request->print($overall_result);   
 1157: 	$request->rflush();   
 1158:     } else {
 1159: 	return $overall_result;
 1160:     }
 1161: }
 1162: 
 1163: sub finished_parsing {
 1164:     undef($Apache::lonhomework::parsing_a_problem);
 1165:     undef($Apache::lonhomework::parsing_a_task);
 1166: }
 1167: 
 1168: # function extracted from get_template_html
 1169: # returns "key" -> list
 1170: # key: path of template
 1171: # value 1: title
 1172: # value 2: category
 1173: # value 3: name of help topic ???
 1174: sub get_template_list{
 1175:     my ($extension) = @_;
 1176:     
 1177:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
 1178:                      '/templates/*.'.$extension);
 1179:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
 1180:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
 1181:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
 1182:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
 1183:     return @files;
 1184: }
 1185: 
 1186: sub get_template_html {
 1187:     my ($extension) = @_;
 1188:     my $result;
 1189:     my @allnames;
 1190:     &Apache::lonxml::debug("Looking for :$extension:");
 1191:     my $glob_extension  = $extension;
 1192:     if ($extension eq 'survey' || $extension eq 'exam') {
 1193: 	$glob_extension = 'problem';
 1194:     }
 1195:     my @files = &get_template_list($extension);
 1196:     my ($midpoint,$seconddiv,$numfiles);
 1197:     my @noexamplelink = ('blank.problem','blank.library','script.library');
 1198:     $numfiles = 0;
 1199:     foreach my $file (@files) {
 1200:         next if ($file->[1] !~ /\S/);
 1201:         $numfiles ++;
 1202:     }
 1203:     if ($numfiles > 0) {
 1204:         $result = '<div class="LC_left_float">';
 1205:         $midpoint = int($numfiles/2);
 1206:         if ($numfiles%2) {
 1207:             $midpoint ++;
 1208:         }
 1209:     }
 1210:     my $count = 0;
 1211:     my $currentcategory='';
 1212:     my $first = 1;
 1213:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1214:     foreach my $file (@files) {
 1215: 	next if ($file->[1] !~ /\S/);
 1216:         if ($file->[2] ne $currentcategory) {
 1217:            $currentcategory=$file->[2];
 1218:            if ((!$seconddiv) && ($count >= $midpoint)) {
 1219:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
 1220:                $seconddiv = 1;
 1221:            } elsif (!$first) {
 1222:                $result.='</div>'."\n";
 1223:            } else {
 1224:                $first = 0;
 1225:            }
 1226:            $result.= '<div class="LC_Box">'."\n"
 1227:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
 1228:            $count++;
 1229:         }
 1230: 	$result .=
 1231: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
 1232: 	    $file->[1].'</label>';
 1233:         if ($file->[3]) {
 1234:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
 1235:         }
 1236:         # Provide example link
 1237:         my $filename=$file->[0];
 1238:         $filename=~s{^\Q$londocroot\E}{};
 1239:         if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
 1240:             $result .= ' <span class="LC_fontsize_small">'
 1241:                       .&Apache::loncommon::modal_link(
 1242:                            $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
 1243:                       .'</span>';
 1244:         }
 1245:         $result .= '<br />'."\n";
 1246:         $count ++;
 1247:     }
 1248:     if ($numfiles > 0) {
 1249:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
 1250:     }
 1251:     return $result;
 1252: }
 1253: 
 1254: sub newproblem {
 1255:     my ($request) = @_;
 1256: 
 1257: 	if ($env{'form.mode'} eq 'blank'){
 1258:         my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1259:         &File::Copy::copy('/home/httpd/html/res/adm/includes/templates/blank.problem',$dest);
 1260:         &renderpage($request,$dest);
 1261:         return;
 1262:     }
 1263:     if ($env{'form.template'}) {
 1264: 	my $file = $env{'form.template'};
 1265: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1266: 	&File::Copy::copy($file,$dest);
 1267: 	&renderpage($request,$dest);
 1268: 	return;
 1269:     }
 1270: 
 1271:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
 1272:     &Apache::lonxml::debug("Looking for :$extension:");
 1273:     my $templatelist=&get_template_html($extension);
 1274:     if ($env{'form.newfile'} && !$templatelist) {
 1275: 	# no templates found
 1276: 	my $templatefilename =
 1277: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
 1278: 	&Apache::lonxml::debug("$templatefilename");
 1279: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1280: 	&File::Copy::copy($templatefilename,$dest);
 1281: 	&renderpage($request,$dest);
 1282:     } else {
 1283: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
 1284: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1285: 	my $errormsg;
 1286: 	my $instructions;
 1287:         my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
 1288:                        'text' => 'Authoring Space'},
 1289:                       {'href' => '',
 1290:                        'text' => "Create New $extension"}];
 1291: 	my $start_page = 
 1292:             &Apache::loncommon::start_page("Create New $extension",
 1293:                                            undef,
 1294:                                            {'bread_crumbs' => $brcrum,});
 1295: 	$request->print(
 1296:         $start_page
 1297:        .&Apache::loncommon::head_subbox(
 1298:                 &Apache::loncommon::CSTR_pageheader())
 1299:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
 1300: $errormsg
 1301: ".&mt("The requested file [_1] currently does not exist.",
 1302:       '<span class="LC_filename">'.$url.'</span>').'
 1303: <p class="LC_info">
 1304: '.&mt("To create a new $extension, select a template from the".
 1305:       " list below. Then click on the \"Create $extension\" button.").'
 1306: </p><div><form action="'.$url.'" method="post">');
 1307: 
 1308: 	if (defined($templatelist)) {
 1309: 	    $request->print($templatelist);
 1310: 	}
 1311: 	$request->print('<br /><input type="submit" name="newfile" value="'.
 1312: 			&mt("Create $extension").'" />');
 1313: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
 1314:     }
 1315:     return;
 1316: }
 1317: 
 1318: sub update_construct_style {
 1319:     if ($env{'request.state'} eq "construct"
 1320: 	&& $env{'form.problemmode'} eq 'view' 
 1321: 	&&  defined($env{'form.submitted'})
 1322: 	&& !defined($env{'form.resetdata'})
 1323: 	&& !defined($env{'form.newrandomization'})) {
 1324: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
 1325: 	    ||$env{'form.clear_style_file'}) {
 1326: 	    &Apache::lonnet::delenv('construct.style');
 1327: 	} elsif ($env{'form.style_file'} 
 1328: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
 1329: 	    &Apache::lonnet::appenv({'construct.style' => 
 1330: 				        $env{'form.style_file'}});
 1331: 	}
 1332:     }
 1333: }
 1334: 
 1335: 
 1336: sub handler {
 1337:     #my $t0 = [&gettimeofday()];
 1338:     my $request=$_[0];
 1339:     $Apache::lonxml::request=$request;
 1340:     $Apache::lonxml::debug=$env{'user.debug'};
 1341:     $env{'request.uri'}=$request->uri;
 1342:     &setuppermissions();
 1343: 
 1344:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1345: 
 1346:     #check if we know where we are
 1347:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
 1348: 	# if we are browsing we might not be able to know where we are
 1349: 	if ($Apache::lonhomework::browse ne 'F' && 
 1350: 	    $env{'request.state'} ne "construct") {
 1351: 	    #should know where we are, so ask
 1352: 	    &unset_permissions();
 1353: 	    $request->internal_redirect('/adm/ambiguous');
 1354: 	    return OK;
 1355: 	}
 1356:     }
 1357:     if (&setupheader($request)) {
 1358: 	&unset_permissions();
 1359: 	return OK;
 1360:     }
 1361:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
 1362:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
 1363:     my ($symb) = &Apache::lonnet::whichuser();
 1364:     &Apache::lonxml::debug('symb is '.$symb);
 1365:     if ($env{'request.state'} eq "construct") {
 1366: 	if ( -e $file ) {
 1367: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1368: 						    ['problemmode']);
 1369: 	    if (!(defined $env{'form.problemmode'})) {
 1370: 		#first visit to problem in construction space
 1371: 		$env{'form.problemmode'}= 'view';
 1372: 		&renderpage($request,$file);
 1373: 	    } elsif (($env{'form.problemmode'} eq 'editxml') || 
 1374:                      ($env{'form.problemmode'} eq 'saveeditxml') ||
 1375:                      ($env{'form.problemmode'} eq 'saveviewxml') ||
 1376:                      ($env{'form.problemmode'} eq 'undoxml')) {
 1377: 		&editxmlmode($request,$file);
 1378: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
 1379: 		&analyze($request,$file);
 1380: 	    } else {
 1381: 		&update_construct_style();
 1382: 		&renderpage($request,$file);
 1383: 	    }
 1384: 	} else {
 1385: 		&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1386: 						    ['mode']);
 1387: 	    # requested file doesn't exist in contruction space
 1388: 	    &newproblem($request);
 1389: 	}
 1390:     } else {
 1391: 	# just render the page normally outside of construction space
 1392: 	&Apache::lonxml::debug("not construct");
 1393: 	&renderpage($request,$file);
 1394:     }
 1395:     #my $td=&tv_interval($t0);
 1396:     #&Apache::lonxml::debug("Spent $td seconds processing");
 1397:     # always turn off debug messages
 1398:     $Apache::lonxml::debug=0;
 1399:     &unset_permissions();
 1400:     return OK;
 1401: 
 1402: }
 1403: 
 1404: 1;
 1405: __END__

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