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

1.63      albertel    1: # The LearningOnline Network with CAPA
1.52      albertel    2: # The LON-CAPA Homework handler
1.63      albertel    3: #
1.355   ! damieng     4: # $Id: lonhomework.pm,v 1.354 2015/06/17 03:57:01 musolffc Exp $
1.63      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
1.159     www        27: 
1.1       albertel   28: 
                     29: package Apache::lonhomework;
                     30: use strict;
1.73      albertel   31: use Apache::style();
                     32: use Apache::lonxml();
1.204     albertel   33: use Apache::lonnet;
1.73      albertel   34: use Apache::lonplot();
                     35: use Apache::inputtags();
                     36: use Apache::structuretags();
                     37: use Apache::randomlabel();
                     38: use Apache::response();
                     39: use Apache::hint();
                     40: use Apache::outputtags();
1.83      albertel   41: use Apache::caparesponse();
                     42: use Apache::radiobuttonresponse();
                     43: use Apache::optionresponse();
                     44: use Apache::imageresponse();
                     45: use Apache::essayresponse();
                     46: use Apache::externalresponse();
1.106     albertel   47: use Apache::rankresponse();
1.107     albertel   48: use Apache::matchresponse();
1.137     albertel   49: use Apache::chemresponse();
1.321     www        50: use Apache::functionplotresponse();
1.169     albertel   51: use Apache::drawimage();
1.355   ! damieng    52: use Apache::loncapamath();
1.26      www        53: use Apache::Constants qw(:common);
1.83      albertel   54: use Apache::loncommon();
1.354     musolffc   55: use Apache::lonparmset();
1.146     albertel   56: use Apache::lonlocal;
1.179     albertel   57: use Time::HiRes qw( gettimeofday tv_interval );
1.282     albertel   58: use HTML::Entities();
                     59: use File::Copy();
1.188     foxr       60: 
1.189     albertel   61: # FIXME - improve commenting
1.188     foxr       62: 
1.43      albertel   63: 
1.69      harris41   64: BEGIN {
1.145     albertel   65:     &Apache::lonxml::register_insert();
1.43      albertel   66: }
                     67: 
1.188     foxr       68: 
1.276     foxr       69: =pod
                     70: 
                     71: =item set_bubble_lines()
                     72: 
                     73: Called at analysis time to set the bubble lines
                     74: hash for the problem.. This should be called in the
                     75: end_problemtype tag in analysis mode.
                     76: 
                     77: We fetch the hash of part id counters from lonxml
                     78:     and push them into analyze:{part_id.bubble_lines}.
                     79: 
                     80: =cut
                     81: 
                     82: sub set_bubble_lines {
                     83:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
                     84: 
                     85:     foreach my $key (keys(%bubble_counters)) {
                     86: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
                     87: 	    $bubble_counters{"$key"};
                     88:     }
                     89: }
                     90: 
1.301     jms        91: #
                     92: # Decides what targets to render for.
                     93: # Implicit inputs:
                     94: #   Various session environment variables:
                     95: #      request.state -  published  - is a /res/ resource
                     96: #                       uploaded   - is a /uploaded/ resource
                     97: #                       contruct   - is a /priv/ resource
                     98: #      form.grade_target - a form parameter requesting a specific target
1.5       albertel   99: sub get_target {
1.204     albertel  100:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
                    101:     if( defined($env{'form.grade_target'})) {
                    102: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
1.188     foxr      103:     } else {
1.189     albertel  104: 	&Apache::lonxml::debug("form.grade_target <undefined>");
1.188     foxr      105:     }
1.204     albertel  106:     if (($env{'request.state'} eq "published") ||
                    107: 	($env{'request.state'} eq "uploaded")) {
                    108: 	if ( defined($env{'form.grade_target'}  ) 
                    109: 	     && ($env{'form.grade_target'} eq 'tex')) {
                    110: 	    return ($env{'form.grade_target'});
                    111: 	} elsif ( defined($env{'form.grade_target'}  ) 
1.145     albertel  112: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
1.207     albertel  113: 	    return ($env{'form.grade_target'});
1.244     albertel  114: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
                    115: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
                    116: 	    return ($env{'form.grade_target'});
1.320     raeburn   117: 	} elsif ($env{'form.grade_target'} eq 'answer') {
                    118:             if ($env{'form.answer_output_mode'} eq 'tex') {
                    119:                 return ($env{'form.grade_target'});
                    120:             }
                    121:         }
1.207     albertel  122: 	if ($env{'form.webgrade'} &&
1.244     albertel  123: 	    ($Apache::lonhomework::modifygrades eq 'F'
                    124: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
1.207     albertel  125: 	    return ('grade','webgrade');
1.145     albertel  126: 	}
1.204     albertel  127: 	if ( defined($env{'form.submitted'}) &&
                    128: 	     ( !defined($env{'form.newrandomization'}))) {
1.217     albertel  129: 	    return ('grade', 'web');
1.145     albertel  130: 	} else {
1.217     albertel  131: 	    return ('web');
1.145     albertel  132: 	}
1.204     albertel  133:     } elsif ($env{'request.state'} eq "construct") {
1.323     www       134: #
                    135: # We are in construction space, editing and testing problems
                    136: #
1.204     albertel  137: 	if ( defined($env{'form.grade_target'}) ) {
                    138: 	    return ($env{'form.grade_target'});
1.145     albertel  139: 	}
1.204     albertel  140: 	if ( defined($env{'form.preview'})) {
                    141: 	    if ( defined($env{'form.submitted'})) {
1.323     www       142: #
                    143: # We are doing a problem preview
                    144: #
1.145     albertel  145: 		return ('grade', 'web');
                    146: 	    } else {
                    147: 		return ('web');
                    148: 	    }
                    149: 	} else {
1.267     albertel  150: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
                    151: 		return ('grade','webgrade','answer');
1.324     www       152:             } elsif ($env{'form.problemmode'} eq 'view') {
                    153:                 return ('grade','web','answer');
1.323     www       154: 	    } elsif ($env{'form.problemmode'} eq 'saveview') {
                    155:                 return ('modified','web','answer');
                    156:             } elsif ($env{'form.problemmode'} eq 'discard') {
                    157:                 return ('web','answer');
                    158:             } elsif (($env{'form.problemmode'} eq 'saveedit') ||
                    159:                      ($env{'form.problemmode'} eq 'undo')) {
                    160:                 return ('modified','no_output_web','edit');
                    161:             } elsif ($env{'form.problemmode'} eq 'edit') {
                    162: 		return ('no_output_web','edit');
1.145     albertel  163: 	    } else {
                    164: 		return ('web');
                    165: 	    }
1.323     www       166:         }
                    167: #
1.338     raeburn   168: # End of Authoring Space
1.323     www       169: #
1.15      albertel  170:     }
1.323     www       171: #
                    172: # Huh? We are nowhere, so do nothing.
                    173: #
1.145     albertel  174:     return ();
1.5       albertel  175: }
                    176: 
