File:  [LON-CAPA] / loncom / interface / slotrequest.pm
Revision 1.125.2.10.2.2: download - view: text, annotated - select for diffs
Mon Jul 10 01:49:09 2023 UTC (11 months, 4 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.125.2.10: preferred, unified
- For 2.11.4 (modified)
  Fix typo in 1.125.2.10.2.1

    1: # The LearningOnline Network with CAPA
    2: # Handler for requesting to have slots added to a students record
    3: #
    4: # $Id: slotrequest.pm,v 1.125.2.10.2.2 2023/07/10 01:49:09 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::slotrequest;
   31: 
   32: use strict;
   33: use Apache::Constants qw(:common :http :methods);
   34: use Apache::loncommon();
   35: use Apache::lonlocal;
   36: use Apache::lonnet;
   37: use Apache::lonnavmaps();
   38: use Date::Manip;
   39: use lib '/home/httpd/lib/perl/';
   40: use LONCAPA qw(:DEFAULT :match);
   41: 
   42: sub fail {
   43:     my ($r,$code)=@_;
   44:     if ($code eq 'not_valid') {
   45: 	$r->print('<p>'.&mt('Unable to understand what resource you wanted to sign up for.').'</p>');
   46:     } elsif ($code eq 'not_available') {
   47: 	$r->print('<p>'.&mt('No slots are available.').'</p>');
   48:     } elsif ($code eq 'not_allowed') {
   49: 	$r->print('<p>'.&mt('Not allowed to sign up or change reservations at this time.').'</p>');
   50:     } else {
   51: 	$r->print('<p>'.&mt('Failed.').'</p>');
   52:     }
   53:     
   54:     &return_link($r);
   55:     &end_page($r);
   56: }
   57: 
   58: sub start_page {
   59:     my ($r,$title,$brcrum,$bread_crumbs_component,$js,$mgr)=@_;
   60:     my $args;
   61:     if (ref($brcrum) eq 'ARRAY') {
   62:         $args = {bread_crumbs => $brcrum};
   63:         if ($bread_crumbs_component) {    
   64:             $args->{bread_crumbs_component} = $bread_crumbs_component;    
   65:         }
   66:     }
   67:     if (($env{'form.requestattempt'}) || ($env{'form.command'} eq 'manageresv')) {
   68:         my %loaditems = (
   69:                            onload => 'javascript:uncheckSlotRadio();',
   70:                         );
   71:         if (ref($args) eq 'HASH') {
   72:             $args->{'add_entries'} = \%loaditems;
   73:         } else {
   74:             $args = { 'add_entries' => \%loaditems };
   75:         }
   76:     }
   77:     unless (($env{'form.context'} eq 'usermanage') || (($mgr eq 'F') &&
   78:             (($env{'form.command'} eq 'release') ||
   79:              ($env{'form.command'} eq 'remove_registration')))) {
   80:         if ($env{'form.symb'}) {
   81:             my $symb=&unescape($env{'form.symb'});
   82:             my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
   83:             if ($resurl =~ /ext\.tool$/) {
   84:                 my $target;
   85:                 my ($marker,$exttool) = (split(m{/},$resurl))[3,4];
   86:                 $marker=~s/\D//g;
   87:                 if (($marker) && ($exttool) && ($env{'request.course.id'})) {
   88:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
   89:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
   90:                     my ($idx,$crstool,$is_tool,%toolhash,%toolsettings);
   91:                     if ($resurl eq "adm/$cdom/$cnum/$marker/$exttool") {
   92:                         my %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$cdom,$cnum);
   93:                         $target = $toolsettings{'target'};
   94:                     }
   95:                 }
   96:                 if ($target eq 'iframe') {
   97:                     $args->{'only_body'} = 1;
   98:                 }
   99:             }
  100:         }
  101:     }
  102:     $r->print(&Apache::loncommon::start_page($title,$js,$args));
  103: }
  104: 
  105: sub end_page {
  106:     my ($r)=@_;
  107:     $r->print(&Apache::loncommon::end_page());
  108: }
  109: 
  110: sub reservation_js {
  111:     my ($slots,$consumed_uniqueperiods,$available,$got_slots,$symb) = @_;
  112:     return unless ((ref($slots) eq 'HASH') && (ref($available) eq 'ARRAY'));
  113:     my $toskip;
  114:     if ($symb eq '') {
  115:         $toskip = { symb => 1, };
  116:     }
  117:     my ($i,$j) = (0,0);
  118:     my $js;
  119:     foreach my $slot (sort
  120:         { return $slots->{$a}->{'starttime'} <=> $slots->{$b}->{'starttime'} }
  121:                     (keys(%{$slots})))  {
  122: 
  123:         next if (!&allowed_slot($slot,$slots->{$slot},$symb,$slots,
  124:                                 $consumed_uniqueperiods,$toskip));
  125:         $js .= "    slotstart[$i]='$slots->{$slot}->{'starttime'}';\n".
  126:                "    slotend[$i]='$slots->{$slot}->{'endtime'}';\n".
  127:                "    slotname[$i]='$slot';\n";
  128:         if (($symb) && (ref($got_slots) eq 'ARRAY')) {
  129:             if (grep(/^\Q$slot\E$/,@{$got_slots})) {
  130:                 $js .= "    currslot[$j]='$slot';\n";
  131:                 $j++;
  132:             }
  133:         }
  134:         $i++;
  135:         push(@{$available},$slot);
  136:     }
  137:     if ($j) {
  138:         $js = "    var currslot = new Array($j);\n\n$js";
  139:     }
  140:     my %alerts = &Apache::lonlocal::texthash (
  141:                                                 none    => 'No reservable time slots found',
  142:                                                 invalid => 'Invalid date format',
  143:                                              );
  144:     return <<"ENDSCRIPT";
  145: <script type="text/javascript">
  146: // <![CDATA[
  147: function updateSlotDisplay(form,num,slotpickradio) {
  148:     var slotstart = new Array($i);
  149:     var slotend = new Array($i);
  150:     var slotname = new Array($i);
  151: $js
  152: 
  153:     if (slotpickradio == 'all') {
  154:         for (var i=0; i<$i; i++) {
  155:             if (document.getElementById('LC_slotrow_'+num+'_'+slotname[i])) {
  156:                 document.getElementById('LC_slotrow_'+num+'_'+slotname[i]).style.display = '';
  157:             }
  158:             if (document.getElementById('LC_slotsearch_'+num)) {
  159:                 document.getElementById('LC_slotsearch_'+num).style.display = 'block';
  160:             }
  161:         }
  162:     } else {
  163:         if (slotpickradio == 'show') {
  164:             for (var i=0; i<$i; i++) {
  165:                 if (document.getElementById('LC_slotrow_'+num+'_'+slotname[i])) {
  166:                     document.getElementById('LC_slotrow_'+num+'_'+slotname[i]).style.display = 'none';
  167:                 }
  168:             }
  169:             for (var j=0; j<$j; j++) {
  170:                 if (document.getElementById('LC_slotrow_'+num+'_'+currslot[j])) {
  171:                     document.getElementById('LC_slotrow_'+num+'_'+currslot[j]).style.display = '';
  172:                 }
  173:             }
  174:             if (document.getElementById('LC_slotsearch_'+num)) {
  175:                 document.getElementById('LC_slotsearch_'+num).style.display = 'block';
  176:             }
  177:         } else {
  178:             var numberRegExp = /^[0-9]+\$/;
  179:             var startm = form.start_month.options[form.start_month.selectedIndex].value;
  180:             var startd = form.start_day.value;
  181:             startd=startd.trim();
  182:             var starty = form.start_year.value;
  183:             starty=starty.trim();
  184:             var endm = form.end_month.options[form.end_month.selectedIndex].value;
  185:             var endd = form.end_day.value;
  186:             endd=endd.trim();
  187:             var endy = form.end_year.value;
  188:             endy=endy.trim();
  189:             if (numberRegExp.test(endd) && numberRegExp.test(endy) && numberRegExp.test(startd) && numberRegExp.test(starty)) {
  190:                 var startdate = startm+"/"+startd+"/"+starty;
  191:                 var starttime = new Date(startdate).getTime();
  192:                 starttime = starttime/1000;
  193:                 var starth = form.start_hour.options[form.start_hour.selectedIndex].value;
  194:                 if (numberRegExp.test(starth)) {
  195:                     starth = parseInt(starth);
  196:                     if (starth > 0 && starth <= 23) {
  197:                         starttime += 3600 * starth;
  198:                     }
  199:                 }
  200:                 var enddate = endm+"/"+endd+"/"+endy;
  201:                 var endtime = new Date(enddate).getTime();
  202:                 endtime = endtime/1000;
  203:                 var endh = form.end_hour.options[form.end_hour.selectedIndex].value;
  204:                 if (numberRegExp.test(endh)) {
  205:                     endh = parseInt(endh);
  206:                     if (endh > 0 && endh <= 23) {
  207:                         endtime += 3600 * endh;
  208:                     }
  209:                 }
  210: 
  211:                 var shown = 0;
  212:                 for (var i=0; i<$i; i++) {
  213:                     if ((slotstart[i] >= starttime) && (slotend[i] <= endtime)) {
  214:                         if (document.getElementById('LC_slotrow_'+num+'_'+slotname[i])) {
  215:                             document.getElementById('LC_slotrow_'+num+'_'+slotname[i]).style.display = '';
  216:                             shown ++;
  217:                         }
  218:                     } else {
  219:                         if (document.getElementById('LC_slotrow_'+num+'_'+slotname[i])) {
  220:                             document.getElementById('LC_slotrow_'+num+'_'+slotname[i]).style.display = 'none';
  221:                         }
  222:                     }
  223:                 }
  224:                 if (document.getElementById('LC_slotsearch_'+num)) {
  225:                     if (shown) {
  226:                         document.getElementById('LC_slotsearch_'+num).style.display = 'block';
  227:                     } else {
  228:                         document.getElementById('LC_slotsearch_'+num).style.display = 'none';
  229:                     }
  230:                 }
  231:                 if (shown == 0) {
  232:                     alert('$alerts{"none"}');
  233:                 }
  234:             } else {
  235:                 alert('$alerts{"invalid"}');
  236:             }
  237:         }
  238:     }
  239:     return;
  240: }
  241: 
  242: function toggleSlotDisplay(form,num) {
  243:     if (form.slotpick.length) {
  244:         for (var i=0; i<form.slotpick.length; i++) {
  245:             if (form.slotpick[i].checked) {
  246:                 var val = form.slotpick[i].value;
  247:                 if (document.getElementById('LC_slotfilter_'+num)) {
  248:                     document.getElementById('LC_slotsearch_'+num).style.display = 'none';
  249:                     if (val == 'filter') {
  250:                         document.getElementById('LC_slotfilter_'+num).style.display = 'block';
  251:                     } else {
  252:                         document.getElementById('LC_slotfilter_'+num).style.display = 'none';
  253:                         if (val == 'all') {
  254:                             updateSlotDisplay(form,num,val);
  255:                         } else {
  256:                             updateSlotDisplay(form,num,val);
  257:                         }
  258:                     }
  259:                 }
  260:                 break;
  261:             }
  262:         }
  263:     }
  264:     return false;
  265: }
  266: 
  267: if (!document.getElementsByClassName) {
  268:     function getElementsByClassName(node, classname) {
  269:         var a = [];
  270:         var re = new RegExp('(^| )'+classname+'( |$)');
  271:         var els = node.getElementsByTagName("*");
  272:         for(var i=0,j=els.length; i<j; i++)
  273:             if(re.test(els[i].className))a.push(els[i]);
  274:         return a;
  275:     }
  276: }
  277: 
  278: function uncheckSlotRadio() {
  279:     var slotpicks;
  280:     if (document.getElementsByClassName) {
  281:         slotpicks = document.getElementsByClassName('LC_slotpick_radio');
  282:     } else {
  283:         slotpicks = getElementsByClassName(document.body,'LC_slotpick_radio');
  284:     }
  285:     if (slotpicks.length) {
  286:         for (var i=0; i<slotpicks.length; i++) {
  287:             slotpicks[i].checked = false;  
  288:         }
  289:     }
  290: }
  291: // ]]>
  292: </script>
  293: ENDSCRIPT
  294: 
  295: }
  296: 
  297: 
  298: =pod
  299: 
  300:  slot_reservations db
  301:    - keys are 
  302:     - slotname\0id -> value is an hashref of
  303:                          name -> user@domain of holder
  304:                          timestamp -> timestamp of reservation
  305:                          symb -> symb of resource that it is reserved for
  306: 
  307: =cut
  308: 
  309: sub get_course {
  310:     (undef,my $courseid)=&Apache::lonnet::whichuser();
  311:     my $cdom=$env{'course.'.$courseid.'.domain'};
  312:     my $cnum=$env{'course.'.$courseid.'.num'};
  313:     return ($cnum,$cdom);
  314: }
  315: 
  316: sub get_reservation_ids {
  317:     my ($slot_name)=@_;
  318:     
  319:     my ($cnum,$cdom)=&get_course();
  320: 
  321:     my %consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum,
  322: 				       "^$slot_name\0");
  323:     if (&Apache::lonnet::error(%consumed)) { 
  324: 	return 'error: Unable to determine current status';
  325:     }
  326:     my ($tmp)=%consumed;
  327:     if ($tmp=~/^error: 2 / ) {
  328: 	return 0;
  329:     }
  330:     return keys(%consumed);
  331: }
  332: 
  333: sub space_available {
  334:     my ($slot_name,$slot)=@_;
  335:     my $max=$slot->{'maxspace'};
  336: 
  337:     if (!defined($max)) { return 1; }
  338: 
  339:     my $consumed=scalar(&get_reservation_ids($slot_name));
  340:     if ($consumed < $max) {
  341: 	return 1
  342:     }
  343:     return 0;
  344: }
  345: 
  346: sub check_for_reservation {
  347:     my ($symb,$mode)=@_;
  348:     my $student = &Apache::lonnet::EXT("resource.0.availablestudent", $symb,
  349: 				       $env{'user.domain'}, $env{'user.name'});
  350:     my $course = &Apache::lonnet::EXT("resource.0.available", $symb,
  351: 				    $env{'user.domain'}, $env{'user.name'});
  352:     my @slots = (split(/:/,$student), split(/:/, $course));
  353: 
  354:     &Apache::lonxml::debug(" slot list is ".join(':',@slots));
  355: 
  356:     my ($cnum,$cdom)=&get_course();
  357:     my %slots=&Apache::lonnet::get('slots', [@slots], $cdom, $cnum);
  358: 
  359:     if (&Apache::lonnet::error($student) 
  360: 	|| &Apache::lonnet::error($course)
  361: 	|| &Apache::lonnet::error(%slots)) {
  362: 	return 'error: Unable to determine current status';
  363:     }    
  364:     my @got;
  365:     my @sorted_slots = &Apache::loncommon::sorted_slots(\@slots,\%slots,'starttime');
  366:     foreach my $slot_name (@sorted_slots) {
  367: 	next if (!defined($slots{$slot_name}) ||
  368: 		 !ref($slots{$slot_name}));
  369: 	&Apache::lonxml::debug(time." $slot_name ".
  370: 			       $slots{$slot_name}->{'starttime'}." -- ".
  371: 			       $slots{$slot_name}->{'startreserve'}." -- ".
  372:                                $slots{$slot_name}->{'endreserve'});
  373: 	if (($slots{$slot_name}->{'endtime'} > time) &&
  374: 	    ($slots{$slot_name}->{'startreserve'} < time) &&
  375:             ((!$slots{$slot_name}->{'endreserve'}) || 
  376:              ($slots{$slot_name}->{'endreserve'} > time))) {
  377: 	    # between start of reservation time and end of reservation time
  378:             # and before end of slot
  379: 	    if ($mode eq 'allslots') {
  380: 		push(@got,$slot_name);
  381: 	    } else {
  382: 		return($slot_name, $slots{$slot_name});
  383: 	    }
  384: 	}
  385:     }
  386:     if ($mode eq 'allslots' && @got) {
  387: 	return @got;
  388:     }
  389:     return (undef,undef);
  390: }
  391: 
  392: sub get_consumed_uniqueperiods {
  393:     my ($slots) = @_;
  394:     my $navmap=Apache::lonnavmaps::navmap->new;
  395:     if (!defined($navmap)) {
  396:         return 'error: Unable to determine current status';
  397:     }
  398:     my @problems = $navmap->retrieveResources(undef,
  399: 					      sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0);
  400:     my %used_slots;
  401:     foreach my $problem (@problems) {
  402: 	my $symb = $problem->symb();
  403: 	my $student = &Apache::lonnet::EXT("resource.0.availablestudent",
  404: 					   $symb, $env{'user.domain'},
  405: 					   $env{'user.name'});
  406: 	my $course =  &Apache::lonnet::EXT("resource.0.available",
  407: 					   $symb, $env{'user.domain'},
  408: 					   $env{'user.name'});
  409: 	if (&Apache::lonnet::error($student) 
  410: 	    || &Apache::lonnet::error($course)) {
  411: 	    return 'error: Unable to determine current status';
  412: 	}
  413: 	foreach my $slot (split(/:/,$student), split(/:/, $course)) {
  414: 	    $used_slots{$slot}=1;
  415: 	}
  416:     }
  417: 
  418:     if (!ref($slots)) {
  419: 	my ($cnum,$cdom)=&get_course();
  420: 	my %slots=&Apache::lonnet::get('slots', [keys(%used_slots)], $cdom, $cnum);
  421: 	if (&Apache::lonnet::error(%slots)) {
  422: 	    return 'error: Unable to determine current status';
  423: 	}
  424: 	$slots = \%slots;
  425:     }
  426: 
  427:     my %consumed_uniqueperiods;
  428:     foreach my $slot_name (keys(%used_slots)) {
  429: 	next if (!defined($slots->{$slot_name}) ||
  430: 		 !ref($slots->{$slot_name}));
  431: 	
  432:         next if (!defined($slots->{$slot_name}{'uniqueperiod'}) ||
  433: 		 !ref($slots->{$slot_name}{'uniqueperiod'}));
  434: 	$consumed_uniqueperiods{$slot_name} = 
  435: 	    $slots->{$slot_name}{'uniqueperiod'};
  436:     }
  437:     return \%consumed_uniqueperiods;
  438: }
  439: 
  440: sub check_for_conflict {
  441:     my ($symb,$new_slot_name,$new_slot,$slots,$consumed_uniqueperiods)=@_;
  442: 
  443:     if (!defined($new_slot->{'uniqueperiod'})) { return undef; }
  444: 
  445:     if (!ref($consumed_uniqueperiods)) {
  446:         if ($consumed_uniqueperiods =~ /^error: /) {
  447:             return $consumed_uniqueperiods;
  448:         } else {
  449: 	    $consumed_uniqueperiods = &get_consumed_uniqueperiods($slots);
  450:             if (ref($consumed_uniqueperiods) eq 'HASH') {
  451: 	        if (&Apache::lonnet::error(%$consumed_uniqueperiods)) {
  452: 	            return 'error: Unable to determine current status';
  453: 	        }
  454:             } else {
  455:                 return 'error: Unable to determine current status';
  456:             }
  457:         }
  458:     } 
  459:     my ($new_uniq_start,$new_uniq_end) = @{$new_slot->{'uniqueperiod'}};
  460:     foreach my $slot_name (keys(%$consumed_uniqueperiods)) {
  461: 	my ($start,$end)=@{$consumed_uniqueperiods->{$slot_name}};
  462: 	if (!
  463: 	    ($start < $new_uniq_start &&  $end < $new_uniq_start) ||
  464: 	    ($start > $new_uniq_end   &&  $end > $new_uniq_end  )) {
  465: 	    return $slot_name;
  466: 	}
  467:     }
  468:     return undef;
  469: }
  470: 
  471: sub make_reservation {
  472:     my ($slot_name,$slot,$symb,$cnum,$cdom)=@_;
  473: 
  474:     my $value=&Apache::lonnet::EXT("resource.0.availablestudent",$symb,
  475: 				   $env{'user.domain'},$env{'user.name'});
  476:     &Apache::lonxml::debug("value is  $value<br />");
  477: 
  478:     my $use_slots = &Apache::lonnet::EXT("resource.0.useslots",$symb,
  479: 					 $env{'user.domain'},$env{'user.name'});
  480:     &Apache::lonxml::debug("use_slots is  $use_slots<br />");
  481: 
  482:     if (&Apache::lonnet::error($value) 
  483: 	|| &Apache::lonnet::error($use_slots)) { 
  484: 	return 'error: Unable to determine current status';
  485:     }
  486: 
  487:     my $symb_for_db = $symb;
  488:     my $parm_level = 1;
  489:     if ($use_slots eq 'map' || $use_slots eq 'map_map') {
  490: 	my ($map) = &Apache::lonnet::decode_symb($symb);
  491: 	$symb_for_db = &Apache::lonnet::symbread($map);
  492: 	$parm_level = 2;
  493:     }
  494: 
  495:     foreach my $other_slot (split(/:/, $value)) {
  496: 	if ($other_slot eq $slot_name) {
  497: 	    my %consumed=&Apache::lonnet::dump('slot_reservations', $cdom,
  498: 					       $cnum, "^$slot_name\0");   
  499: 	    if (&Apache::lonnet::error($value)) { 
  500: 		return 'error: Unable to determine current status';
  501: 	    }
  502: 	    my $me=$env{'user.name'}.':'.$env{'user.domain'};
  503: 	    foreach my $key (keys(%consumed)) {
  504: 		if ($consumed{$key}->{'name'} eq $me) {
  505: 		    my $num=(split('\0',$key))[1];
  506: 		    return -$num;
  507: 		}
  508: 	    }
  509: 	}
  510:     }
  511: 
  512:     my $max=$slot->{'maxspace'};
  513:     if (!defined($max)) { $max=99999; }
  514: 
  515:     my (@ids)=&get_reservation_ids($slot_name);
  516:     if (&Apache::lonnet::error(@ids)) { 
  517: 	return 'error: Unable to determine current status';
  518:     }
  519:     my $last=0;
  520:     foreach my $id (@ids) {
  521: 	my $num=(split('\0',$id))[1];
  522: 	if ($num > $last) { $last=$num; }
  523:     }
  524:     
  525:     my $wanted=$last+1;
  526:     &Apache::lonxml::debug("wanted $wanted<br />");
  527:     if (scalar(@ids) >= $max) {
  528: 	# full up
  529: 	return undef;
  530:     }
  531:     
  532:     my %reservation=('name'      => $env{'user.name'}.':'.$env{'user.domain'},
  533: 		     'timestamp' => time,
  534: 		     'symb'      => $symb_for_db);
  535: 
  536:     my $success=&Apache::lonnet::newput('slot_reservations',
  537: 					{"$slot_name\0$wanted" =>
  538: 					     \%reservation},
  539: 					$cdom, $cnum);
  540: 
  541:     if ($success eq 'ok') {
  542: 	my $new_value=$slot_name;
  543: 	if ($value) {
  544: 	    $new_value=$value.':'.$new_value;
  545: 	}
  546:         my $result = &store_slot_parm($symb,$symb_for_db,$slot_name,$parm_level,
  547:                                       $new_value,$cnum,$cdom,$env{'user.name'},
  548:                                       $env{'user.domain'},'reserve',$env{'form.context'});
  549: 	return $wanted;
  550:     }
  551: 
  552:     # someone else got it
  553:     return undef;
  554: }
  555: 
  556: sub store_slot_parm {
  557:     my ($symb_for_parm,$symb_for_db,$slot_name,$parm_level,$new_value,
  558:         $cnum,$cdom,$uname,$udom,$action,$context,$delflag) = @_;
  559: 
  560:     # store new parameter string
  561:     my $result=&Apache::lonparmset::storeparm_by_symb($symb_for_parm,
  562:                                                       '0_availablestudent',
  563:                                                       $parm_level,$new_value,
  564:                                                       'string',$uname,$udom);
  565:     &Apache::lonxml::debug("hrrm $result");
  566:     my %storehash = (
  567:                        symb    => $symb_for_db,
  568:                        slot    => $slot_name,
  569:                        action  => $action,
  570:                        context => $context,
  571:                     );
  572: 
  573:     &Apache::lonnet::write_log('course','slotreservationslog',\%storehash,
  574:                                $delflag,$uname,$udom,$cnum,$cdom);
  575:     &Apache::lonnet::write_log('course',$cdom.'_'.$cnum.'_slotlog',\%storehash,
  576:                                $delflag,$uname,$udom,$uname,$udom);
  577:     return $result;
  578: }
  579: 
  580: sub remove_registration {
  581:     my ($r) = @_;
  582:     if ($env{'form.entry'} ne 'remove all') {
  583: 	return &remove_registration_user($r);
  584:     }
  585:     my $slot_name = $env{'form.slotname'};
  586:     my %slot=&Apache::lonnet::get_slot($slot_name);
  587: 
  588:     my ($cnum,$cdom)=&get_course();
  589:     my %consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum,
  590: 				       "^$slot_name\0");
  591:     if (&Apache::lonnet::error(%consumed)) {
  592: 	$r->print("<p><span class=\"LC_error\">".&mt('A network error has occurred.').'</span></p>');
  593: 	return;
  594:     }
  595:     if (!%consumed) {
  596: 	$r->print('<p>'.&mt('Slot [_1] has no reservations.',
  597: 			    '<tt>'.$slot_name.'</tt>').'</p>');
  598: 	return;
  599:     }
  600: 
  601:     my @names = map { $consumed{$_}{'name'} } (sort(keys(%consumed)));
  602:     my $names = join(' ',@names);
  603: 
  604:     my $msg = &mt('Remove all of [_1] from slot [_2]?',$names,$slot_name);
  605:     &remove_registration_confirmation($r,$msg,['entry','slotname','context']);
  606: }
  607: 
  608: sub remove_registration_user {
  609:     my ($r) = @_;
  610:     
  611:     my $slot_name = $env{'form.slotname'};
  612: 
  613:     my $name = &Apache::loncommon::plainname($env{'form.uname'},
  614: 					     $env{'form.udom'});
  615: 
  616:     my $title = &Apache::lonnet::gettitle($env{'form.symb'});
  617: 
  618:     my $msg = &mt('Remove [_1] from slot [_2] for [_3]',
  619: 		  $name,$slot_name,$title);
  620:     
  621:     &remove_registration_confirmation($r,$msg,['uname','udom','slotname',
  622: 					       'entry','symb','context']);
  623: }
  624: 
  625: sub remove_registration_confirmation {
  626:     my ($r,$msg,$inputs) =@_;
  627: 
  628:     my $hidden_input;
  629:     foreach my $parm (@{$inputs}) {
  630: 	$hidden_input .=
  631: 	    '<input type="hidden" name="'.$parm.'" value="'
  632: 	    .&HTML::Entities::encode($env{'form.'.$parm},'"<>&\'').'" />'."\n";
  633:     }
  634:     my %lt = &Apache::lonlocal::texthash(
  635:         'yes' => 'Yes',
  636:         'no'  => 'No',
  637:     );
  638:     $r->print(<<"END_CONFIRM");
  639: <p> $msg </p>
  640: <form action="/adm/slotrequest" method="post">
  641:     <input type="hidden" name="command" value="release" />
  642:     <input type="hidden" name="button" value="yes" />
  643:     $hidden_input
  644:     <input type="submit" value="$lt{'yes'}" />
  645: </form>
  646: <form action="/adm/slotrequest" method="post">
  647:     <input type="hidden" name="command" value="showslots" />
  648:     <input type="submit" value="$lt{'no'}" />
  649: </form>
  650: END_CONFIRM
  651: 
  652: }
  653: 
  654: sub release_all_slot {
  655:     my ($r,$mgr)=@_;
  656:     
  657:     my $slot_name = $env{'form.slotname'};
  658: 
  659:     my ($cnum,$cdom)=&get_course();
  660: 
  661:     my %consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum,
  662: 				       "^$slot_name\0");
  663:     
  664:     $r->print('<p>'.&mt('Releasing reservations').'</p>');
  665: 
  666:     foreach my $entry (sort { $consumed{$a}{'name'} cmp 
  667: 				  $consumed{$b}{'name'} } (keys(%consumed))) {
  668: 	my ($uname,$udom) = split(':',$consumed{$entry}{'name'});
  669: 	my ($result,$msg) =
  670: 	    &release_reservation($slot_name,$uname,$udom,
  671: 				 $consumed{$entry}{'symb'},$mgr);
  672:         if (!$result) {
  673:             $r->print('<p class="LC_error">'.&mt($msg).'</p>');
  674:         } else {
  675: 	    $r->print("<p>$msg</p>");
  676:         }
  677: 	$r->rflush();
  678:     }
  679:     $r->print('<p><a href="/adm/slotrequest?command=showslots">'.
  680: 	      &mt('Return to slot list').'</a></p>');
  681:     &return_link($r);
  682: }
  683: 
  684: sub release_slot {
  685:     my ($r,$symb,$slot_name,$inhibit_return_link,$mgr)=@_;
  686: 
  687:     if ($slot_name eq '') { $slot_name=$env{'form.slotname'}; }
  688: 
  689:     my ($uname,$udom) = ($env{'user.name'}, $env{'user.domain'});
  690:     if ($mgr eq 'F' 
  691: 	&& defined($env{'form.uname'}) && defined($env{'form.udom'})) {
  692: 	($uname,$udom) = ($env{'form.uname'}, $env{'form.udom'});
  693:     }
  694: 
  695:     if ($mgr eq 'F' 
  696: 	&& defined($env{'form.symb'})) {
  697: 	$symb = &unescape($env{'form.symb'});
  698:     }
  699: 
  700:     my ($result,$msg) =
  701: 	&release_reservation($slot_name,$uname,$udom,$symb,$mgr);
  702:     if (!$result) {
  703:         $r->print('<p class="LC_error">'.&mt($msg).'</p>');
  704:     } else {
  705:         $r->print("<p>$msg</p>");
  706:     }
  707:     
  708:     if ($mgr eq 'F') {
  709: 	$r->print('<p><a href="/adm/slotrequest?command=showslots">'.
  710: 		  &mt('Return to slot list').'</a></p>');
  711:     }
  712: 
  713:     if (!$inhibit_return_link) { &return_link($r);  }
  714:     return $result;
  715: }
  716: 
  717: sub release_reservation {
  718:     my ($slot_name,$uname,$udom,$symb,$mgr) = @_;
  719:     my %slot=&Apache::lonnet::get_slot($slot_name);
  720:     my $description=&get_description($slot_name,\%slot);
  721:     my $msg;
  722: 
  723:     if ($mgr ne 'F') {
  724: 	if ($slot{'starttime'} < time) {
  725: 	    return (0,&mt('Not allowed to release Reservation: [_1], as it has already started.',$description));
  726: 	}
  727:     }
  728:     my $context = $env{'form.context'};
  729: 
  730:     # get navmap object
  731:     my $navmap=Apache::lonnavmaps::navmap->new;
  732:     if (!defined($navmap)) {
  733:         return (0,'error: Unable to determine current status');
  734:     }
  735: 
  736:     my ($cnum,$cdom)=&get_course();
  737: 
  738:     # get slot reservations, check if user has reservation
  739:     my %consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum,
  740:                                        "^$slot_name\0");
  741: 
  742:     #
  743:     # If release is because of a reservation *change*, symb(s) associated with reservation
  744:     # being dropped may differ from the current symb.
  745:     #
  746:     # We need to get symb(s) from slot_reservations.db, and for each symb, update
  747:     # the value of the availablestudent parameter, at the appropriate level
  748:     # (as dictated by the value of the useslots parameter for the symb and user).
  749:     #
  750:     # We also delete all entries for the slot being released, for the specific user.
  751:     #
  752: 
  753:     my $conflict;
  754: 
  755:     if (($env{'form.command'} eq 'change') && ($slot_name eq $env{'form.releaseslot'}) &&
  756:         ($env{'form.slotname'} ne $slot_name)) {
  757:         my %changedto = &Apache::lonnet::get_slot($env{'form.slotname'});
  758: 
  759:         # check for conflicts
  760:         my ($to_uniq_start,$to_uniq_end,$from_uniq_start,$from_uniq_end);
  761:         if (ref($changedto{'uniqueperiod'}) eq 'ARRAY') {
  762:             ($to_uniq_start,$to_uniq_end) = @{$changedto{'uniqueperiod'}};
  763:         }
  764:         if (ref($slot{'uniqueperiod'}) eq 'ARRAY') {
  765:             ($from_uniq_start,$from_uniq_end) = @{$slot{'uniqueperiod'}};
  766:         }
  767:         my $to_start = $changedto{'starttime'};
  768:         my $to_end = $changedto{'endtime'};
  769:         my $from_start = $slot{'starttime'};
  770:         my $from_end = $slot{'endtime'};
  771: 
  772:         if (!
  773:              ($from_start < $to_uniq_start && $from_end < $to_uniq_start) ||
  774:              ($from_start > $to_uniq_end   && $from_end > $to_uniq_end  )) {
  775:             $conflict = 1;
  776:         }
  777:         if (!
  778:              ($to_start < $from_uniq_start && $to_end < $from_uniq_start) ||
  779:              ($to_start > $from_uniq_end   && $to_end > $from_uniq_end  )) {
  780:             $conflict = 1;
  781:         }
  782: 
  783:         if ($conflict) {
  784:             my %symbs_for_slot;
  785:             my (%to_delete,%failed,%released);
  786:             foreach my $entry (keys(%consumed)) {
  787:                 if ( $consumed{$entry}->{'name'} eq ($uname.':'.$udom) ) {
  788:                     $symbs_for_slot{$consumed{$entry}->{'symb'}} = 1;
  789:                     $to_delete{$entry} = 1;
  790:                 }
  791:             }
  792:             if (keys(%to_delete)) {
  793:                 my @removals = keys(%to_delete);
  794:                 if (&Apache::lonnet::del('slot_reservations',\@removals,
  795:                                      $cdom,$cnum) eq 'ok') {
  796:                     foreach my $item (keys(%symbs_for_slot)) {
  797:                         my $result = &update_selectable($navmap,$slot_name,$item,$cdom,
  798:                                                         $cnum,$udom,$uname,$context);
  799:                         if ($result =~ /^error/) {
  800:                             $failed{$item} = 1;
  801:                         } else {
  802:                             $released{$item} = 1;
  803:                         }
  804:                     }
  805:                 }
  806:             }
  807:             if (keys(%released)) {
  808:                 $msg = '<span style="font-weight: bold;">'.
  809:                        &mt('Released Reservation: [_1]',$description).'</span>&nbsp;&nbsp;'.
  810:                        &mt('The following items had their reservation status change').':';
  811:                 my (%folders,%pages,%container,%titles);
  812:                 foreach my $item (keys(%released)) {
  813:                     my $res = $navmap->getBySymb($item);
  814:                     if (ref($res)) {
  815:                         $titles{$item} = $res->title();
  816:                         if ($res->is_map()) {
  817:                             $folders{$item}{'title'} = $titles{$item};
  818:                             if ($res->is_page()) {
  819:                                 $pages{$item}{'title'} = $titles{$item};
  820:                             } else {
  821:                                 $folders{$item}{'title'} = $titles{$item};
  822:                             }
  823:                         } else {
  824:                             my $mapsrc = $res->enclosing_map_src();
  825:                             my $map = $navmap->getResourceByUrl($mapsrc);
  826:                             if (ref($map)) {
  827:                                 if ($map->id() eq '0.0') {
  828:                                     $container{$mapsrc}{'title'} &mt('Top level of course');
  829:                                 } else {
  830:                                     $container{$mapsrc}{'title'} = $map->title();
  831:                                     if ($map->is_page()) {
  832:                                         $container{$mapsrc}{'page'} = 1;
  833:                                     }
  834:                                 }
  835:                             }
  836:                             $container{$mapsrc}{'resources'}{$item} = 1;
  837:                         }
  838:                     }
  839:                 }
  840:                 $msg .= '<ul>';
  841:                 if (keys(%folders)) {
  842:                     $msg .= '<li>'.&mt('Folders').': '.
  843:                             join(', ', map { $folders{$_}{'title'} } (sort { $folders{$b}{'title'} cmp $folders{$a}{'title'} } (keys(%folders)))).
  844:                             '</li>';
  845:                 }
  846:                 if (keys(%pages)) {
  847:                     $msg .= '<li>'.&mt('Composite Pages').': '.
  848:                             join(', ', map { $pages{$_}{'title'} } (sort { $pages{$b}{'title'} cmp $pages{$a}{'title'} } (keys(%pages)))).
  849:                             '</li>';
  850:                 }
  851:                 if (keys(%container)) {
  852:                     $msg .= '<li>'.&mt('Resources').':<ul>';
  853:                     foreach my $key (sort { $container{$b}{'title'} cmp $container{$a}{'title'} } (keys(%container))) {
  854:                         if (ref($container{$key}{'resources'}) eq 'HASH') {
  855:                             $msg .= '<li>'.
  856:                                     join(', ', map { $titles{$_} } (sort(keys(%{$container{$key}{'resources'}}))));
  857:                             if ($container{$key}{'page'}) {
  858:                                 $msg .= ' '.&mt('(in composite page [_1])',$container{$key}{'title'}).'</li>';
  859:                             } else {
  860:                                 $msg .= ' '.&mt('(in folder [_1])',$container{$key}{'title'}).'</li>';
  861:                             }
  862:                         }
  863:                     }
  864:                     $msg .= '</ul></li>';
  865:                 }
  866:                 $msg .= '</ul>';
  867:                 my $person = &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'});
  868:                 my $subject = &mt('Reservation change: [_1]',$description);
  869:                 my $msgbody = &mt('Reservation released by [_1] for [_2].',$person,$description);
  870:                 $msg .= &slot_change_messaging($slot{'reservationmsg'},$subject,$msgbody,'release');
  871:                 return (1,$msg);
  872:             } else {
  873:                 if (keys(%to_delete)) {
  874:                     $msg = &mt('Reservation release partially complete for [_1]',$description);
  875:                 } else {
  876:                     $msg = &mt('No entries found for this user to release for [_1].',$description);
  877:                 }
  878:                 return (0,$msg);
  879:             }
  880:         } else {
  881:             $msg = &mt('No conflict found; not releasing: [_1].',$description);
  882:             return (0,$msg);
  883:         }
  884:     }
  885: 
  886:     my $map_symb;
  887:     my $parm_symb = $symb;
  888:     my $passed_resource = $navmap->getBySymb($symb);
  889: 
  890:     # if the reservation symb is for a map get a resource in that map
  891:     # to check slot parameters on
  892:     my $parm_level = 1;
  893:     if (ref($passed_resource)) {
  894:         if ($passed_resource->is_map()) {
  895: 	    my ($a_resource) = 
  896:                 $navmap->retrieveResources($passed_resource, 
  897:                     sub {$_[0]->is_problem() || $_[0]->is_tool() },0,1);
  898:             $parm_symb = $a_resource->symb();
  899:         }
  900:     } else {
  901:         unless ($mgr eq 'F') {
  902:             return (0,'error: Unable to determine current status');
  903:         }
  904:     }
  905: 
  906:     # Get value of useslots parameter in effect for this user.
  907:     # If value is map or map_map, then the parm level is 2 (i.e.,
  908:     # non-recursive enclosing map/folder level for specific user)
  909:     # and the symb for this reservation in slot_reservations.db
  910:     # will be the symb of the map itself.
  911: 
  912:     my $use_slots = &Apache::lonnet::EXT('resource.0.useslots',
  913:                                          $parm_symb,$udom,$uname);
  914:     if (&Apache::lonnet::error($use_slots)) {
  915:         return (0,'error: Unable to determine current status');
  916:     }
  917:     if ($use_slots eq 'map' || $use_slots eq 'map_map') {
  918:         $parm_level = 2;
  919:         if ($passed_resource->is_map()) {
  920:             $map_symb = $passed_resource->symb();
  921:         } else {
  922:             my ($map) = &Apache::lonnet::decode_symb($symb);
  923:             $map_symb = &Apache::lonnet::symbread($map);
  924:         }
  925:     }
  926: 
  927:     #
  928:     # If release is *not* because of a reservation change, i.e., this is a "drop"
  929:     # by a student, or a removal for a single student by an instructor then
  930:     # only remove one entry from slot_reservations.db, where both the user
  931:     # and the symb match the current context.  If useslots was set to map or
  932:     # map_map, then the symb to match in slot_reservations.db is the symb of
  933:     # the enclosing map/folder, not the symb of the resource.
  934:     #
  935: 
  936:     my ($match,$symb_to_check);
  937:     if ($parm_level == 2) {
  938:         $symb_to_check = $map_symb;
  939:     } else {
  940:         $symb_to_check = $parm_symb;
  941:     }
  942:     foreach my $entry (keys(%consumed)) {
  943:         if ( $consumed{$entry}->{'name'} eq ($uname.':'.$udom) ) {
  944:             if ($consumed{$entry}->{'symb'} eq $symb_to_check) {
  945:                 if (&Apache::lonnet::del('slot_reservations',[$entry],
  946:                                          $cdom,$cnum) eq 'ok') {
  947:                     $match = $symb_to_check;
  948:                 }
  949:                 last;
  950:             }
  951:         }
  952:     }
  953:     if ($match) {
  954:         if (&update_selectable($navmap,$slot_name,$symb,$cdom,
  955:                                $cnum,$udom,$uname,$context) =~ /^error/) {
  956:             if ($mgr eq 'F') {
  957:                 $msg = &mt('Reservation release partially complete for: [_1]',"$uname:$udom").'<br />'.
  958:                        &mt('Update of availablestudent parameter for [_1] was not completed.',"$uname:$udom");
  959:             } else {
  960:                 $msg = &mt('Release partially complete for: [_1]',$description);
  961:             }
  962:             return (0,$msg);
  963:         } else {
  964:             if ($mgr eq 'F') {
  965:                 $msg = &mt('Released Reservation for user: [_1]',"$uname:$udom");
  966:             } else {
  967:                 $msg = '<span style="font-weight: bold;">'.&mt('Released reservation: [_1]',$description).'</span><br /><br />';
  968:                 my $person = &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'});
  969:                 my $subject = &mt('Reservation change: [_1]',$description);
  970:                 my $msgbody = &mt('Reservation released by [_1] for [_2].',$person,$description);
  971:                 $msg .= &slot_change_messaging($slot{'reservationmsg'},$subject,$msgbody,'release');
  972:             }
  973:             return (1,$msg);
  974:         }
  975:     } else {
  976:         $msg = &mt('Release failed for: [_1]',$description);
  977:         return (0,$msg);
  978:     }
  979: }
  980: 
  981: sub update_selectable {
  982:     my ($navmap,$slot_name,$symb,$cdom,$cnum,$udom,$uname,$context) = @_;
  983:     return 'error: ' unless (ref($navmap));
  984:     my $symb_for_parm = $symb;
  985:     my $passed_resource = $navmap->getBySymb($symb);
  986:     return 'error: invalid symb' unless (ref($passed_resource));
  987: 
  988:     # if the reservation symb is for a map get a resource in that map
  989:     # to check slot parameters on
  990:     if ($passed_resource->is_map()) {
  991:         my ($a_resource) =
  992:             $navmap->retrieveResources($passed_resource,
  993:                                        sub {$_[0]->is_problem() || $_[0]->is_tool() },0,1);
  994:         $symb_for_parm = $a_resource->symb();
  995:     }
  996:     # get parameter string, check for existence, rebuild string with the slot
  997:     my $student = &Apache::lonnet::EXT('resource.0.availablestudent',
  998:                                        $symb_for_parm,$udom,$uname);
  999: 
 1000:     # Get value of useslots parameter in effect for this user.
 1001:     # If value is map or map_map, then the parm level is 2 (i.e.,
 1002:     # non-recursive enclosing map/folder level for specific user)
 1003:     # and the symb for this reservation in slot_reservations.db
 1004:     # will be the symb of the map itself.
 1005: 
 1006:     my $use_slots = &Apache::lonnet::EXT('resource.0.useslots',
 1007:                                          $symb_for_parm,$udom,$uname);
 1008:     &Apache::lonxml::debug("use_slots is  $use_slots<br />");
 1009: 
 1010:     if (&Apache::lonnet::error($use_slots)) {
 1011:         return 'error: Unable to determine current status';
 1012:     }
 1013: 
 1014:     my $parm_level = 1;
 1015:     if ($use_slots eq 'map' || $use_slots eq 'map_map') {
 1016:         $parm_level = 2;
 1017:     }
 1018: 
 1019:     my @slots = split(/:/,$student);
 1020: 
 1021:     my @new_slots;
 1022:     foreach my $exist_slot (@slots) {
 1023:         next if ($exist_slot eq $slot_name);
 1024:         push(@new_slots,$exist_slot);
 1025:     }
 1026:     my $new_value = join(':',@new_slots);
 1027: 
 1028:     my $result = &store_slot_parm($symb_for_parm,$symb,$slot_name,$parm_level,
 1029:                                   $new_value,$cnum,$cdom,$uname,$udom,'release',
 1030:                                   $context,1);
 1031:     return $result;
 1032: }
 1033: 
 1034: sub delete_slot {
 1035:     my ($r)=@_;
 1036: 
 1037:     my $slot_name = $env{'form.slotname'};
 1038:     my %slot=&Apache::lonnet::get_slot($slot_name);
 1039: 
 1040:     my ($cnum,$cdom)=&get_course();
 1041:     my %consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum,
 1042: 				       "^$slot_name\0");
 1043:     my ($tmp) = %consumed;
 1044:     if ($tmp =~ /error: 2/) { undef(%consumed); }
 1045: 
 1046:     if (%slot && !%consumed) {
 1047: 	$slot{'type'} = 'deleted';
 1048: 	my $ret = &Apache::lonnet::cput('slots', {$slot_name => \%slot},
 1049: 					$cdom, $cnum);
 1050: 	if ($ret eq 'ok') {
 1051: 	    $r->print('<p>'.&mt('Slot [_1] marked as deleted.','<tt>'.$slot_name.'</tt>').'</p>');
 1052: 	} else {
 1053: 	    $r->print('<p class="LC_error">'.&mt('An error occurred when attempting to delete slot: [_1]','<tt>'.$slot_name.'</tt>')." ($ret)</p>");
 1054: 	}
 1055:     } else {
 1056: 	if (%consumed) {
 1057: 	    $r->print('<p>'.&mt('Slot [_1] has active reservations.','<tt>'.$slot_name.'</tt>').'</p>');
 1058: 	} else {
 1059: 	    $r->print('<p>'.&mt('Slot [_1] does not exist.','<tt>'.$slot_name.'</tt>').'</p>');
 1060: 	}
 1061:     }
 1062:     $r->print('<p><a href="/adm/slotrequest?command=showslots">'.
 1063: 	      &mt('Return to slot list').'</a></p>');
 1064:     &return_link($r);
 1065: }
 1066: 
 1067: sub return_link {
 1068:     my ($r) = @_;
 1069:     my $target = &return_target();
 1070:     if (($env{'form.command'} eq 'manageresv') || ($env{'form.context'} eq 'usermanage')) {
 1071: 	$r->print('<p><a href="/adm/slotrequest?command=manageresv" target="'.$target.'">'.
 1072:                   &mt('Return to reservations'));  
 1073:     } else {
 1074:         $r->print('<p><a href="/adm/flip?postdata=return:" target="'.$target.'">'.
 1075: 	          &mt('Return to last resource').'</a></p>');
 1076:     }
 1077: }
 1078: 
 1079: sub return_target {
 1080:     my ($target,$ltitarget,$deeplinktarget);
 1081:     if ($env{'request.lti.login'}) {
 1082:          $ltitarget = $env{'request.lti.target'};
 1083:     }
 1084:     if ($env{'request.deeplink.login'}) {
 1085:         $deeplinktarget = $env{'request.deeplink.target'};
 1086:     }
 1087:     if (($ltitarget eq 'iframe') || ($deeplinktarget eq '_self')) {
 1088:         $target = '_self';
 1089:     } else {
 1090:         $target = '_top';
 1091:     }
 1092:     return $target;
 1093: }
 1094: 
 1095: sub get_slot {
 1096:     my ($r,$symb,$conflictable_slot,$inhibit_return_link)=@_;
 1097: 
 1098:     my %slot=&Apache::lonnet::get_slot($env{'form.slotname'});
 1099:     my $slot_name=&check_for_conflict($symb,$env{'form.slotname'},\%slot);
 1100: 
 1101:     if ($slot_name =~ /^error: (.*)/) {
 1102: 	$r->print('<p class="LC_error">'
 1103:                  .&mt('An error occurred while attempting to make a reservation. ([_1])',$1)
 1104:                  .'</p>');
 1105: 	&return_link($r);
 1106: 	return 0;
 1107:     }
 1108:     if ($slot_name && $slot_name ne $conflictable_slot) {
 1109: 	my %slot=&Apache::lonnet::get_slot($slot_name);
 1110: 	my $description1=&get_description($slot_name,\%slot);
 1111:         my $slottype1=$slot{'type'};
 1112: 	%slot=&Apache::lonnet::get_slot($env{'form.slotname'});
 1113: 	my $description2=&get_description($env{'form.slotname'},\%slot);
 1114:         if ($slottype1 eq 'preassigned') {
 1115:             $r->print('<p>'.&mt('You already have a reservation: "[_1]", assigned by your instructor.',
 1116:                                 $description1).'</p>'.
 1117:                       '<p>'.&mt('Your instructor must unassign it before you can make a new reservation.').
 1118:                       '</p>');
 1119:         } elsif ($slot_name ne $env{'form.slotname'}) {
 1120: 	    $r->print(<<STUFF);
 1121: <form method="post" action="/adm/slotrequest">
 1122:    <input type="hidden" name="symb" value="$env{'form.symb'}" />
 1123:    <input type="hidden" name="slotname" value="$env{'form.slotname'}" />
 1124:    <input type="hidden" name="releaseslot" value="$slot_name" />
 1125:    <input type="hidden" name="command" value="change" />
 1126: STUFF
 1127:             $r->print('<p class="LC_error">'.&mt('Reservation currently unchanged').'</p>');
 1128:             if ($slot_name ne '') {
 1129:                 $r->print('<p>'.&mt('To complete the transaction you [_1]must confirm[_2] you want to [_3]process the change[_4] to [_5].'
 1130:                          ,'<b>','</b>','<i>','</i>','<b>'.$description2.'</b>')
 1131:                          .'<br />'
 1132:                          .&mt('Or you can choose to [_1]make no change[_2] and continue[_2] with the reservation you already had: [_3].'
 1133:                          ,'<i>','</i>','<b>'.$description1.'</b>')
 1134:                          .'</p><p><span class="LC_nobreak">'
 1135:                          .'<input type="submit" name="change" value="'.&mt('Process the change').'" />' 
 1136:                          .('&nbsp;'x3)
 1137:                          .'<input type="submit" name="nochange" value="'.&mt('Make no change').'" />'
 1138:                          .'</span></p>');
 1139:             }
 1140: 	    $r->print(<<STUFF);
 1141: </form>
 1142: STUFF
 1143:         } else {
 1144:             $r->print('<p>'.&mt('Already have a reservation: [_1].',$description1).'</p>');
 1145: 	    &return_link($r);
 1146: 	}
 1147: 	return 0;
 1148:     }
 1149: 
 1150:     my ($cnum,$cdom)=&get_course();
 1151:     my $reserved=&make_reservation($env{'form.slotname'},
 1152: 				   \%slot,$symb,$cnum,$cdom);
 1153:     my $description=&get_description($env{'form.slotname'},\%slot);
 1154:     if (defined($reserved)) {
 1155: 	my $retvalue = 0;
 1156: 	if ($slot_name =~ /^error: (.*)/) {
 1157: 	    $r->print('<p class="LC_error">'
 1158:                      .&mt('An error occurred while attempting to make a reservation. ([_1])',$1)
 1159:                      .'</p>');
 1160: 	} elsif ($reserved > -1) {
 1161: 	    $r->print('<p style="font-weight: bold;">'.&mt('Successfully signed up:  [_1]',$description).'</p>');
 1162: 	    $retvalue = 1;
 1163:             my $person = &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'});
 1164:             my $subject = &mt('Reservation change: [_1]',$description);
 1165:             my $msgbody = &mt('Successful reservation by [_1] for [_2].',$person,$description);
 1166:             my $msg = &slot_change_messaging($slot{'reservationmsg'},$subject,$msgbody,'reserve');
 1167:             if ($msg) {
 1168:                 $r->print($msg);
 1169:             }
 1170: 	} elsif ($reserved < 0) {
 1171: 	    $r->print('<p>'.&mt('Already reserved: [_1]',$description).'</p>');
 1172: 	}
 1173: 	if (!$inhibit_return_link) { &return_link($r); }
 1174: 	return 1;
 1175:     }
 1176: 
 1177:     my %lt = &Apache::lonlocal::texthash(
 1178:         'request' => 'Availability list',
 1179:         'try'     => 'Try again?',
 1180:         'or'      => 'or',
 1181:     );
 1182: 
 1183:     my $extra_input;
 1184:     if ($conflictable_slot) {
 1185: 	$extra_input='<input type="hidden" name="releaseslot" value="'.$env{'form.slotname'}.'" />';
 1186:     }
 1187: 
 1188:     $r->print('<p>'.&mt('[_1]Failed[_2] to reserve a slot for [_3].','<span class="LC_warning">','</span>',$description).'</p>');
 1189:     $r->print(<<STUFF);
 1190: <p>
 1191: <form method="post" action="/adm/slotrequest">
 1192:    <input type="submit" name="Try Again" value="$lt{'try'}" />
 1193:    <input type="hidden" name="symb" value="$env{'form.symb'}" />
 1194:    <input type="hidden" name="slotname" value="$env{'form.slotname'}" />
 1195:    <input type="hidden" name="command" value="$env{'form.command'}" />
 1196:    $extra_input
 1197: </form>
 1198: </p>
 1199: <p>
 1200: $lt{'or'}
 1201: <form method="post" action="/adm/slotrequest">
 1202:     <input type="hidden" name="symb" value="$env{'form.symb'}" />
 1203:     <input type="submit" name="requestattempt" value="$lt{'request'}" />
 1204: </form>
 1205: STUFF
 1206: 
 1207:     if (!$inhibit_return_link) { 
 1208:         $r->print(&mt('or').'</p>');
 1209:         &return_link($r);
 1210:     } else {
 1211:         $r->print('</p>');
 1212:     }
 1213:     return 0;
 1214: }
 1215: 
 1216: sub allowed_slot {
 1217:     my ($slot_name,$slot,$symb,$slots,$consumed_uniqueperiods,$toskip)=@_;
 1218: 
 1219:     #already started
 1220:     if ($slot->{'starttime'} < time) {
 1221: 	return 0;
 1222:     }
 1223:     &Apache::lonxml::debug("$slot_name starttime good");
 1224: 
 1225:     #already ended
 1226:     if ($slot->{'endtime'} < time) {
 1227: 	return 0;
 1228:     }
 1229:     &Apache::lonxml::debug("$slot_name endtime good");
 1230: 
 1231:     # not allowed to pick this one
 1232:     if (defined($slot->{'type'})
 1233: 	&& $slot->{'type'} ne 'schedulable_student') {
 1234: 	return 0;
 1235:     }
 1236:     &Apache::lonxml::debug("$slot_name type good");
 1237: 
 1238:     # reserve time not yet started
 1239:     if ($slot->{'startreserve'} > time) {
 1240: 	return 0;
 1241:     }
 1242:     # reserve time ended
 1243:     if (($slot->{'endreserve'}) &&
 1244:         ($slot->{'endreserve'} < time)) {
 1245:         return 0;
 1246:     }    
 1247:     &Apache::lonxml::debug("$slot_name reserve good");
 1248: 
 1249:     my $userallowed=0;
 1250:     # its for a different set of users
 1251:     if (defined($slot->{'allowedsections'})) {
 1252: 	if (!defined($env{'request.role.sec'})
 1253: 	    && grep(/^No section assigned$/,
 1254: 		    split(',',$slot->{'allowedsections'}))) {
 1255: 	    $userallowed=1;
 1256: 	}
 1257: 	if (defined($env{'request.role.sec'})
 1258: 	    && grep(/^\Q$env{'request.role.sec'}\E$/,
 1259: 		    split(',',$slot->{'allowedsections'}))) {
 1260: 	    $userallowed=1;
 1261: 	}
 1262: 	if (defined($env{'request.course.groups'})) {
 1263: 	    my @groups = split(/:/,$env{'request.course.groups'});
 1264: 	    my @allowed_sec = split(',',$slot->{'allowedsections'});
 1265: 	    foreach my $group (@groups) {
 1266: 		if (grep {$_ eq $group} (@allowed_sec)) {
 1267: 		    $userallowed=1;
 1268: 		    last;
 1269: 		}
 1270: 	    }
 1271: 	}
 1272:     }
 1273:     &Apache::lonxml::debug("$slot_name sections is $userallowed");
 1274: 
 1275:     # its for a different set of users
 1276:     if (defined($slot->{'allowedusers'})
 1277: 	&& grep(/^\Q$env{'user.name'}:$env{'user.domain'}\E$/,
 1278: 		split(',',$slot->{'allowedusers'}))) {
 1279: 	$userallowed=1;
 1280:     }
 1281: 
 1282:     if (!defined($slot->{'allowedusers'})
 1283: 	&& !defined($slot->{'allowedsections'})) {
 1284: 	$userallowed=1;
 1285:     }
 1286: 
 1287:     &Apache::lonxml::debug("$slot_name user is $userallowed");
 1288:     return 0 if (!$userallowed);
 1289: 
 1290:     # not allowed for this resource
 1291:     if (defined($slot->{'symb'})
 1292: 	&& $slot->{'symb'} ne $symb) {
 1293:         unless ((ref($toskip) eq 'HASH') && ($toskip->{'symb'})) {
 1294: 	    return 0;
 1295:         }
 1296:     }
 1297: 
 1298:     my $conflict = &check_for_conflict($symb,$slot_name,$slot,$slots,
 1299: 				       $consumed_uniqueperiods);
 1300:     if ($conflict =~ /^error: /) {
 1301:         return 0;
 1302:     } elsif ($conflict ne '') {
 1303: 	if ($slots->{$conflict}{'starttime'} < time) {
 1304: 	    return 0;
 1305: 	}
 1306:     }
 1307:     &Apache::lonxml::debug("$slot_name symb good");
 1308:     return 1;
 1309: }
 1310: 
 1311: sub get_description {
 1312:     my ($slot_name,$slot)=@_;
 1313:     my $description=$slot->{'description'};
 1314:     if (!defined($description)) {
 1315: 	$description=&mt('[_1] From [_2] to [_3]',$slot_name,
 1316: 			 &Apache::lonlocal::locallocaltime($slot->{'starttime'}),
 1317: 			 &Apache::lonlocal::locallocaltime($slot->{'endtime'}));
 1318:     }
 1319:     return $description;
 1320: }
 1321: 
 1322: sub show_choices {
 1323:     my ($r,$symb,$formname,$num,$slots,$consumed_uniqueperiods,$available,$got_slots)=@_;
 1324:     my $output;
 1325:     &Apache::lonxml::debug("Checking Slots");
 1326:     if (!ref($available) eq 'ARRAY') {
 1327:         return;
 1328:     }
 1329:     if (!@{$available}) {
 1330:         $output = '<span class="LC_info">'.&mt('No available times.').'</span>';
 1331:         if ($env{'form.command'} ne 'manageresv') {
 1332:             my $target = &return_target();
 1333:             $output .= ' <a href="/adm/flip?postdata=return:" target="'.$target.'">'.
 1334:                        &mt('Return to last resource').'</a>';
 1335:         }
 1336:         $r->print($output);
 1337:         return;
 1338:     }
 1339:     if (@{$available} > 1) {
 1340:         my $numavailable = scalar(@{$available});
 1341:         my $numreserved = 0;
 1342:         my $js;
 1343:         my $j = 0;
 1344:         foreach my $got (@{$got_slots}) {
 1345:             unless (($got eq '') || (!defined($got))) {
 1346:                 $numreserved ++;
 1347:                 if ($env{'form.command'} eq 'manageresv') {
 1348:                     $js .= "    currslot[$j]='$got';\n";
 1349:                     $j++;
 1350:                 }
 1351:             }
 1352:         }
 1353:         my $showfilter = 'none';
 1354:         $output .= '<fieldset><legend>'.&mt('Actions').'</legend>'."\n".
 1355:                    '<form method="post" name="reservationdisplay_'.$num.
 1356:                    '" action="" onsubmit="toggleSlotDisplay(this.form,'."'$num'".');">';
 1357:         my @options = ('all','filter');
 1358:         if ($numreserved) {
 1359:             unshift(@options,'show');
 1360:         }
 1361:         my %resmenu = &Apache::lonlocal::texthash (
 1362:                                          show   => 'Show current reservation',
 1363:                                          all    => 'Show all', 
 1364:                                          filter => 'Search by date',
 1365:                      );
 1366:         foreach my $option (@options) {
 1367:             my $onclick = "toggleSlotDisplay(this.form,'$num');";
 1368:             if (($option eq 'show') && ($env{'form.command'} eq 'manageresv')) {  
 1369:                 $onclick .= "currSlotDisplay$num(this.form,'$num');"; 
 1370:             }
 1371:             $output .= '<span class="LC_nobreak"><label>'.
 1372:                        '<input type="radio" class="LC_slotpick_radio" name="slotpick" value="'.
 1373:                        $option.'" onclick="'.$onclick.'" />'.
 1374:                        $resmenu{$option}.
 1375:                        '</label></span>'.('&nbsp;' x3)."\n";
 1376:         }
 1377:         $output .= '</form>';
 1378:         my $chooserform = 'reservationchooser_'.$num;
 1379:         my $starttime = $slots->{$available->[0]}->{'starttime'};
 1380:         my $endtime = $slots->{$available->[-1]}->{'starttime'};
 1381:         if ($env{'form.command'} eq 'manageresv') {
 1382:             $output .= <<"ENDSCRIPT";
 1383: 
 1384: <script type="text/javascript">
 1385: // <![CDATA[
 1386: function currSlotDisplay$num() {
 1387:     var currslot = new Array($numreserved);
 1388: $js    
 1389:     for (var j=0; j<$numreserved; j++) {
 1390:         if (document.getElementById('LC_slotrow_$num\_'+currslot[j])) {
 1391:             document.getElementById('LC_slotrow_$num\_'+currslot[j]).style.display = '';
 1392:         }
 1393:     }
 1394: }
 1395: // ]]>
 1396: </script>
 1397: 
 1398: ENDSCRIPT
 1399:         }
 1400:         $output .=
 1401:             '<div id="LC_slotfilter_'.$num.'" style="display:'.$showfilter.'">'.
 1402:             '<form method="post" name="'.$chooserform.'" action="">'.
 1403:             '<table><tr><td>'.&mt('Open after').'</td><td>'.
 1404:             &Apache::lonhtmlcommon::date_setter($chooserform,'start',$starttime,'','','','','','','',1,1).
 1405:             '</td></tr><tr><td>'.&mt('Closed before').'</td><td>'.
 1406:             &Apache::lonhtmlcommon::date_setter($chooserform,'end',$endtime,'','','','','','','',1,1).
 1407:             '</td></tr></table><br />'.
 1408:             '<input type="button" name="slotfilter" value="Search for reservable slots" onclick="updateSlotDisplay(this.form,'."'$num'".');" />'.
 1409:             '</form></div><div id="LC_slotsearch_'.$num.'" style="display:none"><hr />';
 1410:     }
 1411:     if ($env{'form.command'} eq 'manageresv') {
 1412:         $output .= '<table border="0">';
 1413:     } else {
 1414:         $output .= &Apache::loncommon::start_data_table();
 1415:     }
 1416:     foreach my $slot (@{$available}) {
 1417: 	my $description=&get_description($slot,$slots->{$slot});
 1418: 	my $form;
 1419: 	if ((grep(/^\Q$slot\E$/,@{$got_slots})) ||
 1420: 	    &space_available($slot,$slots->{$slot},$symb)) {
 1421: 	    my $text=&mt('Select');
 1422: 	    my $command='get';
 1423: 	    if (grep(/^\Q$slot\E$/,@{$got_slots})) {
 1424: 		$text=&mt('Drop Reservation');
 1425: 		$command='release';
 1426: 	    } else {
 1427: 		my $conflict = &check_for_conflict($symb,$slot,$slots->{$slot},
 1428: 						   $slots,$consumed_uniqueperiods);
 1429:                 if ($conflict) {
 1430:                     if ($conflict =~ /^error: /) {
 1431:                         $form = '<span class="LC_error">'.
 1432:                                  &mt('Slot: [_1] has unknown status.',$description).
 1433:                                  '</span>';
 1434:                     } else {
 1435: 		        $text=&mt('Change Reservation');
 1436: 		        $command='get';
 1437: 		    }
 1438:                 }
 1439: 	    }
 1440: 	    my $escsymb=&escape($symb);
 1441:             if (!$form) {
 1442:                 my $name;
 1443:                 if ($formname) {
 1444:                      $name = 'name="'.$formname.'"';
 1445:                 }
 1446:                 my $context = 'user';
 1447:                 if ($env{'form.command'} eq 'manageresv') {
 1448:                     $context = 'usermanage';
 1449:                 }
 1450: 	        $form=<<STUFF;
 1451:    <form method="post" action="/adm/slotrequest" $name>
 1452:      <input type="submit" name="Select" value="$text" />
 1453:      <input type="hidden" name="symb" value="$escsymb" />
 1454:      <input type="hidden" name="slotname" value="$slot" />
 1455:      <input type="hidden" name="command" value="$command" />
 1456:      <input type="hidden" name="context" value="$context" />
 1457:    </form>
 1458: STUFF
 1459: 	    }
 1460:         } else {
 1461:             $form = &mt('Unavailable');
 1462:         }
 1463:         if ($env{'form.command'} eq 'manageresv') {
 1464:             $output .= '<tr id="LC_slotrow_'.$num.'_'.$slot.'" >';
 1465:         } else {
 1466: 	    $output .= &Apache::loncommon::start_data_table_row('','LC_slotrow_'.$num.'_'.$slot);
 1467:         }
 1468:         $output .= " 
 1469:  <td>$form</td>
 1470:  <td>$description</td>\n";
 1471:         if ($env{'form.command'} eq 'manageresv') {
 1472:             $output .= '</tr>';
 1473:         } else {
 1474:             $output .= &Apache::loncommon::end_data_table_row();
 1475:         }
 1476:     }
 1477:     if ($env{'form.command'} eq 'manageresv') {
 1478:         $output .= '</table>';
 1479:     } else {
 1480:         $output .= &Apache::loncommon::end_data_table();
 1481:     }
 1482:     if (@{$available} > 1) {
 1483:         $output .= '</div></fieldset>';
 1484:     }
 1485:     $r->print($output);
 1486:     return;
 1487: }
 1488: 
 1489: sub to_show {
 1490:     my ($slotname,$slot,$when,$deleted,$name) = @_;
 1491:     my $time=time;
 1492:     my $week=60*60*24*7;
 1493: 
 1494:     if ($deleted eq 'hide' && $slot->{'type'} eq 'deleted') {
 1495: 	return 0;
 1496:     }
 1497: 
 1498:     if ($name && $name->{'value'} =~ /\w/) {
 1499: 	if ($name->{'type'} eq 'substring') {
 1500: 	    if ($slotname !~ /\Q$name->{'value'}\E/) {
 1501: 		return 0;
 1502: 	    }
 1503: 	}
 1504: 	if ($name->{'type'} eq 'exact') {
 1505: 	    if ($slotname eq $name->{'value'}) {
 1506: 		return 0;
 1507: 	    }
 1508: 	}
 1509:     }
 1510: 
 1511:     if ($when eq 'any') {
 1512: 	return 1;
 1513:     } elsif ($when eq 'now') {
 1514: 	if ($time > $slot->{'starttime'} &&
 1515: 	    $time < $slot->{'endtime'}) {
 1516: 	    return 1;
 1517: 	}
 1518: 	return 0;
 1519:     } elsif ($when eq 'nextweek') {
 1520: 	if ( ($time        < $slot->{'starttime'} &&
 1521: 	      ($time+$week) > $slot->{'starttime'})
 1522: 	     ||
 1523: 	     ($time        < $slot->{'endtime'} &&
 1524: 	      ($time+$week) > $slot->{'endtime'}) ) {
 1525: 	    return 1;
 1526: 	}
 1527: 	return 0;
 1528:     } elsif ($when eq 'lastweek') {
 1529: 	if ( ($time        > $slot->{'starttime'} &&
 1530: 	      ($time-$week) < $slot->{'starttime'})
 1531: 	     ||
 1532: 	     ($time        > $slot->{'endtime'} &&
 1533: 	      ($time-$week) < $slot->{'endtime'}) ) {
 1534: 	    return 1;
 1535: 	}
 1536: 	return 0;
 1537:     } elsif ($when eq 'willopen') {
 1538: 	if ($time < $slot->{'starttime'}) {
 1539: 	    return 1;
 1540: 	}
 1541: 	return 0;
 1542:     } elsif ($when eq 'wereopen') {
 1543: 	if ($time > $slot->{'endtime'}) {
 1544: 	    return 1;
 1545: 	}
 1546: 	return 0;
 1547:     }
 1548:     
 1549:     return 1;
 1550: }
 1551: 
 1552: sub remove_link {
 1553:     my ($slotname,$entry,$uname,$udom,$symb) = @_;
 1554: 
 1555:     my $remove = &mt('Remove');
 1556: 
 1557:     if ($entry eq 'remove all') {
 1558: 	$remove = &mt('Remove All');
 1559: 	undef($uname);
 1560: 	undef($udom);
 1561:     }
 1562: 
 1563:     $slotname  = &escape($slotname);
 1564:     $entry     = &escape($entry);
 1565:     $uname     = &escape($uname);
 1566:     $udom      = &escape($udom);
 1567:     $symb      = &escape($symb);
 1568: 
 1569:     return <<"END_LINK";
 1570:  <a href="/adm/slotrequest?command=remove_registration&amp;slotname=$slotname&amp;entry=$entry&amp;uname=$uname&amp;udom=$udom&amp;symb=$symb&amp;context=manage"
 1571:    >($remove)</a>
 1572: END_LINK
 1573: 
 1574: }
 1575: 
 1576: sub show_table {
 1577:     my ($r,$mgr)=@_;
 1578: 
 1579:     my ($cnum,$cdom)=&get_course();
 1580:     my $crstype=&Apache::loncommon::course_type($cdom.'_'.$cnum);
 1581:     my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 1582:     if ( (keys(%slots))[0] =~ /^error: 2 /) {
 1583: 	undef(%slots);
 1584:     } 
 1585:     my $available;
 1586:     if ($mgr eq 'F') {
 1587: 	$r->print('<div>');
 1588: 	$r->print('<form method="post" action="/adm/slotrequest">
 1589: <input type="hidden" name="command" value="uploadstart" />
 1590: <input type="submit" name="start" value="'.&mt('Upload Slot List').'" />
 1591: </form>');
 1592: 	$r->print(&Apache::loncommon::help_open_topic('Slot CommaDelimited'));
 1593: 	$r->print('<form method="post" action="/adm/helper/newslot.helper">
 1594: <input type="submit" name="newslot" value="'.&mt('Create a New Slot').'" />
 1595: </form>');
 1596: 	$r->print(&Apache::loncommon::help_open_topic('Slot About'));
 1597: 	$r->print('</div>');
 1598:     }
 1599: 
 1600:     if (!keys(%slots)) {
 1601:         $r->print(
 1602:             '<p class="LC_info">'
 1603:            .&mt('No slots have been created in this '.lc($crstype).'.')
 1604:            .'</p>'
 1605:         );
 1606:         return;
 1607:     }
 1608:     
 1609:     my %Saveable_Parameters = ('show'              => 'array',
 1610: 			       'when'              => 'scalar',
 1611: 			       'order'             => 'scalar',
 1612: 			       'deleted'           => 'scalar',
 1613: 			       'name_filter_type'  => 'scalar',
 1614: 			       'name_filter_value' => 'scalar',
 1615: 			       );
 1616:     &Apache::loncommon::store_course_settings('slotrequest',
 1617: 					      \%Saveable_Parameters);
 1618:     &Apache::loncommon::restore_course_settings('slotrequest',
 1619: 						\%Saveable_Parameters);
 1620:     &Apache::grades::init_perm();
 1621:     my ($classlist,$section,$fullname)=&Apache::grades::getclasslist('all');
 1622:     &Apache::grades::reset_perm();
 1623: 
 1624:     # what to display filtering
 1625:     my %show_fields=&Apache::lonlocal::texthash(
 1626: 	     'name'            => 'Slot Name',
 1627: 	     'description'     => 'Description',
 1628: 	     'type'            => 'Type',
 1629: 	     'starttime'       => 'Start time',
 1630: 	     'endtime'         => 'End Time',
 1631:              'startreserve'    => 'Time students can start reserving',
 1632:              'endreserve'      => 'Time students can no longer reserve',
 1633:              'reservationmsg'  => 'Message triggered by reservation',
 1634: 	     'secret'          => 'Secret Word',
 1635: 	     'space'           => '# of students/max',
 1636: 	     'ip'              => 'IP or DNS restrictions',
 1637: 	     'symb'            => 'Resource slot is restricted to.',
 1638: 	     'allowedsections' => 'Sections slot is restricted to.',
 1639: 	     'allowedusers'    => 'Users slot is restricted to.',
 1640: 	     'uniqueperiod'    => 'Period of time slot is unique',
 1641: 	     'scheduled'       => 'Scheduled Students',
 1642: 	     'proctor'         => 'List of proctors');
 1643:     if ($crstype eq 'Community') {
 1644:         $show_fields{'startreserve'} = &mt('Time members can start reserving');
 1645:         $show_fields{'endreserve'} = &mt('Time members can no longer reserve');
 1646:         $show_fields{'scheduled'} = &mt('Scheduled Members');
 1647:     }
 1648:     my @show_order=('name','description','type','starttime','endtime',
 1649: 		    'startreserve','endreserve','reservationmsg','secret','space',
 1650: 		    'ip','symb','allowedsections','allowedusers','uniqueperiod',
 1651: 		    'scheduled','proctor');
 1652:     my @show = 
 1653: 	(exists($env{'form.show'})) ? &Apache::loncommon::get_env_multiple('form.show')
 1654: 	                            : keys(%show_fields);
 1655:     my %show =  map { $_ => 1 } (@show);
 1656: 
 1657:     #when filtering setup
 1658:     my %when_fields=&Apache::lonlocal::texthash(
 1659: 	     'now'      => 'Open now',
 1660: 	     'nextweek' => 'Open within the next week',
 1661: 	     'lastweek' => 'Were open last week',
 1662: 	     'willopen' => 'Will open later',
 1663: 	     'wereopen' => 'Were open',
 1664: 	     'any'      => 'Anytime',
 1665: 						);
 1666:     my @when_order=('any','now','nextweek','lastweek','willopen','wereopen');
 1667:     $when_fields{'select_form_order'} = \@when_order;
 1668:     my $when = 	(exists($env{'form.when'})) ? $env{'form.when'}
 1669:                                             : 'now';
 1670: 
 1671:     #display of students setup
 1672:     my %stu_display_fields=
 1673: 	&Apache::lonlocal::texthash('username' => 'User name',
 1674: 				    'fullname' => 'Full name',
 1675: 				    );
 1676:     my @stu_display_order=('fullname','username');
 1677:     my @stu_display = 
 1678: 	(exists($env{'form.studisplay'})) ? &Apache::loncommon::get_env_multiple('form.studisplay')
 1679: 	                                  : keys(%stu_display_fields);
 1680:     my %stu_display =  map { $_ => 1 } (@stu_display);
 1681: 
 1682:     #name filtering setup
 1683:     my %name_filter_type_fields=
 1684: 	&Apache::lonlocal::texthash('substring' => 'Substring',
 1685: 				    'exact'     => 'Exact',
 1686: 				    #'reg'       => 'Regular Expression',
 1687: 				    );
 1688:     my @name_filter_type_order=('substring','exact');
 1689: 
 1690:     $name_filter_type_fields{'select_form_order'} = \@name_filter_type_order;
 1691:     my $name_filter_type = 
 1692: 	(exists($env{'form.name_filter_type'})) ? $env{'form.name_filter_type'}
 1693:                                                 : 'substring';
 1694:     my $name_filter = {'type'  => $name_filter_type,
 1695: 		       'value' => $env{'form.name_filter_value'},};
 1696: 
 1697:     
 1698:     #deleted slot filtering
 1699:     #default to hide if no value
 1700:     $env{'form.deleted'} ||= 'hide';
 1701:     my $hide_radio = 
 1702: 	&Apache::lonhtmlcommon::radio('deleted',$env{'form.deleted'},'hide');
 1703:     my $show_radio = 
 1704: 	&Apache::lonhtmlcommon::radio('deleted',$env{'form.deleted'},'show');
 1705: 	
 1706:     $r->print('<form method="post" action="/adm/slotrequest">
 1707: <input type="hidden" name="command" value="showslots" />');
 1708:     $r->print('<div>');
 1709:     $r->print('<table class="inline">
 1710:       <tr><th>'.&mt('Show').'</th>
 1711:           <th>'.&mt('Student Display').'</th>
 1712:           <th>'.&mt('Open').'</th>
 1713:           <th>'.&mt('Slot Name Filter').'</th>
 1714:           <th>'.&mt('Options').'</th>
 1715:       </tr>
 1716:       <tr><td valign="top">'.&Apache::loncommon::multiple_select_form('show',\@show,6,\%show_fields,\@show_order).
 1717: 	      '</td>
 1718:            <td valign="top">
 1719:          '.&Apache::loncommon::multiple_select_form('studisplay',\@stu_display,
 1720: 						    6,\%stu_display_fields,
 1721: 						    \@stu_display_order).'
 1722:            </td>
 1723:            <td valign="top">'.&Apache::loncommon::select_form($when,'when',\%when_fields).
 1724:           '</td>
 1725:            <td valign="top">'.&Apache::loncommon::select_form($name_filter_type,
 1726: 						 'name_filter_type',
 1727: 						 \%name_filter_type_fields).
 1728: 	      '<br />'.
 1729: 	      &Apache::lonhtmlcommon::textbox('name_filter_value',
 1730: 					      $env{'form.name_filter_value'},
 1731: 					      15).
 1732:           '</td>
 1733:            <td valign="top">
 1734:             <table>
 1735:               <tr>
 1736:                 <td rowspan="2">'.&mt('Deleted slots:').'</td>
 1737:                 <td><label>'.$show_radio.&mt('Show').'</label></td>
 1738:               </tr>
 1739:               <tr>
 1740:                 <td><label>'.$hide_radio.&mt('Hide').'</label></td>
 1741:               </tr>
 1742:             </table>
 1743: 	  </td>
 1744:        </tr>
 1745:     </table>');
 1746:     $r->print('</div>');
 1747:     $r->print('<p><input type="submit" name="start" value="'.&mt('Update Display').'" /></p>');
 1748:     my $linkstart='<a href="/adm/slotrequest?command=showslots&amp;order=';
 1749:     my $tableheader = &Apache::loncommon::start_data_table().
 1750:                       &Apache::loncommon::start_data_table_header_row().'
 1751:                       <th></th>';
 1752:     foreach my $which (@show_order) {
 1753: 	if ($which ne 'proctor' && exists($show{$which})) {
 1754: 	    $tableheader .= '<th>'.$linkstart.$which.'">'.$show_fields{$which}.'</a></th>';
 1755: 	}
 1756:     }
 1757:     $tableheader .= &Apache::loncommon::end_data_table_header_row();
 1758:     my $shownheader = 0;
 1759: 
 1760:     my %name_cache;
 1761:     my $slotsort = sub {
 1762: 	if ($env{'form.order'}=~/^(type|description|endtime|startreserve|endreserve|ip|symb|allowedsections|allowedusers|reservationmsg)$/) {
 1763: 	    if (lc($slots{$a}->{$env{'form.order'}})
 1764: 		ne lc($slots{$b}->{$env{'form.order'}})) {
 1765: 		return (lc($slots{$a}->{$env{'form.order'}}) 
 1766: 			cmp lc($slots{$b}->{$env{'form.order'}}));
 1767: 	    }
 1768: 	} elsif ($env{'form.order'} eq 'space') {
 1769: 	    if ($slots{$a}{'maxspace'} ne $slots{$b}{'maxspace'}) {
 1770: 		return ($slots{$a}{'maxspace'} cmp $slots{$b}{'maxspace'});
 1771: 	    }
 1772: 	} elsif ($env{'form.order'} eq 'name') {
 1773: 	    if (lc($a) cmp lc($b)) {
 1774: 		return lc($a) cmp lc($b);
 1775: 	    }
 1776: 	} elsif ($env{'form.order'} eq 'uniqueperiod') {
 1777: 	    
 1778: 	    if ($slots{$a}->{'uniqueperiod'}[0] 
 1779: 		ne $slots{$b}->{'uniqueperiod'}[0]) {
 1780: 		return ($slots{$a}->{'uniqueperiod'}[0]
 1781: 			cmp $slots{$b}->{'uniqueperiod'}[0]);
 1782: 	    }
 1783: 	    if ($slots{$a}->{'uniqueperiod'}[1] 
 1784: 		ne $slots{$b}->{'uniqueperiod'}[1]) {
 1785: 		return ($slots{$a}->{'uniqueperiod'}[1]
 1786: 			cmp $slots{$b}->{'uniqueperiod'}[1]);
 1787: 	    }
 1788: 	}
 1789: 	return $slots{$a}->{'starttime'} <=> $slots{$b}->{'starttime'};
 1790:     };
 1791: 
 1792:     my %consumed;
 1793:     if (exists($show{'scheduled'}) || exists($show{'space'}) ) {
 1794: 	%consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum);
 1795: 	my ($tmp)=%consumed;
 1796: 	if ($tmp =~ /^error: /) { undef(%consumed); }
 1797:     }
 1798: 
 1799:     my %msgops = &slot_reservationmsg_options();
 1800: 
 1801:     foreach my $slot (sort $slotsort (keys(%slots)))  {
 1802: 	if (!&to_show($slot,$slots{$slot},$when,
 1803: 		      $env{'form.deleted'},$name_filter)) { next; }
 1804:         my $reservemsg;
 1805: 	if (defined($slots{$slot}->{'type'})
 1806: 	    && $slots{$slot}->{'type'} eq 'schedulable_student') {
 1807: 	    $reservemsg = $msgops{$slots{$slot}->{'reservationmsg'}};
 1808: 	}
 1809: 	my $description=&get_description($slot,$slots{$slot});
 1810: 	my ($id_count,$ids);
 1811: 	    
 1812: 	if (exists($show{'scheduled'}) || exists($show{'space'}) ) {
 1813: 	    my $re_str = "$slot\0";
 1814: 	    my @this_slot = grep(/^\Q$re_str\E/,keys(%consumed));
 1815: 	    $id_count = scalar(@this_slot);
 1816: 	    if (exists($show{'scheduled'})) {
 1817: 		foreach my $entry (sort { $consumed{$a}{name} cmp 
 1818: 					      $consumed{$b}{name} }
 1819: 				   (@this_slot)) {
 1820: 		    my (undef,$id)=split("\0",$entry);
 1821: 		    my ($uname,$udom) = split(':',$consumed{$entry}{'name'});
 1822: 		    $ids.= '<span class="LC_nobreak">';
 1823: 		    foreach my $item (@stu_display_order) {
 1824: 			if ($stu_display{$item}) {
 1825: 			    if ($item eq 'fullname') {
 1826: 				$ids.=$fullname->{"$uname:$udom"}.' ';
 1827: 			    } elsif ($item eq 'username') {
 1828: 				$ids.="<tt>$uname:$udom</tt> ";
 1829: 			    }
 1830: 			}
 1831: 		    }
 1832: 		    $ids.=&remove_link($slot,$entry,$uname,$udom,
 1833: 				       $consumed{$entry}{'symb'}).'</span><br />';
 1834: 		}
 1835: 	    }
 1836: 	}
 1837: 
 1838: 	my $start=($slots{$slot}->{'starttime'}?
 1839: 		   &Apache::lonlocal::locallocaltime($slots{$slot}->{'starttime'}):'');
 1840: 	my $end=($slots{$slot}->{'endtime'}?
 1841: 		 &Apache::lonlocal::locallocaltime($slots{$slot}->{'endtime'}):'');
 1842: 	my $start_reserve=($slots{$slot}->{'startreserve'}?
 1843: 			   &Apache::lonlocal::locallocaltime($slots{$slot}->{'startreserve'}):'');
 1844:         my $end_reserve=($slots{$slot}->{'endreserve'}?
 1845:                          &Apache::lonlocal::locallocaltime($slots{$slot}->{'endreserve'}):'');
 1846: 	
 1847: 	my $unique;
 1848: 	if (ref($slots{$slot}{'uniqueperiod'})) {
 1849: 	    $unique=localtime($slots{$slot}{'uniqueperiod'}[0]).', '.
 1850: 		localtime($slots{$slot}{'uniqueperiod'}[1]);
 1851: 	}
 1852: 
 1853: 	my $title;
 1854: 	if (exists($slots{$slot}{'symb'})) {
 1855: 	    my (undef,undef,$res)=
 1856: 		&Apache::lonnet::decode_symb($slots{$slot}{'symb'});
 1857: 	    $res =   &Apache::lonnet::clutter($res);
 1858: 	    $title = &Apache::lonnet::gettitle($slots{$slot}{'symb'});
 1859: 	    $title='<a href="'.$res.'?symb='.$slots{$slot}{'symb'}.'">'.$title.'</a>';
 1860: 	}
 1861: 
 1862: 	my $allowedsections;
 1863: 	if (exists($show{'allowedsections'})) {
 1864: 	    $allowedsections = 
 1865: 		join(', ',sort(split(/\s*,\s*/,
 1866: 				     $slots{$slot}->{'allowedsections'})));
 1867: 	}
 1868: 
 1869: 	my @allowedusers;
 1870: 	if (exists($show{'allowedusers'})) {
 1871: 	    @allowedusers= map {
 1872: 		my ($uname,$udom)=split(/:/,$_);
 1873: 		my $fullname=$name_cache{$_};
 1874: 		if (!defined($fullname)) {
 1875: 		    $fullname = &Apache::loncommon::plainname($uname,$udom);
 1876: 		    $fullname =~s/\s/&nbsp;/g;
 1877: 		    $name_cache{$_} = $fullname;
 1878: 		}
 1879: 		&Apache::loncommon::aboutmewrapper($fullname,$uname,$udom);
 1880: 	    } (sort(split(/\s*,\s*/,$slots{$slot}->{'allowedusers'})));
 1881: 	}
 1882: 	my $allowedusers=join(', ',@allowedusers);
 1883: 	
 1884: 	my @proctors;
 1885: 	my $rowspan=1;
 1886: 	my $colspan=1;
 1887: 	if (exists($show{'proctor'})) {
 1888: 	    $rowspan=2;
 1889: 	    @proctors= map {
 1890: 		my ($uname,$udom)=split(/:/,$_);
 1891: 		my $fullname=$name_cache{$_};
 1892: 		if (!defined($fullname)) {
 1893: 		    $fullname = &Apache::loncommon::plainname($uname,$udom);
 1894: 		    $fullname =~s/\s/&nbsp;/g;
 1895: 		    $name_cache{$_} = $fullname;
 1896: 		}
 1897: 		&Apache::loncommon::aboutmewrapper($fullname,$uname,$udom);
 1898: 	    } (sort(split(/\s*,\s*/,$slots{$slot}->{'proctor'})));
 1899: 	}
 1900: 	my $proctors=join(', ',@proctors);
 1901: 
 1902:         my %lt = &Apache::lonlocal::texthash (
 1903:                                                edit   => 'Edit',
 1904:                                                delete => 'Delete',
 1905:                                                slotlog => 'History',
 1906:         );
 1907:         my ($edit,$delete,$showlog,$remove_all);
 1908:         if ($mgr) {
 1909: 	    $edit=(<<"EDITLINK");
 1910: <a href="/adm/helper/newslot.helper?name=$slot">$lt{'edit'}</a>
 1911: EDITLINK
 1912: 
 1913: 	    $delete=(<<"DELETELINK");
 1914: <a href="/adm/slotrequest?command=delete&amp;slotname=$slot">$lt{'delete'}</a>
 1915: DELETELINK
 1916: 
 1917:             $remove_all=&remove_link($slot,'remove all').'<br />';
 1918: 
 1919:             if ($ids eq '') {
 1920:                 undef($remove_all);
 1921:             } else {
 1922:                 undef($delete);
 1923:             }
 1924:         }
 1925: 
 1926:         $showlog=(<<"LOGLINK");
 1927: <a href="/adm/slotrequest?command=slotlog&amp;slotname=$slot">$lt{'slotlog'}</a>
 1928: LOGLINK
 1929: 
 1930: 	if ($slots{$slot}{'type'} ne 'schedulable_student') {
 1931:             undef($showlog); 
 1932: 	    undef($remove_all);
 1933: 	}
 1934: 
 1935:         unless ($shownheader) {
 1936:             $r->print($tableheader);
 1937:             $shownheader = 1;
 1938:         }
 1939: 
 1940: 	my $row_start=&Apache::loncommon::start_data_table_row();
 1941: 	my $row_end=&Apache::loncommon::end_data_table_row();
 1942:         $r->print($row_start.
 1943: 		  "\n<td rowspan=\"$rowspan\">$edit $delete $showlog</td>\n");
 1944: 	if (exists($show{'name'})) {
 1945: 	    $colspan++;$r->print("<td>$slot</td>");
 1946: 	}
 1947: 	if (exists($show{'description'})) {
 1948: 	    $colspan++;$r->print("<td>$description</td>\n");
 1949: 	}
 1950: 	if (exists($show{'type'})) {
 1951: 	    $colspan++;$r->print("<td>$slots{$slot}->{'type'}</td>\n");
 1952: 	}
 1953: 	if (exists($show{'starttime'})) {
 1954: 	    $colspan++;$r->print("<td>$start</td>\n");
 1955: 	}
 1956: 	if (exists($show{'endtime'})) {
 1957: 	    $colspan++;$r->print("<td>$end</td>\n");
 1958: 	}
 1959: 	if (exists($show{'startreserve'})) {
 1960: 	    $colspan++;$r->print("<td>$start_reserve</td>\n");
 1961: 	}
 1962:         if (exists($show{'endreserve'})) {
 1963:             $colspan++;$r->print("<td>$end_reserve</td>\n");
 1964:         }
 1965:         if (exists($show{'reservationmsg'})) {
 1966:             $colspan++;$r->print("<td>$reservemsg</td>\n");
 1967:         }
 1968: 	if (exists($show{'secret'})) {
 1969: 	    $colspan++;$r->print("<td>$slots{$slot}{'secret'}</td>\n");
 1970: 	}
 1971: 	if (exists($show{'space'})) {
 1972: 	    my $display = $id_count;
 1973: 	    if ($slots{$slot}{'maxspace'}>0) {
 1974: 		$display.='/'.$slots{$slot}{'maxspace'};
 1975: 		if ($slots{$slot}{'maxspace'} <= $id_count) {
 1976: 		    $display = '<strong>'.$display.' (full) </strong>';
 1977: 		}
 1978: 	    }
 1979: 	    $colspan++;$r->print("<td>$display</td>\n");
 1980: 	}
 1981: 	if (exists($show{'ip'})) {
 1982: 	    $colspan++;$r->print("<td>$slots{$slot}{'ip'}</td>\n");
 1983: 	}
 1984: 	if (exists($show{'symb'})) {
 1985: 	    $colspan++;$r->print("<td>$title</td>\n");
 1986: 	}
 1987: 	if (exists($show{'allowedsections'})) {
 1988: 	    $colspan++;$r->print("<td>$allowedsections</td>\n");
 1989: 	}
 1990: 	if (exists($show{'allowedusers'})) {
 1991: 	    $colspan++;$r->print("<td>$allowedusers</td>\n");
 1992: 	}
 1993: 	if (exists($show{'uniqueperiod'})) {
 1994: 	    $colspan++;$r->print("<td>$unique</td>\n");
 1995: 	}
 1996: 	if (exists($show{'scheduled'})) {
 1997: 	    $colspan++;$r->print("<td>$remove_all $ids</td>\n");
 1998: 	}
 1999: 	$r->print("$row_end\n");
 2000: 	if (exists($show{'proctor'})) {
 2001: 	    $r->print(<<STUFF);
 2002: $row_start
 2003:  <td colspan="$colspan">$proctors</td>
 2004: $row_end
 2005: STUFF
 2006:         }
 2007:     }
 2008:     if ($shownheader) {
 2009:         $r->print(&Apache::loncommon::end_data_table());
 2010:     } else {
 2011:         $r->print('<p>'.&mt('No slots meet the criteria for display').'</p>');
 2012:     }
 2013:     $r->print('</form>');
 2014:     return;
 2015: }
 2016: 
 2017: sub manage_reservations {
 2018:     my ($r,$crstype,$slots,$consumed_uniqueperiods,$allavailable) = @_;
 2019:     my $navmap = Apache::lonnavmaps::navmap->new();
 2020:     $r->print('<p>'
 2021:              .&mt('Instructors may use a reservation system to place restrictions on when and where assignments can be worked on.')
 2022:              .'<br />'
 2023:              .&mt('One example is for management of laboratory space, which is only available at certain times, and has a limited number of seats.')
 2024:              .'</p>'
 2025:     );
 2026:     if (!defined($navmap)) {
 2027:         $r->print('<div class="LC_error">');
 2028:         if ($crstype eq 'Community') {
 2029:             $r->print(&mt('Unable to retrieve information about community contents'));
 2030:         } else {
 2031:             $r->print(&mt('Unable to retrieve information about course contents'));
 2032:         }
 2033:         $r->print('</div>');
 2034:         &Apache::lonnet::logthis('Manage Reservations - could not create navmap object in '.lc($crstype).':'.$env{'request.course.id'});
 2035:         return;
 2036:     }
 2037:     if (ref($consumed_uniqueperiods) eq 'HASH') {
 2038:         if (&Apache::lonnet::error(%$consumed_uniqueperiods)) {
 2039:             $r->print('<span class="LC_error">'.
 2040:                       &mt('An error occurred determining slot availability.').
 2041:                       '</span>');
 2042:             return;
 2043:         }
 2044:     } elsif ($consumed_uniqueperiods =~ /^error: /) {
 2045:         $r->print('<span class="LC_error">'.
 2046:                   &mt('An error occurred determining slot availability.').
 2047:                   '</span>');
 2048:         return;
 2049:     }
 2050:     my (%parent,%shownparent,%container,%container_title,%contents);
 2051:     my ($depth,$count,$reservable,$lastcontainer,$rownum) = (0,0,0,0,0);
 2052:     my @backgrounds = ("LC_odd_row","LC_even_row");
 2053:     my $numcolors = scalar(@backgrounds);
 2054:     my $location=&Apache::loncommon::lonhttpdurl("/adm/lonIcons/whitespace_21.gif");
 2055:     my $slotheader = '<p>'.
 2056:                  &mt('Your reservation status for any such assignments is listed below:').
 2057:                  '</p>'.
 2058:                  '<table class="LC_data_table LC_tableOfContent">'."\n";
 2059:     my $shownheader = 0;
 2060:     my $it=$navmap->getIterator(undef,undef,undef,1,undef,undef);
 2061:     while (my $resource = $it->next()) {
 2062:         if ($resource == $it->BEGIN_MAP()) {
 2063:             $depth++;
 2064:             $parent{$depth} = $lastcontainer;
 2065:         }
 2066:         if ($resource == $it->END_MAP()) {
 2067:             $depth--;
 2068:             $lastcontainer = $parent{$depth};
 2069:         }
 2070:         if (ref($resource)) {
 2071:             my $symb = $resource->symb();
 2072:             my $ressymb = $symb;
 2073:             $contents{$lastcontainer} ++;
 2074:             next if (!$resource->is_problem() && !$resource->is_tool() &&
 2075:                       !$resource->is_sequence() && !$resource->is_page()); 
 2076:             $count ++;
 2077:             if (($resource->is_sequence()) || ($resource->is_page())) {
 2078:                 $lastcontainer = $count;
 2079:                 $container{$lastcontainer} = $resource;
 2080:                 $container_title{$lastcontainer} = $resource->compTitle();
 2081:             }
 2082:             if ($resource->is_problem() || $resource->is_tool()) {
 2083:                 my ($useslots) = $resource->slot_control();
 2084:                 next if (($useslots eq '') || ($useslots =~ /^\s*no\s*$/i));
 2085:                 my ($msg,$get_choices,$slotdescription);
 2086:                 my $title = $resource->compTitle();
 2087:                 my $status = $resource->simpleStatus('0');
 2088:                 my ($slot_status,$date,$slot_name) = $resource->check_for_slot('0');
 2089:                 if ($slot_name ne '') {
 2090:                     my %slot=&Apache::lonnet::get_slot($slot_name);
 2091:                     $slotdescription=&get_description($slot_name,\%slot);
 2092:                 }
 2093:                 if ($slot_status == $resource->NOT_IN_A_SLOT) {
 2094:                     $msg=&mt('No current reservation.');
 2095:                     $get_choices = 1;
 2096:                 } elsif ($slot_status == $resource->NEEDS_CHECKIN) {
 2097:                     $msg='<span class="LC_nobreak">'.&mt('Reserved:').
 2098:                          '&nbsp;'.$slotdescription.'</span><br />'.
 2099:                          &mt('Access requires proctor validation.');
 2100:                 } elsif ($slot_status == $resource->WAITING_FOR_GRADE) {
 2101:                     $msg=&mt('Submitted and currently in grading queue.');
 2102:                 } elsif ($slot_status == $resource->CORRECT) {
 2103:                     $msg=&mt('Problem is unavailable.');
 2104:                 } elsif ($slot_status == $resource->RESERVED) {
 2105:                     $msg='<span class="LC_nobreak">'.&mt('Reserved:').
 2106:                          '&nbsp;'.$slotdescription.'</span><br />'.
 2107:                          &mt('Problem is currently available.');
 2108:                 } elsif ($slot_status == $resource->RESERVED_LOCATION) {
 2109:                     $msg='<span class="LC_nobreak">'.&mt('Reserved:').
 2110:                          '&nbsp;'.$slotdescription.'</span><br />'.
 2111:                          &mt('Problem is available at a different location.');
 2112:                     $get_choices = 1;
 2113:                 } elsif ($slot_status == $resource->RESERVED_LATER) {
 2114:                     $msg='<span class="LC_nobreak">'.&mt('Reserved:').
 2115:                          '&nbsp;'.$slotdescription.'</span><br />'.
 2116:                          &mt('Problem will be available later.');
 2117:                     $get_choices = 1;
 2118:                 } elsif ($slot_status == $resource->RESERVABLE) {
 2119:                     $msg=&mt('Reservation needed');
 2120:                     $get_choices = 1;
 2121:                 } elsif ($slot_status == $resource->RESERVABLE_LATER) {
 2122:                     $msg=&mt('Reservation needed: will be reservable later.');
 2123:                 } elsif ($slot_status == $resource->NOTRESERVABLE) {
 2124:                     $msg=&mt('Reservation needed: none available.');
 2125:                 } elsif ($slot_status == $resource->UNKNOWN) {
 2126:                     $msg=&mt('Unable to determine status due to network problems.');
 2127:                 } else {
 2128:                     if ($status != $resource->OPEN) {
 2129:                         $msg = &Apache::lonnavmaps::getDescription($resource,'0'); 
 2130:                     }
 2131:                 }
 2132:                 $reservable ++;
 2133:                 my $treelevel = $depth;
 2134:                 my $higherup = $lastcontainer;
 2135:                 if ($depth > 1) {
 2136:                     my @maprows;
 2137:                     while ($treelevel > 1) {
 2138:                         if (ref($container{$higherup})) {
 2139:                             my $res = $container{$higherup};
 2140:                             last if (defined($shownparent{$higherup}));
 2141:                             my $maptitle = $res->compTitle();
 2142:                             my $type = 'sequence';
 2143:                             if ($res->is_page()) {
 2144:                                 $type = 'page';
 2145:                             }
 2146:                             &show_map_row($treelevel,$location,$type,$maptitle,
 2147:                                           \@maprows);
 2148:                             $shownparent{$higherup} = 1;
 2149:                         }
 2150:                         $treelevel --;
 2151:                         $higherup = $parent{$treelevel};
 2152:                     }
 2153:                     foreach my $item (@maprows) {
 2154:                         $rownum ++;
 2155:                         my $bgcolor = $backgrounds[$rownum % $numcolors];
 2156:                         if (!$shownheader) {
 2157:                             $r->print($slotheader);
 2158:                             $shownheader = 1;
 2159:                         }
 2160:                         $r->print('<tr class="'.$bgcolor.'">'.$item.'</tr>'."\n");
 2161:                     }
 2162:                 }
 2163:                 $rownum ++;
 2164:                 my $bgcolor = $backgrounds[$rownum % $numcolors];
 2165:                 if (!$shownheader) {
 2166:                     $r->print($slotheader);
 2167:                     $shownheader = 1;
 2168:                 }
 2169:                 $r->print('<tr class="'.$bgcolor.'"><td>'."\n");
 2170:                 for (my $i=0; $i<$depth; $i++) {
 2171:                     $r->print('<img src="'.$location.'" alt="" />');
 2172:                 }
 2173:                 my $result = '<a href="'.$resource->src().'?symb='.$symb.'">'.
 2174:                              '<img class="LC_contentImage" src="/adm/lonIcons/';
 2175:                 if ($resource->is_task()) {
 2176:                     $result .= 'task.gif" alt="'.&mt('Task');
 2177:                 } else {
 2178:                     $result .= 'problem.gif" alt="'.&mt('Problem');
 2179:                 }
 2180:                 $result .= '" /><b>'.$title.'</b></a>'.('&nbsp;' x6).'</td>';
 2181:                 my $hasaction;
 2182:                 if ($status == $resource->OPEN) {
 2183:                     if ($get_choices) {
 2184:                         $hasaction = 1;
 2185:                     }
 2186:                 }
 2187:                 if ($hasaction) {
 2188:                     $result .= '<td valign="top">'.$msg.'</td>'.
 2189:                                '<td valign="top">';
 2190:                 } else {
 2191:                     $result .= '<td colspan="2" valign="middle">'.$msg.'</td>';
 2192:                 }
 2193:                 $r->print($result);
 2194:                 if ($hasaction) {
 2195:                     my @got_slots=&check_for_reservation($symb,'allslots');
 2196:                     if ($got_slots[0] =~ /^error: /) {
 2197:                         $r->print('<span class="LC_error">'.
 2198:                                   &mt('An error occurred determining slot availability.').
 2199:                                   '</span>');
 2200:                     } else {
 2201:                         my $formname = 'manageres_'.$reservable;
 2202:                         if (ref($allavailable) eq 'ARRAY') {
 2203:                             my @available;
 2204:                             if (ref($slots) eq 'HASH') {
 2205:                                 foreach my $slot (@{$allavailable}) {
 2206:                                 # not allowed for this resource
 2207:                                     if (ref($slots->{$slot}) eq 'HASH') {
 2208:                                         if ((defined($slots->{$slot}->{'symb'})) && 
 2209:                                             ($slots->{$slot}->{'symb'} ne $symb)) {
 2210:                                             next;
 2211:                                         }
 2212:                                     }
 2213:                                     push(@available,$slot);
 2214:                                 }
 2215:                             }  
 2216:                             &show_choices($r,$symb,$formname,$reservable,$slots,$consumed_uniqueperiods,
 2217:                                           \@available,\@got_slots);
 2218:                         }
 2219:                     }
 2220:                     $r->print('</td>');
 2221:                 }
 2222:                 $r->print('</tr>');
 2223:             }
 2224:         }
 2225:     }
 2226:     if ($shownheader) {
 2227:         $r->print('</table>');
 2228:     }
 2229:     if (!$reservable) {
 2230:         $r->print('<span class="LC_info">');
 2231:         if ($crstype eq 'Community') {
 2232:             $r->print(&mt('No community items currently require a reservation to gain access.'));
 2233:         } else {
 2234:             $r->print(&mt('No course items currently require a reservation to gain access.'));
 2235:         }
 2236:         $r->print('</span>');
 2237:     }
 2238:     $r->print('<p><a href="/adm/slotrequest?command=showresv">'.
 2239:               &mt('Reservation History').'</a></p>');
 2240: }
 2241: 
 2242: sub show_map_row {
 2243:     my ($depth,$location,$type,$title,$maprows) = @_;
 2244:     my $output = '<td>';
 2245:     for (my $i=0; $i<$depth-1; $i++) {
 2246:         $output .= '<img src="'.$location.'" alt="" />';
 2247:     }
 2248:     if ($type eq 'page') {
 2249:         $output .= '<img src="/adm/lonIcons/navmap.page.open.gif" alt="" />&nbsp;'."\n";
 2250:     } else {
 2251:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n";
 2252:     }
 2253:     $output .= $title.'</td><td colspan="2">&nbsp;</td>'."\n";
 2254:     unshift (@{$maprows},$output);
 2255:     return;
 2256: }
 2257: 
 2258: sub show_reservations {
 2259:     my ($r,$uname,$udom) = @_;
 2260:     if (!defined($uname)) {
 2261:         $uname = $env{'user.name'};
 2262:     }
 2263:     if (!defined($udom)) {
 2264:         $udom = $env{'user.domain'};
 2265:     }
 2266:     my $formname = 'slotlog';
 2267:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2268:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2269:     my $crstype = &Apache::loncommon::course_type();
 2270:     my %log=&Apache::lonnet::dump('nohist_'.$cdom.'_'.$cnum.'_slotlog',$udom,$uname);
 2271:     if ($env{'form.origin'} eq 'aboutme') {
 2272:         $r->print('<div class="LC_fontsize_large">');
 2273:         my $name = &Apache::loncommon::plainname($env{'form.uname'},$env{'form.udom'},
 2274:                                                     'firstname');
 2275:         if ($crstype eq 'Community') {
 2276:             $r->print(&mt('History of member-reservable slots for: [_1]',
 2277:                           $name));
 2278:         } else {
 2279:             $r->print(&mt('History of student-reservable slots for: [_1]',
 2280:                           $name));
 2281: 
 2282:         }
 2283:         $r->print('</div>');
 2284:     }
 2285:     $r->print('<form action="/adm/slotrequest" method="post" name="'.$formname.'">');
 2286:     # set defaults
 2287:     my $now = time();
 2288:     my $defstart = $now - (7*24*3600); #7 days ago
 2289:     my %defaults = (
 2290:                      page           => '1',
 2291:                      show           => '10',
 2292:                      action         => 'any',
 2293:                      log_start_date => $defstart,
 2294:                      log_end_date   => $now,
 2295:                    );
 2296:     my $more_records = 0;
 2297: 
 2298:     # set current
 2299:     my %curr;
 2300:     foreach my $item ('show','page','action') {
 2301:         $curr{$item} = $env{'form.'.$item};
 2302:     }
 2303:     my ($startdate,$enddate) =
 2304:         &Apache::lonuserutils::get_dates_from_form('log_start_date',
 2305:                                                    'log_end_date');
 2306:     $curr{'log_start_date'} = $startdate;
 2307:     $curr{'log_end_date'} = $enddate;
 2308:     foreach my $key (keys(%defaults)) {
 2309:         if ($curr{$key} eq '') {
 2310:             $curr{$key} = $defaults{$key};
 2311:         }
 2312:     }
 2313:     my ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 2314:     $r->print(&display_filter($formname,$cdom,$cnum,\%curr,$version));
 2315:     my $showntablehdr = 0;
 2316:     my $tablehdr = &Apache::loncommon::start_data_table().
 2317:                    &Apache::loncommon::start_data_table_header_row().
 2318:                    '<th>&nbsp;</th><th>'.&mt('When').'</th><th>'.&mt('Action').'</th>'.
 2319:                    '<th>'.&mt('Description').'</th><th>'.&mt('Start time').'</th>'.
 2320:                    '<th>'.&mt('End time').'</th><th>'.&mt('Resource').'</th>'.
 2321:                    &Apache::loncommon::end_data_table_header_row();
 2322:     my ($minshown,$maxshown);
 2323:     $minshown = 1;
 2324:     my $count = 0;
 2325:     if ($curr{'show'} ne &mt('all')) {
 2326:         $maxshown = $curr{'page'} * $curr{'show'};
 2327:         if ($curr{'page'} > 1) {
 2328:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 2329:         }
 2330:     }
 2331:     my (%titles,%maptitles);
 2332:     my %lt = &reservationlog_contexts($crstype);
 2333:     foreach my $id (sort { $log{$b}{'exe_time'}<=>$log{$a}{'exe_time'} } (keys(%log))) {
 2334:         next if (($log{$id}{'exe_time'} < $curr{'log_start_date'}) ||
 2335:                  ($log{$id}{'exe_time'} > $curr{'log_end_date'}));
 2336:         if ($curr{'show'} ne &mt('all')) {
 2337:             if ($count >= $curr{'page'} * $curr{'show'}) {
 2338:                 $more_records = 1;
 2339:                 last;
 2340:             }
 2341:         }
 2342:         if ($curr{'action'} ne 'any') {
 2343:             next if ($log{$id}{'logentry'}{'action'} ne $curr{'action'});
 2344:         }
 2345:         $count ++;
 2346:         next if ($count < $minshown);
 2347:         if (!$showntablehdr) {
 2348:             $r->print($tablehdr);
 2349:             $showntablehdr = 1;
 2350:         }
 2351:         my $symb = $log{$id}{'logentry'}{'symb'};
 2352:         my $slot_name = $log{$id}{'logentry'}{'slot'};
 2353:         my %slot=&Apache::lonnet::get_slot($slot_name);
 2354:         my $description = $slot{'description'};
 2355:         my $start = ($slot{'starttime'}?
 2356:                      &Apache::lonlocal::locallocaltime($slot{'starttime'}):'');
 2357:         my $end = ($slot{'endtime'}?
 2358:                    &Apache::lonlocal::locallocaltime($slot{'endtime'}):'');
 2359:         my $title = &get_resource_title($symb,\%titles,\%maptitles);
 2360:         my $chgaction = $log{$id}{'logentry'}{'action'};
 2361:         if ($chgaction ne '' && $lt{$chgaction} ne '') {
 2362:             $chgaction = $lt{$chgaction};
 2363:         }
 2364:         $r->print(&Apache::loncommon::start_data_table_row().'<td>'.$count.'</td><td>'.&Apache::lonlocal::locallocaltime($log{$id}{'exe_time'}).'</td><td>'.$chgaction.'</td><td>'.$description.'</td><td>'.$start.'</td><td>'.$end.'</td><td>'.$title.'</td>'.&Apache::loncommon::end_data_table_row()."\n");
 2365:     }
 2366:     if ($showntablehdr) {
 2367:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 2368:         if (($curr{'page'} > 1) || ($more_records)) {
 2369:             $r->print('<p>');
 2370:             if ($curr{'page'} > 1) {
 2371:                 $r->print('<input type="button" onclick="javascript:chgPage('."'previous'".');" value="'.
 2372:                           &mt('Previous [_1] changes',$curr{'show'}).'" />');
 2373:             }
 2374:             if ($more_records) {
 2375:                 $r->print('<input type="button" onclick="javascript:chgPage('."'next'".');" value="'.
 2376:                           &mt('Next [_1] changes',$curr{'show'}).'" />');
 2377:             }
 2378:             $r->print('</p>');
 2379:             $r->print(<<"ENDSCRIPT");
 2380: <script type="text/javascript">
 2381: // <![CDATA[
 2382: function chgPage(caller) {
 2383:     if (caller == 'previous') {
 2384:         document.$formname.page.value --;
 2385:     }
 2386:     if (caller == 'next') {
 2387:         document.$formname.page.value ++;
 2388:     }
 2389:     document.$formname.submit();
 2390:     return;
 2391: }
 2392: // ]]>
 2393: </script>
 2394: ENDSCRIPT
 2395:         }
 2396:     } else {
 2397:         $r->print('<span class="LC_info">'
 2398:                  .&mt('There are no transactions to display.')
 2399:                  .'</span>'
 2400:         );
 2401:     }
 2402:     $r->print('<input type="hidden" name="page" value="'.$curr{'page'}.'" />'."\n".
 2403:               '<input type="hidden" name="command" value="showresv" />'."\n");
 2404:     if ($env{'form.origin'} eq 'aboutme') {
 2405:         $r->print('<input type="hidden" name="origin" value="'.$env{'form.origin'}.'" />'."\n".
 2406:                   '<input type="hidden" name="uname" value="'.$env{'form.uname'}.'" />'."\n".
 2407:                   '<input type="hidden" name="udom" value="'.$env{'form.udom'}.'" />'."\n");
 2408:     }
 2409:     $r->print('</form>');
 2410:     return;
 2411: }
 2412: 
 2413: sub show_reservations_log {
 2414:     my ($r) = @_;
 2415:     my $badslot;
 2416:     my $crstype = &Apache::loncommon::course_type();
 2417:     if ($env{'form.slotname'} eq '') {
 2418:         $r->print('<div class="LC_warning">'.&mt('No slot name provided').'</div>');
 2419:         $badslot = 1;
 2420:     } else {
 2421:         my %slot=&Apache::lonnet::get_slot($env{'form.slotname'});
 2422:         if (keys(%slot) == 0) {
 2423:             $r->print('<div class="LC_warning">'.&mt('Invalid slot name: [_1]',$env{'form.slotname'}).'</div>');
 2424:             $badslot = 1;
 2425:         } elsif ($slot{type} ne 'schedulable_student') {
 2426:             my $description = &get_description($env{'form.slotname'},\%slot);
 2427:             $r->print('<div class="LC_warning">');
 2428:             if ($crstype eq 'Community') {
 2429:                 $r->print(&mt('Reservation history unavailable for non-member-reservable slot: [_1].',$description));
 2430:             } else {
 2431:                 $r->print(&mt('Reservation history unavailable for non-student-reservable slot: [_1].',$description));
 2432:             }
 2433:             $r->print('</div>');
 2434:             $badslot = 1;
 2435:         }
 2436:     }
 2437:     if ($badslot) {
 2438:         $r->print('<p><a href="/adm/slotrequest?command=showslots">'.
 2439:                   &mt('Return to slot list').'</a></p>');
 2440:         return;
 2441:     }
 2442:     my $formname = 'reservationslog';
 2443:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2444:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2445:     my %slotlog=&Apache::lonnet::dump('nohist_slotreservationslog',$cdom,$cnum);
 2446:     if ((keys(%slotlog))[0]=~/^error\:/) { undef(%slotlog); }
 2447: 
 2448:     my (%log,@allsymbs);
 2449:     if (keys(%slotlog)) {
 2450:         foreach my $key (keys(%slotlog)) {
 2451:             if (ref($slotlog{$key}) eq 'HASH') {
 2452:                 if (ref($slotlog{$key}{'logentry'}) eq 'HASH') {
 2453:                     if ($slotlog{$key}{'logentry'}{'slot'} eq $env{'form.slotname'}) {
 2454:                         $log{$key} = $slotlog{$key};
 2455:                         if ($slotlog{$key}{'logentry'}{'symb'} ne '') {
 2456:                             push(@allsymbs,$slotlog{$key}{'logentry'}{'symb'});
 2457:                         }
 2458:                     }
 2459:                 }
 2460:             }
 2461:         }
 2462:     }
 2463: 
 2464:     $r->print('<form action="/adm/slotrequest" method="post" name="'.$formname.'">');
 2465:     my %saveable_parameters = ('show' => 'scalar',);
 2466:     &Apache::loncommon::store_course_settings('reservationslog',
 2467:                                               \%saveable_parameters);
 2468:     &Apache::loncommon::restore_course_settings('reservationslog',
 2469:                                                 \%saveable_parameters);
 2470:     # set defaults
 2471:     my $now = time();
 2472:     my $defstart = $now - (7*24*3600); #7 days ago
 2473:     my %defaults = (
 2474:                      page           => '1',
 2475:                      show           => '10',
 2476:                      chgcontext     => 'any',
 2477:                      action         => 'any',
 2478:                      symb           => 'any',
 2479:                      log_start_date => $defstart,
 2480:                      log_end_date   => $now,
 2481:                    );
 2482:     my $more_records = 0;
 2483: 
 2484:     # set current
 2485:     my %curr;
 2486:     foreach my $item ('show','page','chgcontext','action','symb') {
 2487:         $curr{$item} = $env{'form.'.$item};
 2488:     }
 2489:     my ($startdate,$enddate) =
 2490:         &Apache::lonuserutils::get_dates_from_form('log_start_date',
 2491:                                                    'log_end_date');
 2492:     $curr{'log_start_date'} = $startdate;
 2493:     $curr{'log_end_date'} = $enddate;
 2494:     foreach my $key (keys(%defaults)) {
 2495:         if ($curr{$key} eq '') {
 2496:             $curr{$key} = $defaults{$key};
 2497:         }
 2498:     }
 2499:     my (%whodunit,%changed,$version);
 2500:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 2501: 
 2502:     my %slot=&Apache::lonnet::get_slot($env{'form.slotname'});
 2503:     my $description = $slot{'description'};
 2504:     $r->print('<span class="LC_fontsize_large">');
 2505:     if ($crstype eq 'Community') {
 2506:         $r->print(&mt('Reservation changes for member-reservable slot: [_1]',$description));
 2507:     } else {
 2508:         $r->print(&mt('Reservation changes for student-reservable slot: [_1]',$description));
 2509:     }
 2510:     $r->print('</span><br />');
 2511:     $r->print(&display_filter($formname,$cdom,$cnum,\%curr,$version,\@allsymbs));
 2512:     my $showntablehdr = 0;
 2513:     my $tablehdr = &Apache::loncommon::start_data_table().
 2514:                    &Apache::loncommon::start_data_table_header_row().
 2515:                    '<th>&nbsp;</th><th>'.&mt('When').'</th><th>'.&mt('Who made the change').
 2516:                    '</th><th>'.&mt('Affected User').'</th><th>'.&mt('Action').'</th>'.
 2517:                    '<th>'.&mt('Resource').'</th><th>'.&mt('Context').'</th>'.
 2518:                    &Apache::loncommon::end_data_table_header_row();
 2519:     my ($minshown,$maxshown);
 2520:     $minshown = 1;
 2521:     my $count = 0;
 2522:     if ($curr{'show'} ne &mt('all')) {
 2523:         $maxshown = $curr{'page'} * $curr{'show'};
 2524:         if ($curr{'page'} > 1) {
 2525:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 2526:         }
 2527:     }
 2528:     my %lt = &reservationlog_contexts($crstype);
 2529:     my (%titles,%maptitles);
 2530:     foreach my $id (sort { $log{$b}{'exe_time'}<=>$log{$a}{'exe_time'} } (keys(%log))) {
 2531:         next if (($log{$id}{'exe_time'} < $curr{'log_start_date'}) ||
 2532:                  ($log{$id}{'exe_time'} > $curr{'log_end_date'}));
 2533:         if ($curr{'show'} ne &mt('all')) {
 2534:             if ($count >= $curr{'page'} * $curr{'show'}) {
 2535:                 $more_records = 1;
 2536:                 last;
 2537:             }
 2538:         }
 2539:         if ($curr{'chgcontext'} ne 'any') {
 2540:             if ($curr{'chgcontext'} eq 'user') {
 2541:                 next if (($log{$id}{'logentry'}{'context'} ne 'user') && 
 2542:                          ($log{$id}{'logentry'}{'context'} ne 'usermanage'));
 2543:             } else {
 2544:                 next if ($log{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 2545:             }
 2546:         }
 2547:         if ($curr{'action'} ne 'any') {
 2548:             next if ($log{$id}{'logentry'}{'action'} ne $curr{'action'});
 2549:         }
 2550:         if ($curr{'symb'} ne 'any') {
 2551:             next if ($log{$id}{'logentry'}{'symb'} ne $curr{'symb'});
 2552:         }
 2553:         $count ++;
 2554:         next if ($count < $minshown);
 2555:         if (!$showntablehdr) {
 2556:             $r->print($tablehdr);
 2557:             $showntablehdr = 1;
 2558:         }
 2559:         if ($whodunit{$log{$id}{'exe_uname'}.':'.$log{$id}{'exe_udom'}} eq '') {
 2560:             $whodunit{$log{$id}{'exe_uname'}.':'.$log{$id}{'exe_udom'}} =
 2561:                 &Apache::loncommon::plainname($log{$id}{'exe_uname'},$log{$id}{'exe_udom'});
 2562:         }
 2563:         if ($changed{$log{$id}{'uname'}.':'.$log{$id}{'udom'}} eq '') {
 2564:             $changed{$log{$id}{'uname'}.':'.$log{$id}{'udom'}} =
 2565:                 &Apache::loncommon::plainname($log{$id}{'uname'},$log{$id}{'udom'});
 2566:         }
 2567:         my $symb = $log{$id}{'logentry'}{'symb'};
 2568:         my $title = &get_resource_title($symb,\%titles,\%maptitles); 
 2569:         my $chgcontext = $log{$id}{'logentry'}{'context'};
 2570:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 2571:             $chgcontext = $lt{$chgcontext};
 2572:         }
 2573:         my $chgaction = $log{$id}{'logentry'}{'action'};
 2574:         if ($chgaction ne '' && $lt{$chgaction} ne '') {
 2575:             $chgaction = $lt{$chgaction}; 
 2576:         }
 2577:         $r->print(&Apache::loncommon::start_data_table_row().'<td>'.$count.'</td><td>'.&Apache::lonlocal::locallocaltime($log{$id}{'exe_time'}).'</td><td>'.$whodunit{$log{$id}{'exe_uname'}.':'.$log{$id}{'exe_udom'}}.'</td><td>'.$changed{$log{$id}{'uname'}.':'.$log{$id}{'udom'}}.'</td><td>'.$chgaction.'</td><td>'.$title.'</td><td>'.$chgcontext.'</td>'.&Apache::loncommon::end_data_table_row()."\n");
 2578:     }
 2579:     if ($showntablehdr) {
 2580:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 2581:         if (($curr{'page'} > 1) || ($more_records)) {
 2582:             $r->print('<p>');
 2583:             if ($curr{'page'} > 1) {
 2584:                 $r->print('<input type="button" onclick="javascript:chgPage('."'previous'".');" value="'.
 2585:                           &mt('Previous [_1] changes',$curr{'show'}).'" />');
 2586:             }
 2587:             if ($more_records) {
 2588:                 $r->print('<input type="button" onclick="javascript:chgPage('."'next'".');" value="'.
 2589:                           &mt('Next [_1] changes',$curr{'show'}).'" />');
 2590:             }
 2591:             $r->print('</p>');
 2592:             $r->print(<<"ENDSCRIPT");
 2593: <script type="text/javascript">
 2594: function chgPage(caller) {
 2595:     if (caller == 'previous') {
 2596:         document.$formname.page.value --;
 2597:     }
 2598:     if (caller == 'next') {
 2599:         document.$formname.page.value ++;
 2600:     }
 2601:     document.$formname.submit();
 2602:     return;
 2603: }
 2604: </script>
 2605: ENDSCRIPT
 2606:         }
 2607:     } else {
 2608:         $r->print(&mt('There are no records to display.'));
 2609:     }
 2610:     $r->print('<input type="hidden" name="page" value="'.$curr{'page'}.'" />'.
 2611:               '<input type="hidden" name="slotname" value="'.$env{'form.slotname'}.'" />'.
 2612:               '<input type="hidden" name="command" value="slotlog" /></form>'.
 2613:               '<p><a href="/adm/slotrequest?command=showslots">'.
 2614:               &mt('Return to slot list').'</a></p>');
 2615:     return;
 2616: }
 2617: 
 2618: sub get_resource_title {
 2619:     my ($symb,$titles,$maptitles) = @_;
 2620:     my $title;
 2621:     if ((ref($titles) eq 'HASH') && (ref($maptitles) eq 'HASH')) { 
 2622:         if (defined($titles->{$symb})) {
 2623:             $title = $titles->{$symb};
 2624:         } else {
 2625:             $title = &Apache::lonnet::gettitle($symb);
 2626:             my $maptitle;
 2627:             my ($mapurl) = &Apache::lonnet::decode_symb($symb);
 2628:             if (defined($maptitles->{$mapurl})) {
 2629:                 $maptitle = $maptitles->{$mapurl};
 2630:             } else {
 2631:                 if ($mapurl eq $env{'course.'.$env{'request.course.id'}.'.url'}) {
 2632:                     $maptitle=&mt('Main Content');
 2633:                 } else {
 2634:                     $maptitle=&Apache::lonnet::gettitle($mapurl);
 2635:                 }
 2636:                 $maptitles->{$mapurl} = $maptitle;
 2637:             }
 2638:             if ($maptitle ne '') {
 2639:                 $title .= ' '.&mt('(in [_1])',$maptitle);
 2640:             }
 2641:             $titles->{$symb} = $title;
 2642:         }
 2643:     } else {
 2644:         $title = $symb;
 2645:     }
 2646:     return $title;
 2647: }
 2648: 
 2649: sub reservationlog_contexts {
 2650:     my ($crstype) = @_;
 2651:     my %lt = &Apache::lonlocal::texthash (
 2652:                                              any        => 'Any',
 2653:                                              user       => 'By student',
 2654:                                              manage     => 'Via Slot Manager',
 2655:                                              parameter  => 'Via Parameter Manager',
 2656:                                              reserve    => 'Made reservation',
 2657:                                              release    => 'Dropped reservation',
 2658:                                              usermanage => 'By student', 
 2659:                                          );
 2660:     if ($crstype eq 'Community') {
 2661:         $lt{'user'} = &mt('By member');
 2662:         $lt{'usermanage'} = $lt{'user'};
 2663:     }
 2664:     return %lt;
 2665: }
 2666: 
 2667: sub display_filter {
 2668:     my ($formname,$cdom,$cnum,$curr,$version,$allsymbs) = @_;
 2669:     my $nolink = 1;
 2670:     my (%titles,%maptitles);
 2671:     my $output = '<br /><table><tr><td valign="top">'.
 2672:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b><br />'.
 2673:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 2674:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 2675:                  '</td><td>&nbsp;&nbsp;</td>';
 2676:     my $startform =
 2677:         &Apache::lonhtmlcommon::date_setter($formname,'log_start_date',
 2678:                                             $curr->{'log_start_date'},undef,
 2679:                                             undef,undef,undef,undef,undef,undef,$nolink);
 2680:     my $endform =
 2681:         &Apache::lonhtmlcommon::date_setter($formname,'log_end_date',
 2682:                                             $curr->{'log_end_date'},undef,
 2683:                                             undef,undef,undef,undef,undef,undef,$nolink);
 2684:     my $crstype = &Apache::loncommon::course_type();
 2685:     my %lt = &reservationlog_contexts($crstype);
 2686:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').
 2687:                '</b><br /><table><tr><td>'.&mt('After:').
 2688:                '</td><td>'.$startform.'</td></tr><tr><td>'.&mt('Before:').'</td><td>'.
 2689:                $endform.'</td></tr></table></td><td>&nbsp;&nbsp;</td>';
 2690:     if (ref($allsymbs) eq 'ARRAY') {
 2691:         $output .= '<td valign="top"><b>'.&mt('Resource').'</b><br />'.
 2692:                    '<select name="resource"><option value="any"';
 2693:         if ($curr->{'resource'} eq 'any') {
 2694:             $output .= ' selected="selected"';
 2695:         }
 2696:         $output .=  '>'.&mt('Any').'</option>'."\n";
 2697:         foreach my $symb (@{$allsymbs}) {
 2698:             my $title = &get_resource_title($symb,\%titles,\%maptitles);
 2699:             my $selstr = '';
 2700:             if ($curr->{'resource'} eq $symb) {
 2701:                 $selstr = ' selected="selected"';
 2702:             }
 2703:             $output .= '  <option value="'.$symb.'"'.$selstr.'>'.$title.'</option>';
 2704:         }
 2705:         $output .= '</select></td><td>&nbsp;&nbsp;</td><td valign="top"><b>'.
 2706:                    &mt('Context:').'</b><br /><select name="chgcontext">';
 2707:         foreach my $chgtype ('any','user','manage','parameter') {
 2708:             my $selstr = '';
 2709:             if ($curr->{'chgcontext'} eq $chgtype) {
 2710:                 $output .= $selstr = ' selected="selected"';
 2711:             }
 2712:             $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 2713:         }
 2714:         $output .= '</select></td>';
 2715:     } else {
 2716:         $output .= '<td valign="top"><b>'.&mt('Action').'</b><br />'.
 2717:                    '<select name="action"><option value="any"';
 2718:         if ($curr->{'action'} eq 'any') {
 2719:             $output .= ' selected="selected"';
 2720:         }
 2721:         $output .=  '>'.&mt('Any').'</option>'."\n";
 2722:         foreach my $actiontype ('reserve','release') {
 2723:             my $selstr = '';
 2724:             if ($curr->{'action'} eq $actiontype) {
 2725:                 $output .= $selstr = ' selected="selected"';
 2726:             }
 2727:             $output .= '<option value="'.$actiontype.'"'.$selstr.'>'.$lt{$actiontype}.'</option>'."\n";
 2728:         }
 2729:         $output .= '</select></td>';
 2730:     }
 2731:     $output .= '<td>&nbsp;&nbsp;</td></tr></table>'.
 2732:                '<p><input type="submit" value="'.
 2733:                &mt('Update Display').'" /></p>'.
 2734:                '<p class="LC_info">'.
 2735:                &mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 2736:                   ,'2.9.0');
 2737:     if ($version) {
 2738:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 2739:     }
 2740:     $output .= '</p><hr /><br />';
 2741:     return $output;
 2742: }
 2743: 
 2744: sub slot_change_messaging {
 2745:     my ($setting,$subject,$msg,$action) = @_;
 2746:     my $user = $env{'user.name'};
 2747:     my $domain = $env{'user.domain'};
 2748:     my ($message_status,$comment_status);
 2749:     if ($setting eq 'only_student'
 2750:         || $setting eq 'student_and_user_notes_screen') {
 2751:         $message_status =
 2752:             &Apache::lonmsg::user_normal_msg($user,$domain,$subject,$msg);
 2753:         $message_status = '<li>'.&mt('Sent to you: [_1]',
 2754:                                     $message_status).' </li>';
 2755:     }
 2756:     if ($setting eq 'student_and_user_notes_screen') {
 2757:         $comment_status =
 2758:             &Apache::lonmsg::store_instructor_comment($subject.'<br />'.
 2759:                                                       $msg,$user,$domain);
 2760:         $comment_status = '<li>'.&mt('Entry added to course record (viewable by instructor): [_1]',
 2761:                                     $comment_status).'</li>';
 2762:     }
 2763:     if ($message_status || $comment_status) {
 2764:         my $msgtitle;
 2765:         if ($action eq 'reserve') {
 2766:             $msgtitle = &mt('Status of messages about saved reservation');
 2767:         } elsif ($action eq 'release') {
 2768:             $msgtitle = &mt('Status of messages about dropped reservation');
 2769:         } elsif ($action eq 'nochange') {
 2770:             $msgtitle = &mt('Status of messages about unchanged existing reservation');
 2771:         }
 2772:         return '<span class="LC_info">'.$msgtitle.'</span>'
 2773:                .'<ul>'
 2774:                .$message_status
 2775:                .$comment_status
 2776:                .'</ul><hr />';
 2777:     }
 2778: }
 2779: 
 2780: sub upload_start {
 2781:     my ($r)=@_;    
 2782:     $r->print(
 2783:         &Apache::grades::checkforfile_js()
 2784:        .'<h2>'.&mt('Upload a file containing the slot definitions').'</h2>'
 2785:        .'<form method="post" enctype="multipart/form-data"'
 2786:        .' action="/adm/slotrequest" name="slotupload">'
 2787:        .'<input type="hidden" name="command" value="csvuploadmap" />'
 2788:        .&Apache::lonhtmlcommon::start_pick_box()
 2789:        .&Apache::lonhtmlcommon::row_title(&mt('File'))
 2790:        .&Apache::loncommon::upfile_select_html()
 2791:        .&Apache::lonhtmlcommon::row_closure()
 2792:        .&Apache::lonhtmlcommon::row_title(
 2793:             '<label for="noFirstLine">'
 2794:            .&mt('Ignore First Line')
 2795:            .'</label>')
 2796:        .'<input type="checkbox" name="noFirstLine" id="noFirstLine" />'
 2797:        .&Apache::lonhtmlcommon::row_closure(1)
 2798:        .&Apache::lonhtmlcommon::end_pick_box()
 2799:        .'<p>'
 2800:        .'<input type="button" onclick="javascript:checkUpload(this.form);"'
 2801:        .' value="'.&mt('Next').'" />'
 2802:        .'</p>'
 2803:       .'</form>'
 2804:     );
 2805: }
 2806: 
 2807: sub csvuploadmap_header {
 2808:     my ($r,$datatoken,$distotal)= @_;
 2809:     my $javascript;
 2810:     if ($env{'form.upfile_associate'} eq 'reverse') {
 2811: 	$javascript=&csvupload_javascript_reverse_associate();
 2812:     } else {
 2813: 	$javascript=&csvupload_javascript_forward_associate();
 2814:     }
 2815: 
 2816:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 2817:     my $ignore=&mt('Ignore First Line');
 2818:     my $buttontext = &mt('Reverse Association');
 2819: 
 2820:     $r->print(
 2821:         '<form method="post" enctype="multipart/form-data" action="/adm/slotrequest" name="slotupload">'
 2822:        .'<h2>'.&mt('Identify fields in uploaded list').'</h2>'
 2823:        .'<div class="LC_columnSection">'
 2824:        .&Apache::loncommon::help_open_topic(
 2825:             'Slot About',&mt('Help on slots'))
 2826:        .' '.&Apache::loncommon::help_open_topic(
 2827:             'Slot SelectingField',&mt('Help on selecting Fields'))
 2828:        ."</div>\n"
 2829:        .'<p class="LC_info">'
 2830:        .&mt('Total number of records found in file: [_1]','<b>'.$distotal.'</b>')
 2831:        ."</p>\n"
 2832:     );
 2833:     if ($distotal == 0) {
 2834:         $r->print('<p class="LC_warning">'.&mt('None found').'</p>');
 2835:     }
 2836:     $r->print(
 2837:         '<p>'
 2838:        .&mt('Enter as many fields as you can.').'<br />'
 2839:        .&mt('The system will inform you and bring you back to this page,[_1]if the data selected is insufficient to create the slots.','<br />')
 2840:        .'</p>'
 2841:     );
 2842:     $r->print(
 2843:         '<div class="LC_left_float">'
 2844:        .'<fieldset><legend>'.&mt('Functions').'</legend>'
 2845:        .'<label><input type="checkbox" name="noFirstLine"'.$checked.' />'.$ignore.'</label>'
 2846:        .' <input type="button" value="'.$buttontext
 2847:            .'" onclick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />'
 2848:        .'</fieldset></div><br clear="all" />'
 2849:     );
 2850: 
 2851:     $r->print(<<ENDPICK);
 2852: <input type="hidden" name="associate"  value="" />
 2853: <input type="hidden" name="datatoken"  value="$datatoken" />
 2854: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 2855: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 2856: <input type="hidden" name="upfile_associate" 
 2857:                                        value="$env{'form.upfile_associate'}" />
 2858: <input type="hidden" name="command"    value="csvuploadassign" />
 2859: <script type="text/javascript" language="Javascript">
 2860: // <![CDATA[
 2861: $javascript
 2862: // ]]>
 2863: </script>
 2864: ENDPICK
 2865:     return '';
 2866: 
 2867: }
 2868: 
 2869: sub csvuploadmap_footer {
 2870:     my ($request,$i,$keyfields) =@_;
 2871:     my $buttontext = &mt('Create Slots');
 2872:     $request->print(<<ENDPICK);
 2873: <input type="hidden" name="nfields" value="$i" />
 2874: <input type="hidden" name="keyfields" value="$keyfields" />
 2875: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
 2876: </form>
 2877: ENDPICK
 2878: }
 2879: 
 2880: sub csvupload_javascript_reverse_associate {
 2881:     my $error1=&mt('You need to specify the name, start time, end time and a type.');
 2882:     return(<<ENDPICK);
 2883:   function verify(vf) {
 2884:     var foundstart=0;
 2885:     var foundend=0;
 2886:     var foundname=0;
 2887:     var foundtype=0;
 2888:     for (i=0;i<=vf.nfields.value;i++) {
 2889:       tw=eval('vf.f'+i+'.selectedIndex');
 2890:       if (i==0 && tw!=0) { foundname=1; }
 2891:       if (i==1 && tw!=0) { foundtype=1; }
 2892:       if (i==2 && tw!=0) { foundstat=1; }
 2893:       if (i==3 && tw!=0) { foundend=1; }
 2894:     }
 2895:     if (foundstart==0 && foundend==0 && foundtype==0 && foundname==0) {
 2896: 	alert('$error1');
 2897: 	return;
 2898:     }
 2899:     vf.submit();
 2900:   }
 2901:   function flip(vf,tf) {
 2902:   }
 2903: ENDPICK
 2904: }
 2905: 
 2906: sub csvupload_javascript_forward_associate {
 2907:     my $error1=&mt('You need to specify the name, start time, end time and a type.');
 2908:   return(<<ENDPICK);
 2909:   function verify(vf) {
 2910:     var foundstart=0;
 2911:     var foundend=0;
 2912:     var foundname=0;
 2913:     var foundtype=0;
 2914:     for (i=0;i<=vf.nfields.value;i++) {
 2915:       tw=eval('vf.f'+i+'.selectedIndex');
 2916:       if (tw==1) { foundname=1; }
 2917:       if (tw==2) { foundtype=1; }
 2918:       if (tw==3) { foundstat=1; }
 2919:       if (tw==4) { foundend=1; }
 2920:     }
 2921:     if (foundstart==0 && foundend==0 && foundtype==0 && foundname==0) {
 2922: 	alert('$error1');
 2923: 	return;
 2924:     }
 2925:     vf.submit();
 2926:   }
 2927:   function flip(vf,tf) {
 2928:   }
 2929: ENDPICK
 2930: }
 2931: 
 2932: sub csv_upload_map {
 2933:     my ($r)= @_;
 2934: 
 2935:     my $datatoken;
 2936:     if (!$env{'form.datatoken'}) {
 2937: 	$datatoken=&Apache::loncommon::upfile_store($r);
 2938:     } else {
 2939:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 2940:         if ($datatoken ne '') {
 2941:             &Apache::loncommon::load_tmp_file($r,$datatoken);
 2942:         }
 2943:     }
 2944:     my @records=&Apache::loncommon::upfile_record_sep();
 2945:     if ($env{'form.noFirstLine'}) { shift(@records); }
 2946:     &csvuploadmap_header($r,$datatoken,$#records+1);
 2947:     my ($i,$keyfields);
 2948:     if (@records) {
 2949: 	my @fields=&csvupload_fields();
 2950: 
 2951: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 2952: 	    &Apache::loncommon::csv_print_samples($r,\@records);
 2953: 	    $i=&Apache::loncommon::csv_print_select_table($r,\@records,
 2954: 							  \@fields);
 2955: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 2956: 	    chop($keyfields);
 2957: 	} else {
 2958: 	    unshift(@fields,['none','']);
 2959: 	    $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
 2960: 							    \@fields);
 2961: 	    my %sone=&Apache::loncommon::record_sep($records[0]);
 2962: 	    $keyfields=join(',',sort(keys(%sone)));
 2963: 	}
 2964:     }
 2965:     &csvuploadmap_footer($r,$i,$keyfields);
 2966: 
 2967:     return '';
 2968: }
 2969: 
 2970: sub csvupload_fields {
 2971:     return (['name','Slot name'],
 2972: 	    ['type','Type of slot'],
 2973: 	    ['starttime','Start Time of slot'],
 2974: 	    ['endtime','End Time of slot'],
 2975: 	    ['startreserve','Reservation Start Time'],
 2976:             ['endreserve','Reservation End Time'],
 2977:             ['reservationmsg','Message when reservation changed'],
 2978: 	    ['ip','IP or DNS restriction'],
 2979: 	    ['proctor','List of proctor ids'],
 2980: 	    ['description','Slot Description'],
 2981: 	    ['maxspace','Maximum number of reservations'],
 2982: 	    ['symb','Resource Restriction'],
 2983: 	    ['uniqueperiod','Date range of slot exclusion'],
 2984: 	    ['secret','Secret word proctor uses to validate'],
 2985: 	    ['allowedsections','Sections slot is restricted to'],
 2986: 	    ['allowedusers','Users slot is restricted to'],
 2987: 	    );
 2988: }
 2989: 
 2990: sub csv_upload_assign {
 2991:     my ($r,$mgr)= @_;
 2992:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 2993:     if ($datatoken ne '') {
 2994:         &Apache::loncommon::load_tmp_file($r,$datatoken);
 2995:     }
 2996:     my @slotdata = &Apache::loncommon::upfile_record_sep();
 2997:     if ($env{'form.noFirstLine'}) { shift(@slotdata); }
 2998:     my %fields=&Apache::grades::get_fields();
 2999:     $r->print('<h3>'.&mt('Creating Slots').'</h3>');
 3000:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3001:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3002:     my $countdone=0;
 3003:     my @errors;
 3004:     foreach my $slot (@slotdata) {
 3005: 	my %slot;
 3006: 	my %entries=&Apache::loncommon::record_sep($slot);
 3007: 	my $domain;
 3008: 	my $name=$entries{$fields{'name'}};
 3009: 	if ($name=~/^\s*$/) {
 3010: 	    push(@errors,"Did not create slot with no name");
 3011: 	    next;
 3012: 	}
 3013: 	if ($name=~/\s/) { 
 3014: 	    push(@errors,"$name not created -- Name must not contain spaces");
 3015: 	    next;
 3016: 	}
 3017: 	if ($name=~/\W/) { 
 3018: 	    push(@errors,"$name not created -- Name must contain only letters, numbers and _");
 3019: 	    next;
 3020: 	}
 3021: 	if ($entries{$fields{'type'}}) {
 3022: 	    $slot{'type'}=$entries{$fields{'type'}};
 3023: 	} else {
 3024: 	    $slot{'type'}='preassigned';
 3025: 	}
 3026: 	if ($slot{'type'} ne 'preassigned' &&
 3027: 	    $slot{'type'} ne 'schedulable_student') {
 3028: 	    push(@errors,"$name not created -- invalid type ($slot{'type'}) must be either preassigned or schedulable_student");
 3029: 	    next;
 3030: 	}
 3031: 	if ($entries{$fields{'starttime'}}) {
 3032: 	    $slot{'starttime'}=&UnixDate($entries{$fields{'starttime'}},"%s");
 3033: 	}
 3034: 	if ($entries{$fields{'endtime'}}) {
 3035: 	    $slot{'endtime'}=&UnixDate($entries{$fields{'endtime'}},"%s");
 3036: 	}
 3037: 
 3038: 	# start/endtime must be defined and greater than zero
 3039: 	if (!$slot{'starttime'}) {
 3040: 	    push(@errors,"$name not created -- Invalid start time");
 3041: 	    next;
 3042: 	}
 3043: 	if (!$slot{'endtime'}) {
 3044: 	    push(@errors,"$name not created -- Invalid end time");
 3045: 	    next;
 3046: 	}
 3047: 	if ($slot{'starttime'} > $slot{'endtime'}) {
 3048: 	    push(@errors,"$name not created -- Slot starts after it ends");
 3049: 	    next;
 3050: 	}
 3051: 
 3052: 	if ($entries{$fields{'startreserve'}}) {
 3053:             my $date = &UnixDate($entries{$fields{'startreserve'}},"%s");
 3054:             if ($date eq '') {
 3055:                 push(@errors,"$name -- No reservation start time set for slot -- value provided had invalid format");
 3056:             } else {
 3057:                 $slot{'startreserve'} = $date;
 3058:             }
 3059: 	}
 3060: 	if (defined($slot{'startreserve'})
 3061: 	    && $slot{'startreserve'} > $slot{'starttime'}) {
 3062: 	    push(@errors,"$name not created -- Slot's reservation start time is after the slot's start time.");
 3063: 	    next;
 3064: 	}
 3065: 
 3066:         if ($entries{$fields{'endreserve'}}) {
 3067:             my $date = &UnixDate($entries{$fields{'endreserve'}},"%s");
 3068:             if ($date eq '') {
 3069:                 push(@errors,"$name -- No reservation end time set for slot -- value provided had invalid format");
 3070:             } else {
 3071:                 $slot{'endreserve'} = $date;
 3072:             }
 3073:         }
 3074:         if (defined($slot{'endreserve'})
 3075:             && $slot{'endreserve'} > $slot{'starttime'}) {
 3076:             push(@errors,"$name not created -- Slot's reservation end time is after the slot's start time.");
 3077:             next;
 3078:         }
 3079: 
 3080:         if ($slot{'type'} eq 'schedulable_student') {
 3081:             if ($entries{$fields{'reservationmsg'}}) {
 3082:                  if (($entries{$fields{'reservationmsg'}} eq 'only_student') ||
 3083:                      ($entries{$fields{'reservationmsg'}} eq 'student_and_user_notes_screen')) {
 3084:                       $slot{'reservationmsg'}=$entries{$fields{'reservationmsg'}};
 3085:                  } else {
 3086:                       unless (($entries{$fields{'reservationmsg'}} eq 'none') ||
 3087:                               ($entries{$fields{'reservationmsg'}} eq '')) {
 3088:                           push(@errors,"$name -- Slot's reservationmsg setting ignored - not one of: 'only_student', 'student_and_user_notes_screen', 'none' or ''");
 3089:                       }
 3090:                  }
 3091:             }
 3092:         }
 3093: 
 3094: 	foreach my $key ('ip','proctor','description','maxspace',
 3095: 			 'secret','symb') {
 3096: 	    if ($entries{$fields{$key}}) {
 3097: 		$slot{$key}=$entries{$fields{$key}};
 3098:                 if ($key eq 'maxspace') {
 3099:                     $slot{$key} =~ s/\D+//g;
 3100:                 }
 3101: 	    }
 3102: 	}
 3103:         if ($entries{$fields{'allowedusers'}}) {
 3104:             $entries{$fields{'allowedusers'}} =~ s/^\s+//;
 3105:             $entries{$fields{'allowedusers'}} =~ s/\s+$//;
 3106:             my @allowedusers;
 3107:             foreach my $poss (split(/\s*,\s*/,$entries{$fields{'allowedusers'}})) {
 3108:                 my ($possuname,$possudom) = split(/:/,$poss);
 3109:                 if (($possuname =~ /^$match_username$/) && ($possudom =~ /^$match_domain$/)) {
 3110:                     unless (grep(/^\Q$poss\E$/,@allowedusers)) {
 3111:                         push(@allowedusers,$poss);
 3112:                     }
 3113:                 }
 3114:             }
 3115:             if (@allowedusers > 0) {
 3116:                 $slot{'allowedusers'} = join(',',@allowedusers);
 3117:             }
 3118:         }
 3119:         if ($entries{$fields{'allowedsections'}}) {
 3120:             $entries{$fields{'allowedsections'}} =~ s/^\s+//;
 3121:             $entries{$fields{'allowedsections'}} =~ s/\s+$//;
 3122:             my @allowedsections;
 3123:             foreach my $poss (split(/\s*,\s*/,$entries{$fields{'allowedsections'}})) {
 3124:                 if (($poss !~ /\W/) && ($poss ne 'none')) {
 3125:                     unless (grep(/^\Q$poss\E$/,@allowedsections)) {
 3126:                         push(@allowedsections,$poss);
 3127:                     }
 3128:                 }
 3129:             }
 3130:             if (@allowedsections > 0) {
 3131:                 $slot{'allowedsections'} = join(',',@allowedsections);
 3132:             }
 3133:         }
 3134: 	if ($entries{$fields{'uniqueperiod'}}) {
 3135:             my ($start,$end)= map { &UnixDate($_,"%s"); } split(',',$entries{$fields{'uniqueperiod'}});
 3136:             if (($start ne '') && ($end ne '')) {
 3137:                 $slot{'uniqueperiod'}=[$start,$end];
 3138:             } else {
 3139:                 push(@errors,"$name -- Slot's unique period ignored -- one or both of the comma separated values for start and end had an invalid format");
 3140:             }
 3141: 	}
 3142: 	if (ref($slot{'uniqueperiod'}) eq 'ARRAY' 
 3143: 	    && $slot{'uniqueperiod'}[0] > $slot{'uniqueperiod'}[1]) {
 3144: 	    push(@errors,"$name not created -- Slot's unique period start time is later than the unique period's end time.");
 3145: 	    next;
 3146: 	}
 3147: 
 3148: 	&Apache::lonnet::cput('slots',{$name=>\%slot},$cdom,$cname);
 3149: 	$r->print('.');
 3150: 	$r->rflush();
 3151: 	$countdone++;
 3152:     }
 3153:     if ($countdone) {
 3154:         &Apache::lonnet::devalidate_slots_cache($cname,$cdom); 
 3155:     }
 3156:     $r->print('<p>'.&mt('Created [quant,_1,slot]',$countdone)."\n".'</p>');
 3157:     foreach my $error (@errors) {
 3158: 	$r->print('<p><span class="LC_warning">'.$error.'</span></p>'."\n");
 3159:     }
 3160:     &show_table($r,$mgr);
 3161:     return '';
 3162: }
 3163: 
 3164: sub slot_command_titles {
 3165:     my %titles = (
 3166:                  slotlog            => 'Reservation Logs',
 3167:                  showslots          => 'Manage Slots',
 3168:                  showresv           => 'Reservation History',
 3169:                  manageresv         => 'Manage Reservations',
 3170:                  uploadstart        => 'Upload Slots File',
 3171:                  csvuploadmap       => 'Upload Slots File',
 3172:                  csvuploadassign    => 'Upload Slots File',
 3173:                  delete             => 'Slot Deletion',
 3174:                  release            => 'Reservation Result',
 3175:                  remove_reservation => 'Remove Registration',
 3176:                  get_reservation    => 'Request Reservation',
 3177:               );
 3178:     return %titles;
 3179: }
 3180: 
 3181: sub slot_reservationmsg_options {
 3182:     my %options = &Apache::lonlocal::texthash (
 3183:                         only_student  => 'Sent to student',
 3184:         student_and_user_notes_screen => 'Sent to student and added to user notes',
 3185:                                  none => 'None sent and no record in user notes',
 3186:     );
 3187:     return %options;
 3188: }
 3189: 
 3190: sub handler {
 3191:     my $r=shift;
 3192: 
 3193:     &Apache::loncommon::content_type($r,'text/html');
 3194:     &Apache::loncommon::no_cache($r);
 3195:     if ($r->header_only()) {
 3196: 	$r->send_http_header();
 3197: 	return OK;
 3198:     }
 3199: 
 3200:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 3201: 
 3202:     my %crumb_titles = &slot_command_titles();
 3203:     my ($brcrum,$bread_crumbs_component);
 3204: 
 3205:     my $vgr=&Apache::lonnet::allowed('vgr',$env{'request.course.id'});
 3206:     my $mgr=&Apache::lonnet::allowed('mgr',$env{'request.course.id'});
 3207:     my (%slots,$consumed_uniqueperiods);
 3208:     if ($env{'form.command'} eq 'showslots') {
 3209:         if (($vgr ne 'F') && ($mgr ne 'F')) {
 3210:             $env{'form.command'} = 'manageresv'; 
 3211:         }
 3212:     } elsif ($env{'form.command'} eq 'manageresv') {
 3213:         if (($vgr eq 'F') || ($mgr eq 'F')) {
 3214:             $env{'form.command'} = 'showslots';
 3215:         }
 3216:     }
 3217:     my $title='Requesting Another Worktime';
 3218:     if ($env{'form.command'} eq 'showresv') {
 3219:         $title = 'Reservation History';
 3220:         if ($env{'form.origin'} eq 'aboutme') {
 3221:             $brcrum =[{href=>"/adm/$env{'form.udom'}/$env{'form.uname'}/aboutme",text=>'Personal Information Page'}];
 3222:         } else {
 3223:             $brcrum =[{href=>"/adm/slotrequest?command=manageresv",text=>'Manage Reservations'}];
 3224:         }
 3225:         if (ref($brcrum) eq 'ARRAY') {
 3226:             push(@{$brcrum},{href=>"/adm/slotrequest?command=showresv",text=>$title});
 3227:         }
 3228:     } elsif (($env{'form.requestattempt'}) || ($env{'form.command'} eq 'manageresv')) {  
 3229:         if ($env{'form.command'} eq 'manageresv') {
 3230:             $title = 'Manage Reservations';
 3231:             $brcrum =[{href=>"/adm/slotrequest?command=manageresv",text=>$title}];
 3232:         }
 3233:         my ($cnum,$cdom)=&get_course();
 3234:         %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 3235:         $consumed_uniqueperiods = &get_consumed_uniqueperiods(\%slots);
 3236:     } elsif ($vgr eq 'F') {
 3237:         if ($env{'form.command'} =~ /^(slotlog|showslots|uploadstart|csvuploadmap|csvuploadassign|delete|release|remove_registration)$/) {
 3238:             $brcrum =[{href=>"/adm/slotrequest?command=showslots",
 3239:                        text=>$crumb_titles{'showslots'},
 3240:                        help=>'Slot_Use'}];
 3241: 	    $title = 'Managing Slots';
 3242:             $bread_crumbs_component = 'Slots';
 3243:             unless ($env{'form.command'} eq 'showslots') {
 3244:                 if (ref($brcrum) eq 'ARRAY') {
 3245:                     push(@{$brcrum},{href=>"/adm/slotrequest?command=$env{'form.command'}",text=>$crumb_titles{$env{'form.command'}}});
 3246:                 }
 3247:             }
 3248:         }
 3249:     } elsif ($env{'form.command'} eq 'release') {
 3250:         if ($env{'form.context'} eq 'usermanage') {
 3251:             $brcrum =[{href=>"/adm/slotrequest?command=manageresv",
 3252:                        text=>$crumb_titles{'showslots'}}];
 3253:             $title = 'Manage Reservations';
 3254:             if (ref($brcrum) eq 'ARRAY') {
 3255:                 push(@{$brcrum},{href=>"/adm/slotrequest?command=$env{'form.command'}",text=>$crumb_titles{$env{'form.command'}}});
 3256:             }
 3257:         }
 3258:     } else {
 3259:         $brcrum =[];
 3260:     }
 3261:     my ($symb,$js,$available,$allavailable,$got_slots);
 3262:     $available = [];
 3263:     if ($env{'form.requestattempt'}) {
 3264:         $symb=&unescape($env{'form.symb'});
 3265:         @{$got_slots}=&check_for_reservation($symb,'allslots');
 3266:     }
 3267:     if (($env{'form.requestattempt'}) || ($env{'form.command'} eq 'manageresv')) {
 3268:         $js = &reservation_js(\%slots,$consumed_uniqueperiods,$available,$got_slots,$symb);
 3269:     }
 3270:     &start_page($r,$title,$brcrum,$bread_crumbs_component,$js,$mgr);
 3271: 
 3272:     if ($env{'form.command'} eq 'manageresv') {
 3273:         $allavailable = $available;
 3274:         undef($available);
 3275:         undef($got_slots);
 3276:         my $crstype = &Apache::loncommon::course_type();
 3277:         &manage_reservations($r,$crstype,\%slots,$consumed_uniqueperiods,$allavailable);
 3278:     } elsif ($env{'form.command'} eq 'showresv') {
 3279:         &show_reservations($r,$env{'form.uname'},$env{'form.udom'});
 3280:     } elsif ($env{'form.command'} eq 'showslots' && $vgr eq 'F') {
 3281: 	&show_table($r,$mgr);
 3282:     } elsif ($env{'form.command'} eq 'remove_registration' && $mgr eq 'F') {
 3283: 	&remove_registration($r);
 3284:     } elsif ($env{'form.command'} eq 'release' && $mgr eq 'F') {
 3285: 	if ($env{'form.entry'} eq 'remove all') {
 3286: 	    &release_all_slot($r,$mgr);
 3287: 	} else {
 3288: 	    &release_slot($r,undef,undef,undef,$mgr);
 3289: 	}
 3290:     } elsif ($env{'form.command'} eq 'delete' && $mgr eq 'F') {
 3291: 	&delete_slot($r);
 3292:     } elsif ($env{'form.command'} eq 'uploadstart' && $mgr eq 'F') {
 3293: 	&upload_start($r);
 3294:     } elsif ($env{'form.command'} eq 'csvuploadmap' && $mgr eq 'F') {
 3295: 	&csv_upload_map($r);
 3296:     } elsif ($env{'form.command'} eq 'csvuploadassign' && $mgr eq 'F') {
 3297: 	if ($env{'form.associate'} ne 'Reverse Association') {
 3298: 	    &csv_upload_assign($r,$mgr);
 3299: 	} else {
 3300: 	    if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 3301: 		$env{'form.upfile_associate'} = 'reverse';
 3302: 	    } else {
 3303: 		$env{'form.upfile_associate'} = 'forward';
 3304: 	    }
 3305: 	    &csv_upload_map($r);
 3306: 	}
 3307:     } elsif (($env{'form.command'} eq 'slotlog') && ($vgr eq 'F')) {
 3308:         &show_reservations_log($r);
 3309:     } else {
 3310: 	my $symb=&unescape($env{'form.symb'});
 3311: 	if (!defined($symb)) {
 3312: 	    &fail($r,'not_valid');
 3313: 	    return OK;
 3314: 	}
 3315: 	my (undef,undef,$res)=&Apache::lonnet::decode_symb($symb);
 3316: 	my $useslots = &Apache::lonnet::EXT("resource.0.useslots",$symb);
 3317: 	if ($useslots ne 'resource' 
 3318: 	    && $useslots ne 'map' 
 3319: 	    && $useslots ne 'map_map') {
 3320: 	    &fail($r,'not_available');
 3321: 	    return OK;
 3322: 	}
 3323: 	$env{'request.symb'}=$symb;
 3324: 	my $type = ($res =~ /\.task$/) ? 'Task'
 3325: 	                               : 'problem';
 3326: 	my ($status) = &Apache::lonhomework::check_slot_access('0',$type);
 3327: 	if ($status eq 'CAN_ANSWER' ||
 3328: 	    $status eq 'NEEDS_CHECKIN' ||
 3329: 	    $status eq 'WAITING_FOR_GRADE') {
 3330: 	    &fail($r,'not_allowed');
 3331: 	    return OK;
 3332: 	}
 3333: 	if ($env{'form.requestattempt'}) {
 3334:             $r->print('<div class="LC_left_float">'); 
 3335: 	    &show_choices($r,$symb,undef,undef,\%slots,$consumed_uniqueperiods,$available,$got_slots);
 3336:             $r->print('</div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 3337: 	} elsif ($env{'form.command'} eq 'release') {
 3338: 	    &release_slot($r,$symb);
 3339: 	} elsif ($env{'form.command'} eq 'get') {
 3340: 	    &get_slot($r,$symb);
 3341: 	} elsif ($env{'form.command'} eq 'change') {
 3342:             if ($env{'form.nochange'}) {
 3343:                 my $slot_name = $env{'form.releaseslot'};
 3344:                 my @slots = &check_for_reservation($symb,'allslots');
 3345:                 my $msg;
 3346:                 if (($slot_name ne '') && (grep(/^\Q$slot_name\E/,@slots))) { 
 3347:                      my %slot=&Apache::lonnet::get_slot($env{'form.releaseslot'});
 3348:                      my $description=&get_description($slot_name,\%slot);
 3349:                      $msg = '<span style="font-weight: bold;">'.
 3350:                             &mt('Unchanged reservation: [_1]',$description).'</span><br /><br />';
 3351:                      my $person = 
 3352:                          &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'});
 3353:                      my $subject = &mt('Reservation unchanged: [_1]',$description);
 3354:                      my $msgbody = &mt('No change to existing registration by [_1] for [_2].',$person,$description);
 3355:                      $msg .= &slot_change_messaging($slot{'reservationmsg'},$subject,$msgbody,'nochange');
 3356:                 } else {
 3357:                     $msg = '<span class="LC_warning">'.&mt('Reservation no longer reported as available.').'</span>';
 3358:                 }
 3359:                 $r->print($msg);
 3360:                 &return_link($r);
 3361: 	    } elsif (&get_slot($r,$symb,$env{'form.releaseslot'},1)) {
 3362: 		&release_slot($r,$symb,$env{'form.releaseslot'});
 3363: 	    }
 3364: 	} else {
 3365: 	    $r->print('<p>'.&mt('Unknown command: [_1]',$env{'form.command'}).'</p>');
 3366: 	}
 3367:     }
 3368:     &end_page($r);
 3369:     return OK;
 3370: }
 3371: 
 3372: 1;
 3373: __END__

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