1.3       albertel  177: sub setup_vars {
1.145     albertel  178:     my ($target) = @_;
                    179:     return ';'
1.11      albertel  180: #  return ';$external::target='.$target.';';
1.2       albertel  181: }
                    182: 
1.200     albertel  183: sub proctor_checked_in {
1.226     albertel  184:     my ($slot_name,$slot,$type)=@_;
                    185:     my @possible_proctors=split(",",$slot->{'proctor'});
                    186:     
1.248     albertel  187:     return 1 if (!@possible_proctors);
                    188: 
1.226     albertel  189:     my $key;
                    190:     if ($type eq 'Task') {
1.230     albertel  191: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
                    192: 	$key ="resource.$version.0.checkedin";
1.226     albertel  193:     } elsif ($type eq 'problem') {
                    194: 	$key ='resource.0.checkedin';
                    195:     }
1.249     albertel  196:     # backward compatability, used to be username@domain, 
                    197:     # now is username:domain
                    198:     my $who = $Apache::lonhomework::history{$key};
                    199:     if ($who !~ /:/) {
                    200: 	$who =~ tr/@/:/;
                    201:     }     
1.226     albertel  202:     foreach my $possible (@possible_proctors) { 
1.249     albertel  203: 	if ($who eq $possible
1.226     albertel  204: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
1.202     albertel  205: 	    return 1;
                    206: 	}
                    207:     }
1.226     albertel  208:     
1.200     albertel  209:     return 0;
                    210: }
                    211: 
1.226     albertel  212: sub check_slot_access {
                    213:     my ($id,$type)=@_;
                    214: 
1.207     albertel  215:     # does it pass normal muster
1.226     albertel  216:     my ($status,$datemsg)=&check_access($id);
                    217:     
1.252     albertel  218:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots");
1.251     albertel  219:     if ($useslots ne 'resource' && $useslots ne 'map' 
                    220: 	&& $useslots ne 'map_map') {
1.226     albertel  221: 	return ($status,$datemsg);
                    222:     }
                    223: 
1.200     albertel  224:     if ($status eq 'SHOW_ANSWER' ||
                    225: 	$status eq 'CLOSED' ||
                    226: 	$status eq 'INVALID_ACCESS' ||
                    227: 	$status eq 'UNAVAILABLE') {
                    228: 	return ($status,$datemsg);
                    229:     }
1.204     albertel  230:     if ($env{'request.state'} eq "construct") {
1.203     albertel  231: 	return ($status,$datemsg);
                    232:     }
1.226     albertel  233:     
                    234:     if ($type eq 'Task') {
                    235: 	my $version=$Apache::lonhomework::history{'resource.version'};
1.230     albertel  236: 	if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
                    237: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
1.226     albertel  238: 	    return ('SHOW_ANSWER');
                    239: 	}
1.207     albertel  240:     }
1.226     albertel  241: 
1.288     raeburn   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));
1.210     albertel  245: 
1.200     albertel  246: #    if (!@slots) {
                    247: #	return ($status,$datemsg);
                    248: #    }
                    249:     my $slotstatus='NOT_IN_A_SLOT';
1.206     albertel  250:     my ($returned_slot,$slot_name);
1.334     raeburn   251:     my $now = time;
                    252:     my $num_usable_slots = 0;
1.210     albertel  253:     foreach my $slot (@slots) {
1.241     albertel  254: 	$slot =~ s/(^\s*|\s*$)//g;
1.201     albertel  255: 	&Apache::lonxml::debug("getting $slot");
1.200     albertel  256: 	my %slot=&Apache::lonnet::get_slot($slot);
1.201     albertel  257: 	&Apache::lonhomework::showhash(%slot);
1.334     raeburn   258:         next if ($slot{'endtime'} < $now);
                    259:         $num_usable_slots ++;
                    260: 	if ($slot{'starttime'} < $now &&
                    261: 	    $slot{'endtime'} > $now &&
1.297     raeburn   262: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
1.202     albertel  263: 	    &Apache::lonxml::debug("$slot is good");
                    264: 	    $slotstatus='NEEDS_CHECKIN';
                    265: 	    $returned_slot=\%slot;
1.206     albertel  266: 	    $slot_name=$slot;
1.200     albertel  267: 	    last;
1.334     raeburn   268:         } 
1.200     albertel  269:     }
1.202     albertel  270:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
1.226     albertel  271: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
1.322     raeburn   272: 	&Apache::lonxml::debug("proctor checked in");
                    273: 	$slotstatus=$status;
1.200     albertel  274:     }
1.226     albertel  275: 
1.235     albertel  276:     my ($is_correct,$got_grade,$checkedin);
1.226     albertel  277:     if ($type eq 'Task') {
1.230     albertel  278: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
1.231     albertel  279: 	$got_grade = 
                    280: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
                    281: 	     =~ /^(?:pass|fail)$/);
1.235     albertel  282: 	$is_correct =  
                    283: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
                    284: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
1.226     albertel  285: 	$checkedin =
1.230     albertel  286: 	    $Apache::lonhomework::history{"resource.$version.0.checkedin"};
1.226     albertel  287:     } elsif ($type eq 'problem') {
1.252     albertel  288: 	$got_grade  = 1;
                    289: 	$checkedin  = $Apache::lonhomework::history{"resource.0.checkedin"};
                    290: 	$is_correct =
                    291: 	    ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
1.226     albertel  292:     }
                    293:     
1.235     albertel  294:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
                    295:     
1.243     albertel  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 
1.236     albertel  300: 	&& !$got_grade) {
                    301: 	return ('WAITING_FOR_GRADE');
                    302:     }
                    303: 
1.309     raeburn   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 - 
1.334     raeburn   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);
1.252     albertel  338:     }
                    339: 
1.226     albertel  340:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
                    341: 	&& $checkedin ) {
                    342: 
1.231     albertel  343: 	if ($got_grade) {
1.209     albertel  344: 	    return ('SHOW_ANSWER');
                    345: 	} else {
                    346: 	    return ('WAITING_FOR_GRADE');
                    347: 	}
1.226     albertel  348: 
1.207     albertel  349:     }
1.255     albertel  350: 
1.235     albertel  351:     if ( $is_correct) {
1.255     albertel  352: 	if ($type eq 'problem') {
                    353: 	    return ($status);
                    354: 	}
1.235     albertel  355: 	return ('SHOW_ANSWER');
                    356:     }
1.255     albertel  357: 
1.225     albertel  358:     if ( $status eq 'CANNOT_ANSWER' && 
                    359: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
                    360: 	return ($status,$datemsg);
                    361:     }
                    362: 
1.206     albertel  363:     return ($slotstatus,$datemsg,$slot_name,$returned_slot);
1.198     albertel  364: }
1.200     albertel  365: 
1.301     jms       366: # JB, 9/24/2002: Any changes in this function may require a change
                    367: # in lonnavmaps::resource::getDateStatus.
1.53      www       368: sub check_access {
1.145     albertel  369:     my ($id) = @_;
                    370:     my $date ='';
                    371:     my $status;
                    372:     my $datemsg = '';
                    373:     my $lastdate = '';
                    374:     my $type;
                    375:     my $passed;
                    376: 
1.204     albertel  377:     if ($env{'request.state'} eq "construct") {
                    378: 	if ($env{'form.problemstate'}) {
                    379: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
1.277     albertel  380: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
                    381: 			&& &hide_problem_status())) {
1.168     albertel  382: 		    return ('CANNOT_ANSWER',
1.174     www       383: 			    &mt('is in this state due to author settings.'));
1.167     albertel  384: 		}
1.165     albertel  385: 	    } else {
1.204     albertel  386: 		return ($env{'form.problemstate'},
1.174     www       387: 			&mt('is in this state due to author settings.'));
1.165     albertel  388: 	    }
                    389: 	}
1.145     albertel  390: 	&Apache::lonxml::debug("in construction ignoring dates");
                    391: 	$status='CAN_ANSWER';
1.146     albertel  392: 	$datemsg=&mt('is in under construction');
1.163     albertel  393: #	return ($status,$datemsg);
1.145     albertel  394:     }
                    395: 
                    396:     &Apache::lonxml::debug("checking for part :$id:");
                    397:     &Apache::lonxml::debug("time:".time);
1.152     albertel  398: 
1.261     albertel  399:     my ($symb)=&Apache::lonnet::whichuser();
1.212     albertel  400:     &Apache::lonxml::debug("symb:".$symb);
                    401:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
1.204     albertel  402:     if ($env{'request.state'} ne "construct") {
1.288     raeburn   403:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc");
1.297     raeburn   404: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
1.163     albertel  405: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
                    406: 	    $status='INVALID_ACCESS';
                    407: 	    $date=&mt("can not be accessed from your location.");
1.145     albertel  408: 	    return($status,$date);
                    409: 	}
1.327     raeburn   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:         }
1.226     albertel  416: 	foreach my $temp ("opendate","duedate","answerdate") {
1.163     albertel  417: 	    $lastdate = $date;
1.247     albertel  418: 	    if ($temp eq 'duedate') {
                    419: 		$date = &due_date($id);
                    420: 	    } else {
                    421: 		$date = &Apache::lonnet::EXT("resource.$id.$temp");
                    422: 	    }
                    423: 	    
1.163     albertel  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: 		}
1.145     albertel  438: 	    }
1.163     albertel  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; }
1.274     www       446: 		$date = &Apache::lonlocal::locallocaltime($date);
1.145     albertel  447: 	    }
1.163     albertel  448: 	    if (!$passed) { $type=$temp; last; }
1.145     albertel  449: 	}
1.163     albertel  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';
1.343     bisitz    456: 	    $datemsg = &mt('will open on [_1]',$date);
1.163     albertel  457: 	} elsif ($type eq 'duedate') {
                    458: 	    $status='CAN_ANSWER';
1.343     bisitz    459: 	    $datemsg = &mt('is due at [_1]',$date);
1.163     albertel  460: 	} elsif ($type eq 'answerdate') {
                    461: 	    $status='CLOSED';
1.343     bisitz    462: 	    $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
                    463:                                $lastdate,$date);
1.145     albertel  464: 	}
                    465:     }
1.212     albertel  466:     if ($status eq 'CAN_ANSWER' ||
                    467: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
1.145     albertel  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'; }
1.164     albertel  472: 	if ( $maxtries eq '' && 
1.204     albertel  473: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
1.164     albertel  474: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
1.145     albertel  475: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
1.331     raeburn   476: 	if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
                    477: 	      && (&show_problem_status()) ) {
1.333     raeburn   478:             if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
                    479:                 (&Apache::lonnet::EXT("resource.$id.retrypartial") !~/^1|on|yes$/i)) {
1.331     raeburn   480: 	        $status = 'CANNOT_ANSWER';
                    481:             }
                    482:         } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
1.145     albertel  483: 	    $status = 'CANNOT_ANSWER';
                    484: 	}
1.285     albertel  485: 	if ($status eq 'CANNOT_ANSWER'
                    486: 	    && &show_answer_problem_status()) {
                    487: 	    $status = 'SHOW_ANSWER';
                    488: 	}
1.121     albertel  489:     }
1.181     albertel  490:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
1.286     albertel  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]);
1.177     albertel  495: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
                    496: 	    if (!$first_access) {
                    497: 		$status='NOT_YET_VIEWED';
1.247     albertel  498: 		my $due_date = &due_date($id);
1.256     albertel  499: 		my $seconds_left = $due_date - time;
1.286     albertel  500: 		if ($seconds_left > $interval[0] || $due_date eq '') {
                    501: 		    $seconds_left = $interval[0];
1.256     albertel  502: 		}
                    503: 		$datemsg=&seconds_to_human_length($seconds_left);
1.177     albertel  504: 	    }
                    505: 	}
                    506:     }
1.247     albertel  507: 
1.133     albertel  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:   #}
1.54      www       512: 
1.145     albertel  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';
1.146     albertel  517: 	$datemsg=&mt('is closed but you are allowed to view it');
1.145     albertel  518:     }
1.106     albertel  519: 
1.145     albertel  520:     return ($status,$datemsg);
1.20      albertel  521: }
1.301     jms       522: # this should work exactly like the copy in lonnavmaps.pm
1.246     albertel  523: sub due_date {
1.250     albertel  524:     my ($part_id,$symb,$udom,$uname)=@_;
1.246     albertel  525:     my $date;
1.286     albertel  526:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
1.250     albertel  527: 				       $udom,$uname);
1.286     albertel  528:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
1.250     albertel  529:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
                    530: 				       $udom,$uname);
1.247     albertel  531:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
1.286     albertel  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])");
1.247     albertel  535: 	if (defined($first_access)) {
1.286     albertel  536: 	    my $interval = $first_access+$interval[0];
1.283     albertel  537: 	    $date = (!$due_date || $interval < $due_date) ? $interval
                    538:                                                           : $due_date;
1.247     albertel  539: 	} else {
                    540: 	    $date = $due_date;
                    541: 	}
                    542:     } else {
                    543: 	$date = $due_date;
1.246     albertel  544:     }
1.345     musolffc  545:     return $date;
1.246     albertel  546: }
                    547: 
1.192     albertel  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: 
1.41      albertel  567: sub showhash {
1.145     albertel  568:     my (%hash) = @_;
                    569:     &showhashsubset(\%hash,'.');
                    570:     return '';
1.79      albertel  571: }
                    572: 
1.106     albertel  573: sub showarray {
                    574:     my ($array)=@_;
                    575:     my $string="(";
                    576:     foreach my $elm (@{ $array }) {
1.193     albertel  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,'.');
1.106     albertel  582: 	} else {
                    583: 	    $string.="$elm,"
                    584: 	}
                    585:     }
                    586:     chop($string);
                    587:     $string.=")";
                    588:     return $string;
                    589: }
                    590: 
1.79      albertel  591: sub showhashsubset {
1.145     albertel  592:     my ($hash,$keyre) = @_;
                    593:     my $resultkey;
1.346     raeburn   594:     foreach $resultkey (sort(keys(%$hash))) {
1.193     albertel  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}");
1.145     albertel  604: 	}
                    605:     }
                    606:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
                    607:     return '';
1.41      albertel  608: }
                    609: 
                    610: sub setuppermissions {
1.204     albertel  611:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
1.337     raeburn   612:     unless ($Apache::lonhomework::browse eq 'F') {
                    613:         $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'}); 
                    614:     }
1.204     albertel  615:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
1.145     albertel  616:     if (! $viewgrades && 
1.204     albertel  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'});
1.145     albertel  621:     }
1.244     albertel  622:     $Apache::lonhomework::viewgrades = $viewgrades;
                    623: 
1.185     albertel  624:     if ($Apache::lonhomework::browse eq 'F' && 
1.204     albertel  625: 	$env{'form.devalidatecourseresdata'} eq 'on') {
1.261     albertel  626: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
1.204     albertel  627: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
                    628: 					      $env{"course.$courseid.domain"});
1.185     albertel  629:     }
1.244     albertel  630: 
1.205     albertel  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;
1.244     albertel  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;
1.205     albertel  650:     return '';
1.41      albertel  651: }
                    652: 
1.253     albertel  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: 
1.41      albertel  660: sub setupheader {
1.120     albertel  661:     my $request=$_[0];
1.197     albertel  662:     &Apache::loncommon::content_type($request,'text/html');
1.120     albertel  663:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
                    664: 	&Apache::loncommon::no_cache($request);
                    665:     }
1.196     albertel  666: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                    667: #							  'lastrevisiondate'));
1.120     albertel  668:     $request->send_http_header;
                    669:     return OK if $request->header_only;
                    670:     return ''
1.41      albertel  671: }
1.35      albertel  672: 
1.47      albertel  673: sub handle_save_or_undo {
1.338     raeburn   674:     my ($request,$problem,$result,$getobjref) = @_;
1.323     www       675: 
1.145     albertel  676:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
                    677:     my $filebak =$file.".bak";
                    678:     my $filetmp =$file.".tmp";
                    679:     my $error=0;
1.323     www       680:     if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel  681: 	my $error=0;
1.284     albertel  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; }
1.145     albertel  685: 	if (!$error) {
1.266     albertel  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>");
1.145     albertel  692: 	} else {
1.266     albertel  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>");
1.145     albertel  699: 	    $error=1;
                    700: 	}
1.52      albertel  701:     } else {
1.262     banghart  702:         &Apache::lonnet::correct_line_ends($result);
1.323     www       703: 
1.145     albertel  704: 	my $fs=Apache::File->new(">$filebak");
                    705: 	if (defined($fs)) {
                    706: 	    print $fs $$problem;
                    707: 	} else {
1.266     albertel  708: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
                    709: 				  &mt("Unable to make backup [_1]",
                    710: 				      '<span class="LC_filename">'.
                    711: 				      $filebak.'</span>')."</span>");
1.145     albertel  712: 	    $error=2;
                    713: 	}
                    714: 	my $fh=Apache::File->new(">$file");
                    715: 	if (defined($fh)) {
                    716: 	    print $fh $$result;
1.338     raeburn   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:             }
1.145     albertel  741: 	} else {
1.266     albertel  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>');
1.145     albertel  747: 	    $error|=4;
                    748: 	}
1.52      albertel  749:     }
1.145     albertel  750:     return $error;
1.64      albertel  751: }
                    752: 
1.101     albertel  753: sub analyze_header {
                    754:     my ($request) = @_;
1.289     raeburn   755:     my $js = &Apache::structuretags::setmode_javascript();
1.312     bisitz    756: 
                    757:     # Breadcrumbs
1.330     raeburn   758:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn   759:                    'text' => 'Authoring Space'},
1.312     bisitz    760:                   {'href' => '',
                    761:                    'text' => 'Problem Testing'},
                    762:                   {'href' => '',
                    763:                    'text' => 'Analyzing a problem'}];
                    764: 
1.238     albertel  765:     my $result =
1.312     bisitz    766:         &Apache::loncommon::start_page('Analyzing a problem',
                    767:                                        $js,
                    768:                                        {'bread_crumbs' => $brcrum,})
1.311     bisitz    769:        .&Apache::loncommon::head_subbox(
                    770:                 &Apache::loncommon::CSTR_pageheader());
1.238     albertel  771:     $result .= 
1.347     golterma  772: 	    '<form name="lonhomework" method="post" action="'.
1.204     albertel  773: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.289     raeburn   774:             '<input type="hidden" name="problemmode" value="'.
                    775:             $env{'form.problemmode'}.'" />'.
1.179     albertel  776: 	    &Apache::structuretags::remember_problem_state().'
1.278     albertel  777:             <div class="LC_edit_problem_analyze_header">
1.289     raeburn   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'".')" />
1.313     bisitz    782:             <hr />
1.289     raeburn   783:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
                    784:             'onclick="javascript:setmode(this.form,'."'view'".')" />
1.313     bisitz    785:             <hr />
1.347     golterma  786:             </div>'
                    787:             .&Apache::lonxml::message_location().
                    788:             '</form>';
1.171     albertel  789:     &Apache::lonxml::add_messages(\$result);
1.101     albertel  790:     $request->print($result);
                    791:     $request->rflush();
                    792: }
                    793: 
1.109     albertel  794: sub analyze_footer {
                    795:     my ($request) = @_;
1.237     albertel  796:     $request->print(&Apache::loncommon::end_page());
1.109     albertel  797:     $request->rflush();
                    798: }
                    799: 
1.74      albertel  800: sub analyze {
1.101     albertel  801:     my ($request,$file) = @_;
                    802:     &Apache::lonxml::debug("Analyze");
                    803:     my $result;
                    804:     my %overall;
1.219     www       805:     my %seedexample;
1.101     albertel  806:     my %allparts;
1.204     albertel  807:     my $rndseed=$env{'form.rndseed'};
1.101     albertel  808:     &analyze_header($request);
1.114     albertel  809:     my %prog_state=
1.335     www       810: 	&Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
1.204     albertel  811:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
1.335     www       812: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
1.182     albertel  813: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
1.219     www       814:         my $thisseed=$i+$rndseed;
1.101     albertel  815: 	my $subresult=&Apache::lonnet::ssi($request->uri,
                    816: 					   ('grade_target' => 'analyze'),
1.219     www       817: 					   ('rndseed' => $thisseed));
1.101     albertel  818: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    819: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.114     albertel  820: 	my @parts;
1.336     raeburn   821:         if (ref($analyze{'parts'}) eq 'ARRAY') {
1.114     albertel  822: 	    @parts=@{ $analyze{'parts'} };
                    823: 	}
1.101     albertel  824: 	foreach my $part (@parts) {
                    825: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
1.109     albertel  826: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
                    827: 		$analyze{$part.'.type'} eq 'stringresponse'	||
                    828: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
1.263     albertel  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=~/^\@/)) {
1.266     albertel  836: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
1.263     albertel  837: 			}
                    838: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
                    839: 			    $thisseed;
                    840: 			$i++;
                    841: 		    }
1.219     www       842: 		}
1.275     albertel  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: 		}
1.101     albertel  851: 	    }
                    852: 	}
                    853:     }
1.335     www       854:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
1.313     bisitz    855:     $request->print('<hr />'
1.308     bisitz    856:                    .'<h3>'
                    857:                    .&mt('List of possible answers')
                    858:                    .'</h3>'
                    859:     );
1.134     albertel  860:     foreach my $part (sort(keys(%allparts))) {
1.336     raeburn   861:         if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
                    862:             (@{$overall{$part.'.answer'}} > 0)) {
1.263     albertel  863: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
                    864: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
1.308     bisitz    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:                 );
1.263     albertel  870: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
1.308     bisitz    871: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
1.263     albertel  872: 		}
1.308     bisitz    873: 		$request->print('</th>'
                    874:                                .&Apache::loncommon::end_data_table_header_row()
                    875:                 );
1.263     albertel  876: 		my %frequency;
                    877: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
                    878: 		    $frequency{join("\0",@{ $answer })}++;
                    879: 		}
1.308     bisitz    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:                 );
1.263     albertel  886: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
1.308     bisitz    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:                     );
1.263     albertel  896: 		}
1.308     bisitz    897:                 $request->print(&Apache::loncommon::end_data_table());
1.109     albertel  898: 	    }
                    899: 	} else {
1.307     bisitz    900:             $request->print('<p class="LC_warning">'
                    901:                            .&mt('Response [_1] is not analyzable at this time.',$part)
                    902: 			   .'</p>'
                    903:             );
1.101     albertel  904: 	}
                    905:     }
1.130     albertel  906:     if (scalar(keys(%allparts)) == 0 ) {
1.307     bisitz    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:         );
1.130     albertel  912:     }
1.114     albertel  913:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1.109     albertel  914:     &analyze_footer($request);
1.101     albertel  915:     &Apache::lonhomework::showhash(%overall);
                    916:     return $result;
1.74      albertel  917: }
                    918: 
1.277     albertel  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'
1.285     albertel  937: 		|| $show_problem_status eq 'answer'
1.277     albertel  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:     }
1.285     albertel  948:   
                    949:     sub show_answer_problem_status {
                    950: 	return ($show_problem_status eq 'answer');
                    951:     }
1.277     albertel  952: }
                    953: 
1.64      albertel  954: sub editxmlmode {
1.145     albertel  955:     my ($request,$file) = @_;
                    956:     my $result;
                    957:     my $problem=&Apache::lonnet::getfile($file);
                    958:     if ($problem eq -1) {
1.305     bisitz    959: 	&Apache::lonxml::error(
1.328     bisitz    960:             '<p class="LC_error">'
1.305     bisitz    961:            .&mt('Unable to find [_1]',
                    962:                 '<span class="LC_filename">'.$file.'</span>')
1.328     bisitz    963:            .'</p>');
1.305     bisitz    964: 
1.145     albertel  965: 	$problem='';
                    966:     }
1.323     www       967:     if (($env{'form.problemmode'} eq 'saveeditxml') ||
1.347     golterma  968:         ($env{'form.problemmode'} eq 'saveviewxml') ||
1.323     www       969:         ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel  970: 	my $error=&handle_save_or_undo($request,\$problem,
1.204     albertel  971: 				       \$env{'form.editxmltext'});
1.145     albertel  972: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
                    973:     }
1.204     albertel  974:     &Apache::lonhomework::showhashsubset(\%env,'^form');
1.323     www       975:     if ($env{'form.problemmode'} eq 'saveviewxml') {
1.204     albertel  976: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
1.289     raeburn   977: 	$env{'form.problemmode'}='view';
1.145     albertel  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; }
1.269     albertel  984: 	my $js =
                    985: 	    &Apache::edit::js_change_detection(). 
1.289     raeburn   986: 	    &Apache::loncommon::resize_textarea_js().
1.296     raeburn   987:             &Apache::structuretags::setmode_javascript().
1.298     foxr      988:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
1.312     bisitz    989: 
                    990:     # Breadcrumbs
1.330     raeburn   991:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn   992:                    'text' => 'Authoring Space'},
1.312     bisitz    993:                   {'href' => '',
                    994:                    'text' => 'Problem Editing'}];
                    995: 
1.238     albertel  996: 	my $start_page = 
1.269     albertel  997: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
                    998: 					   {'no_auto_mt_title' => 1,
1.318     droeschl  999: 					    'only_body'        => 0,
1.269     albertel 1000: 					    'add_entries'      => {
                   1001: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
                   1002: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1.323     www      1003:                                                                   },
1.312     bisitz   1004:                                                 'bread_crumbs' => $brcrum,
1.323     www      1005:                                              });
1.311     bisitz   1006: 
                   1007:     $result=$start_page
                   1008:            .&Apache::loncommon::head_subbox(
                   1009:                 &Apache::loncommon::CSTR_pageheader());
                   1010: 	$result.=&renderpage($request,$file,['no_output_web'],1).
1.310     bisitz   1011:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
1.204     albertel 1012: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.179     albertel 1013: 	    &Apache::structuretags::remember_problem_state().'
1.347     golterma 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: 
1.352     droeschl 1019:     $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
1.348     droeschl 1020:                   &Apache::structuretags::problem_edit_buttons('editxml');
1.352     droeschl 1021:     $result.='<div>';
1.347     golterma 1022: 
1.352     droeschl 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:     }
1.351     droeschl 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; "/>', 
1.352     droeschl 1043:         helpmenu_datastructure(),"");
1.351     droeschl 1044: 
                   1045:     $result.="</ol></div>";
1.323     www      1046:          
1.352     droeschl 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);
1.145     albertel 1096:     }
                   1097:     return '';
1.47      albertel 1098: }
1.189     albertel 1099: 
1.301     jms      1100: #
                   1101: #    Render the page in whatever target desired.
                   1102: #
1.41      albertel 1103: sub renderpage {
1.213     albertel 1104:     my ($request,$file,$targets,$return_string) = @_;
1.52      albertel 1105: 
1.211     albertel 1106:     my @targets = @{$targets || [&get_target()]};
1.204     albertel 1107:     &Apache::lonhomework::showhashsubset(\%env,'form.');
1.145     albertel 1108:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
1.268     albertel 1109: 
1.171     albertel 1110:     my $overall_result;
1.145     albertel 1111:     foreach my $target (@targets) {
1.183     albertel 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: 	#}
1.145     albertel 1119: 	#my $t0 = [&gettimeofday()];
1.211     albertel 1120: 	my $output=1;
                   1121: 	if ($target eq 'no_output_web') {
                   1122: 	    $target = 'web'; $output=0;
                   1123: 	}
1.145     albertel 1124: 	my $problem=&Apache::lonnet::getfile($file);
1.222     albertel 1125: 	my $result;
1.145     albertel 1126: 	if ($problem eq -1) {
1.260     albertel 1127: 	    $problem='';
1.222     albertel 1128: 	    my $filename=(split('/',$file))[-1];
1.260     albertel 1129: 	    my $error =
1.347     golterma 1130: 		'<p class="LC_error">'
                   1131:                .&mt('Unable to find [_1]',
                   1132: 			   '<span class="LC_filename">'.$filename.'</span>')
                   1133: 		."</p>";
1.260     albertel 1134: 	    $result.=
                   1135: 		&Apache::loncommon::simple_error_page($request,'Not available',
1.340     bisitz   1136: 						      $error,{'no_auto_mt_msg' => 1});
1.260     albertel 1137: 	    return;
1.145     albertel 1138: 	}
1.52      albertel 1139: 
1.145     albertel 1140: 	my %mystyle;
                   1141: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
                   1142: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
1.204     albertel 1143: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
1.145     albertel 1144: 
                   1145: 	&Apache::lonxml::debug("Should be parsing now");
1.222     albertel 1146: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
                   1147: 					     &setup_vars($target),%mystyle);
1.273     albertel 1148: 	&finished_parsing();
1.214     albertel 1149: 	if (!$output) { $result = ''; }
1.145     albertel 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: 	    #}
1.171     albertel 1163: #	    $request->print($result);
                   1164: 	    $overall_result.=$result;
                   1165: #	    $request->rflush();
1.145     albertel 1166: 	}
                   1167: 	#$request->print(":Result ends");
                   1168: 	#my $td=&tv_interval($t0);
1.52      albertel 1169:     }
1.213     albertel 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:     }
1.41      albertel 1177: }
                   1178: 
1.273     albertel 1179: sub finished_parsing {
                   1180:     undef($Apache::lonhomework::parsing_a_problem);
                   1181:     undef($Apache::lonhomework::parsing_a_task);
                   1182: }
                   1183: 
1.347     golterma 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 {
1.282     albertel 1203:     my ($extension) = @_;
1.145     albertel 1204:     my $result;
                   1205:     my @allnames;
                   1206:     &Apache::lonxml::debug("Looking for :$extension:");
1.282     albertel 1207:     my $glob_extension  = $extension;
                   1208:     if ($extension eq 'survey' || $extension eq 'exam') {
                   1209: 	$glob_extension = 'problem';
                   1210:     }
1.347     golterma 1211:     my @files = &get_template_list($extension);
1.287     raeburn  1212:     my ($midpoint,$seconddiv,$numfiles);
1.341     bisitz   1213:     my @noexamplelink = ('blank.problem','blank.library','script.library');
1.287     raeburn  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;
1.292     www      1227:     my $currentcategory='';
1.314     bisitz   1228:     my $first = 1;
1.329     raeburn  1229:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.282     albertel 1230:     foreach my $file (@files) {
                   1231: 	next if ($file->[1] !~ /\S/);
1.292     www      1232:         if ($file->[2] ne $currentcategory) {
                   1233:            $currentcategory=$file->[2];
                   1234:            if ((!$seconddiv) && ($count >= $midpoint)) {
1.314     bisitz   1235:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
1.292     www      1236:                $seconddiv = 1;
1.314     bisitz   1237:            } elsif (!$first) {
                   1238:                $result.='</div>'."\n";
                   1239:            } else {
                   1240:                $first = 0;
1.292     www      1241:            }
1.314     bisitz   1242:            $result.= '<div class="LC_Box">'."\n"
                   1243:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
1.293     www      1244:            $count++;
1.292     www      1245:         }
1.282     albertel 1246: 	$result .=
                   1247: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
1.292     www      1248: 	    $file->[1].'</label>';
                   1249:         if ($file->[3]) {
                   1250:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
                   1251:         }
1.341     bisitz   1252:         # Provide example link
1.292     www      1253:         my $filename=$file->[0];
1.329     raeburn  1254:         $filename=~s{^\Q$londocroot\E}{};
1.344     raeburn  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:         }
1.341     bisitz   1261:         $result .= '<br />'."\n";
1.287     raeburn  1262:         $count ++;
                   1263:     }
                   1264:     if ($numfiles > 0) {
1.314     bisitz   1265:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
1.42      albertel 1266:     }
1.145     albertel 1267:     return $result;
1.42      albertel 1268: }
                   1269: 
                   1270: sub newproblem {
1.65      matthew  1271:     my ($request) = @_;
1.282     albertel 1272: 
1.347     golterma 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:     }
1.282     albertel 1279:     if ($env{'form.template'}) {
                   1280: 	my $file = $env{'form.template'};
1.65      matthew  1281: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1282: 	&File::Copy::copy($file,$dest);
1.65      matthew  1283: 	&renderpage($request,$dest);
1.282     albertel 1284: 	return;
                   1285:     }
                   1286: 
                   1287:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
                   1288:     &Apache::lonxml::debug("Looking for :$extension:");
1.347     golterma 1289:     my $templatelist=&get_template_html($extension);
1.282     albertel 1290:     if ($env{'form.newfile'} && !$templatelist) {
                   1291: 	# no templates found
1.131     albertel 1292: 	my $templatefilename =
1.258     albertel 1293: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
1.131     albertel 1294: 	&Apache::lonxml::debug("$templatefilename");
                   1295: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1296: 	&File::Copy::copy($templatefilename,$dest);
1.131     albertel 1297: 	&renderpage($request,$dest);
1.85      albertel 1298:     } else {
1.176     albertel 1299: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
1.65      matthew  1300: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.128     albertel 1301: 	my $errormsg;
1.85      albertel 1302: 	my $instructions;
1.330     raeburn  1303:         my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn  1304:                        'text' => 'Authoring Space'},
1.312     bisitz   1305:                       {'href' => '',
                   1306:                        'text' => "Create New $extension"}];
1.240     albertel 1307: 	my $start_page = 
1.312     bisitz   1308:             &Apache::loncommon::start_page("Create New $extension",
                   1309:                                            undef,
                   1310:                                            {'bread_crumbs' => $brcrum,});
1.311     bisitz   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>
1.128     albertel 1316: $errormsg
1.258     albertel 1317: ".&mt("The requested file [_1] currently does not exist.",
1.329     raeburn  1318:       '<span class="LC_filename">'.$url.'</span>').'
1.314     bisitz   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">');
1.258     albertel 1323: 
1.85      albertel 1324: 	if (defined($templatelist)) {
1.282     albertel 1325: 	    $request->print($templatelist);
1.85      albertel 1326: 	}
1.282     albertel 1327: 	$request->print('<br /><input type="submit" name="newfile" value="'.
                   1328: 			&mt("Create $extension").'" />');
1.314     bisitz   1329: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
1.65      matthew  1330:     }
1.282     albertel 1331:     return;
1.42      albertel 1332: }
                   1333: 
1.268     albertel 1334: sub update_construct_style {
                   1335:     if ($env{'request.state'} eq "construct"
1.289     raeburn  1336: 	&& $env{'form.problemmode'} eq 'view' 
1.268     albertel 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'}) {
1.303     raeburn  1342: 	    &Apache::lonnet::delenv('construct.style');
1.268     albertel 1343: 	} elsif ($env{'form.style_file'} 
                   1344: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
1.291     raeburn  1345: 	    &Apache::lonnet::appenv({'construct.style' => 
                   1346: 				        $env{'form.style_file'}});
1.268     albertel 1347: 	}
                   1348:     }
                   1349: }
                   1350: 
1.354     musolffc 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: }
1.268     albertel 1386: 
1.41      albertel 1387: sub handler {
1.145     albertel 1388:     #my $t0 = [&gettimeofday()];
                   1389:     my $request=$_[0];
1.354     musolffc 1390: 
1.223     albertel 1391:     $Apache::lonxml::request=$request;
1.204     albertel 1392:     $Apache::lonxml::debug=$env{'user.debug'};
                   1393:     $env{'request.uri'}=$request->uri;
1.180     albertel 1394:     &setuppermissions();
1.193     albertel 1395: 
1.145     albertel 1396:     my $file=&Apache::lonnet::filelocation("",$request->uri);
                   1397: 
                   1398:     #check if we know where we are
1.350     raeburn  1399:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) {
1.145     albertel 1400: 	# if we are browsing we might not be able to know where we are
1.173     albertel 1401: 	if ($Apache::lonhomework::browse ne 'F' && 
1.204     albertel 1402: 	    $env{'request.state'} ne "construct") {
1.145     albertel 1403: 	    #should know where we are, so ask
1.253     albertel 1404: 	    &unset_permissions();
                   1405: 	    $request->internal_redirect('/adm/ambiguous');
                   1406: 	    return OK;
1.145     albertel 1407: 	}
                   1408:     }
1.253     albertel 1409:     if (&setupheader($request)) {
                   1410: 	&unset_permissions();
                   1411: 	return OK;
                   1412:     }
1.354     musolffc 1413: 
1.244     albertel 1414:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1.204     albertel 1415:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1.261     albertel 1416:     my ($symb) = &Apache::lonnet::whichuser();
1.145     albertel 1417:     &Apache::lonxml::debug('symb is '.$symb);
1.204     albertel 1418:     if ($env{'request.state'} eq "construct") {
1.145     albertel 1419: 	if ( -e $file ) {
                   1420: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1421: 						    ['problemmode']);
1.204     albertel 1422: 	    if (!(defined $env{'form.problemmode'})) {
1.145     albertel 1423: 		#first visit to problem in construction space
1.289     raeburn  1424: 		$env{'form.problemmode'}= 'view';
1.145     albertel 1425: 		&renderpage($request,$file);
1.323     www      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')) {
1.145     albertel 1430: 		&editxmlmode($request,$file);
1.289     raeburn  1431: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
1.145     albertel 1432: 		&analyze($request,$file);
                   1433: 	    } else {
1.268     albertel 1434: 		&update_construct_style();
1.145     albertel 1435: 		&renderpage($request,$file);
                   1436: 	    }
                   1437: 	} else {
1.347     golterma 1438: 		&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1439: 						    ['mode']);
1.145     albertel 1440: 	    # requested file doesn't exist in contruction space
                   1441: 	    &newproblem($request);
                   1442: 	}
                   1443:     } else {
1.354     musolffc 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:         }
1.145     albertel 1450: 	# just render the page normally outside of construction space
                   1451: 	&Apache::lonxml::debug("not construct");
1.52      albertel 1452: 	&renderpage($request,$file);
1.41      albertel 1453:     }
1.145     albertel 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;
1.253     albertel 1458:     &unset_permissions();
1.145     albertel 1459:     return OK;
1.52      albertel 1460: 
1.1       albertel 1461: }
                   1462: 
1.352     droeschl 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],
1.353     droeschl 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]
1.352     droeschl 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: 
1.1       albertel 1633: 1;
                   1634: __END__

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