File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.184: download - view: text, annotated - select for diffs
Mon Jun 11 21:29:44 2007 UTC (16 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: version_2_4_X, version_2_4_1, HEAD
- BUG#5290 handle uploading of files with no directories correctly

    1: # The LearningOnline Network
    2: # portfolio browser
    3: #
    4: # $Id: portfolio.pm,v 1.184 2007/06/11 21:29:44 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or 
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::portfolio;
   30: use strict;
   31: use Apache::Constants qw(:common :http);
   32: use Apache::loncommon;
   33: use Apache::lonnet;
   34: use Apache::lontexconvert;
   35: use Apache::lonfeedback;
   36: use Apache::lonlocal;
   37: use Apache::lonnet;
   38: use Apache::longroup;
   39: use Apache::lonhtmlcommon;
   40: use HTML::Entities;
   41: use LONCAPA;
   42: 
   43: sub group_args {
   44:     my $output;
   45:     if (defined($env{'form.group'})) {
   46:         $output .= '&group='.$env{'form.group'};
   47: 	if (defined($env{'form.ref'})) {
   48: 	    $output .= '&ref='.$env{'form.ref'};
   49: 	}
   50:     }
   51:     return $output;
   52: }
   53: 
   54: sub group_form_data {
   55:     my $output;
   56:     if (defined($env{'form.group'})) {
   57: 	$output = '<input type="hidden" name="group" value="'.$env{'form.group'}.'" />';
   58: 	if (exists($env{'form.ref'})) {
   59: 	    $output .= '<input type="hidden" name="ref" value="'.
   60: 		$env{'form.ref'}.'" />';
   61: 	}
   62:     }
   63:     return $output;
   64: } 
   65: 
   66: # receives a file name and path stub from username/userfiles/portfolio/
   67: # returns an anchor tag consisting encoding filename and currentpath
   68: sub make_anchor {
   69:     my ($url, $anchor_fields, $inner_text) = @_;
   70:     if ($$anchor_fields{'continue'} ne 'true') {$$anchor_fields{'continue'} = 'false'};
   71:     my $anchor = '<a href="'.$url.'?';
   72:     foreach my $field_name (keys(%$anchor_fields)) {
   73:         $anchor .= $field_name.'='.$$anchor_fields{$field_name}.'&amp;';
   74:     }
   75:     $anchor =~ s/&amp;$//;
   76:     $anchor .= &group_args();
   77:     $anchor .= '">'.$inner_text.'</a>';
   78:     return $anchor;
   79: }
   80: 
   81: my $dirptr=16384;
   82: sub display_common {
   83:     my ($r,$url,$current_path,$is_empty,$dir_list,$can_upload)=@_;
   84:     my $namespace = &get_namespace();
   85:     my $port_path = &get_port_path();
   86:     if ($can_upload) {
   87:         my $groupitem = &group_form_data();
   88: 
   89:         my $iconpath= $r->dir_config('lonIconsURL') . "/";
   90:         my %text=&Apache::lonlocal::texthash(
   91: 					 'upload' => 'Upload',
   92: 					 'upload_label' =>  
   93: 					 'Upload file to current directory:',
   94: 					 'createdir' => 'Create Subdirectory',
   95: 					 'createdir_label' => 
   96: 					 'Create subdirectory in current directory:');
   97:         my $escuri = &HTML::Entities::encode($r->uri,'&<>"');
   98: 	my $help_fileupload = &Apache::loncommon::help_open_topic('Portfolio AddFiles');
   99: 	my $help_createdir = &Apache::loncommon::help_open_topic('Portfolio CreateDirectory');
  100: 		
  101: 	# FIXME: This line should be deleted once Portfolio uses breadcrumbs
  102: 	$r->print(&Apache::loncommon::help_open_topic('Portfolio About', 'Help on the portfolio'));
  103: 
  104:         $r->print(<<"TABLE"); 
  105: <table id="LC_portfolio_actions">
  106:   <tr id="LC_portfolio_upload">
  107:     <td class="LC_label">
  108:       $text{'upload_label'}
  109:     </td>
  110:     <td class="LC_value">
  111:       <form method="post" enctype="multipart/form-data" action="$escuri">
  112:         $groupitem 
  113:         <input name="uploaddoc" type="file" />
  114: 	<input type="hidden" name="currentpath" value="$current_path" />
  115: 	<input type="hidden" name="action" value="$env{"form.action"}" />
  116: 	<input type="hidden" name="fieldname" value="$env{"form.fieldname"}" />
  117: 	<input type="hidden" name="mode" value="$env{"form.mode"}" />
  118: 	<input type="submit" name="storeupl" value="$text{'upload'}" />$help_fileupload
  119:       </form>
  120:     </td>
  121:   </tr>
  122:   <tr id="LC_portfolio_createdir">
  123:     <td class="LC_label">
  124:       $text{'createdir_label'}
  125:     </td>
  126:     <td class="LC_value">
  127:       <form method="post" action="$escuri">
  128:         <input name="newdir" type="input" />$groupitem
  129:         <input type="hidden" name="currentpath" value="$current_path" />
  130:         <input type="hidden" name="action" value="$env{"form.action"}" />
  131:         <input type="hidden" name="fieldname" value="$env{"form.fieldname"}" />
  132:         <input type="hidden" name="mode" value="$env{"form.mode"}" />
  133:         <input type="submit" name="createdir" value="$text{'createdir'}" />$help_createdir
  134:       </form>
  135:     </td>
  136:   </tr>
  137: </table>
  138: TABLE
  139:     }
  140:     my @tree = split (/\//,$current_path);
  141:     my %anchor_fields = (
  142:         'selectfile'    => $port_path,
  143:         'currentpath'   => '/',
  144:         'mode'          => $env{"form.mode"},
  145:         'fieldname'     => $env{"form.fieldname"},
  146:         'continue'      => $env{"form.continue"}
  147:     );
  148:     $r->print('<span class="LC_current_location">'.&make_anchor($url,\%anchor_fields,$port_path).'/');
  149:     if (@tree > 1){
  150:         my $newCurrentPath = '/';
  151:         for (my $i = 1; $i< @tree; $i++){
  152:             $newCurrentPath .= $tree[$i].'/';
  153:             my %anchor_fields = (
  154:                 'selectfile' => $tree[$i],
  155:                 'currentpath' => $newCurrentPath,
  156:                 'mode' => $env{"form.mode"},
  157:                 'fieldname' => $env{"form.fieldname"},
  158:                 'continue' => $env{"form.continue"}
  159:             );
  160:             $r->print(&make_anchor($url,\%anchor_fields,$tree[$i]).'/');
  161:         }
  162:     }
  163:     $r->print('</span>');
  164:     $r->print(&Apache::loncommon::help_open_topic('Portfolio ChangeDirectory'));
  165:     &Apache::lonhtmlcommon::store_recent($namespace,$current_path,$current_path);
  166:     $r->print('<br /><form method="post" action="'.$url.'?mode='.$env{"form.mode"}.'&amp;fieldname='.$env{"form.fieldname"}.&group_args());
  167:     $r->print('">'.
  168: 	      &Apache::lonhtmlcommon::select_recent($namespace,'currentpath',
  169: 						    'this.form.submit();'));
  170:     $r->print("</form>");
  171: }
  172: 
  173: sub display_directory_line {
  174:     my ($r,$select_mode, $filename, $mtime, $size, $css_class,
  175: 	$line, $access_controls, $curr_access, $now, $version_flag,
  176: 	$href_location, $url, $current_path, $access_admin_text, $versions)=@_;
  177: 
  178:     my $fullpath =  &prepend_group($current_path.$filename);
  179:     $r->print('<tr class="'.$css_class.'">');
  180:     $r->print($line); # contains first two cells of table
  181:     my $lock_info;
  182:     if ($version_flag) { # versioned can't be versioned, so TRUE when root file
  183:         $r->print('<td><img alt="" src="'.&Apache::loncommon::icon($filename).'" /></td>');
  184:         $r->print('<td>'.$version_flag.'</td>');
  185:     } else { # this is a graded or handed back file
  186:         my ($user,$domain) = &get_name_dom();
  187:         my $permissions_hash = &Apache::lonnet::get_portfile_permissions($domain,$user);
  188:         if (defined($$permissions_hash{$fullpath})) {
  189:             foreach my $array_item (@{$$permissions_hash{$fullpath}}) {
  190:                 if (ref($array_item) eq 'ARRAY') {
  191:                     if ($$array_item[-1] eq 'handback') {
  192:                         $lock_info = 'Handback';
  193:                     } elsif ($$array_item[-1] eq 'graded') {
  194:                         $lock_info = 'Graded';
  195:                     }
  196:                  }
  197:             }
  198:         }
  199: 	if ($lock_info) {
  200: 	    my %anchor_fields = ('lockinfo' => $fullpath);
  201: 	    if ($versions) { # hold the folder open
  202: 	        my ($fname,$version,$extension) = &Apache::grades::file_name_version_ext($fullpath);
  203: 	        $fname =~ s|^/||;
  204: 	        $anchor_fields{'showversions'} = $fname.'.'.$extension;
  205: 	    }
  206: 	    $lock_info = &make_anchor(undef,\%anchor_fields,$lock_info);
  207: 	}
  208: 	$r->print('<td colspan="2">'.$lock_info.'</td>');
  209:     }
  210:     # $r->print('<td>'.$$version_flag{$filename}.'</td><td>');
  211:     $r->print('<td>'.&make_anchor($href_location.$filename,undef,$filename).'</td>'); 
  212:     $r->print('<td>'.$size.'</td>');
  213:     $r->print('<td>'.&Apache::lonlocal::locallocaltime($mtime).'</td>');
  214:     if ($select_mode ne 'true') {
  215: 	$r->print('<td><span style="white-space: nowrap">'.
  216: 		  &mt($curr_access).'&nbsp;&nbsp;&nbsp;');
  217:         my %anchor_fields = (
  218:             'access' => $filename,
  219:             'currentpath' => $current_path
  220:         );
  221: 	$r->print(&make_anchor($url, \%anchor_fields, $access_admin_text).'</span></td>');
  222:     }
  223:     $r->print('</tr>'.$/);
  224: }
  225: 
  226: sub display_directory {
  227:     my ($r,$url,$current_path,$is_empty,$dir_list,$group,$can_upload,
  228:         $can_modify,$can_delete,$can_setacl)=@_;
  229:     my $iconpath= $r->dir_config('lonIconsURL') . "/";
  230:     my $display_out;
  231:     my $select_mode;
  232:     my $checked_files;
  233:     my $port_path = &get_port_path();
  234:     my ($uname,$udom) = &get_name_dom();
  235:     my $access_admin_text = &mt('View Status');
  236:     if ($can_setacl) {
  237:         $access_admin_text = &mt('View/Change Status');
  238:     }
  239: 
  240:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
  241:                                                                         $uname);
  242:     my %locked_files = &Apache::lonnet::get_marked_as_readonly_hash(
  243:                                                   $current_permissions,$group);
  244:     my %access_controls = &Apache::lonnet::get_access_controls($current_permissions,$group);
  245:     my $now = time;
  246:     if ($env{"form.mode"} eq 'selectfile') {
  247: 	&select_files($r);
  248: 	$checked_files =&Apache::lonnet::files_in_path($uname,$env{'form.currentpath'});
  249: 	$select_mode = 'true';
  250:     } 
  251:     if ($is_empty && ($current_path ne '/') && $can_delete) {
  252:         $display_out = '<form method="post" action="'.$url.'">'.
  253: 	    &group_form_data().
  254:         '<input type="hidden" name="action" value="deletedir" />'.
  255:         '<input type="submit" name="deletedir" value="'.&mt("Delete Directory").'" />'.
  256:         '<input type="hidden" name="selectfile" value="" />'.
  257:         '<input type="hidden" name="currentpath" value="'.$current_path.'" />'.
  258:         '</form>';
  259:         
  260:         $r->print($display_out);
  261: 	return;
  262:     }
  263:     if ($select_mode eq 'true') {
  264:         $r->print('<form method="post" name="checkselect" action="'.$url.'">');
  265:         $r->print('<table id="LC_browser">'.
  266:             '<tr><th>Select</th><th>&nbsp;</th><th>&nbsp;</th><th>Name</th><th>Size</th><th>Last Modified</th></tr>');
  267:     } else {
  268:         $r->print('<form method="post" action="'.$url.'">');
  269: 	$r->print(&Apache::loncommon::help_open_topic('Portfolio FileList',
  270: 						      'Using the portfolio file list'));
  271:         $r->print('<table id="LC_browser">'.
  272: 		  '<tr><th colspan="2">Actions'.
  273: 		  &Apache::loncommon::help_open_topic('Portfolio FileAction').
  274: 		  '</th><th>&nbsp;</th><th>&nbsp;</th><th>Name'.
  275: 		  &Apache::loncommon::help_open_topic('Portfolio OpenFile').
  276: 		  '</th><th>Size</th><th>Last Modified</th><th>Current Access Status'.
  277: 		  &Apache::loncommon::help_open_topic('Portfolio ShareFile').
  278: 		  '</th></tr>');
  279:     }
  280:     $r->print("\n".&group_form_data()."\n");
  281: 
  282:     my $href_location="/uploaded/$udom/$uname/$port_path".$current_path;
  283:     my $href_edit_location="/editupload/$udom/$uname/$port_path".$current_path;
  284:     my @dir_lines;
  285:     my %versioned;
  286:     foreach my $dir_line (sort 
  287: 		      { 
  288: 			  my ($afile)=split('&',$a,2);
  289: 			  my ($bfile)=split('&',$b,2);
  290: 			  return (lc($afile) cmp lc($bfile));
  291: 		      } (@$dir_list)) {
  292:     	#$strip holds directory/file name
  293:     	#$dom 
  294:     	my ($filename,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef)=split(/\&/,$dir_line,16); 
  295:     	$filename =~ s/\s+$//;
  296:     	my ($fname,$version,$extension) = &Apache::grades::file_name_version_ext($filename);
  297:     	if ($version) {
  298: 	    my $fullpath = &prepend_group($current_path.$fname.'.'.$extension);
  299:     	    push(@{ $versioned{$fullpath} },
  300: 		 [$filename,$dom,$testdir,$size,$mtime,$obs,]);
  301:     	} else {
  302:     	    push(@dir_lines, [$filename,$dom,$testdir,$size,$mtime,$obs]);
  303:     	}
  304:     }
  305:     foreach my $dir_line (@dir_lines) {
  306:         my ($filename,$dom,$testdir,$size,$mtime,$obs) = @$dir_line;
  307:         my ($fname,$version,$extension) = &Apache::grades::file_name_version_ext($filename);
  308:     	if (($filename ne '.') && ($filename ne '..') && ($filename !~ /\.meta$/ ) && ($filename !~ /(.*)\.(\d+)\.([^\.]*)$/)) {
  309:     	    my $version_flag;
  310:     	    my $show_versions;
  311: 	    my $fullpath =  &prepend_group($current_path.$filename);
  312:     	    if ($env{'form.showversions'} =~ /$filename/) {
  313:     	        $show_versions = 'true';
  314:     	    }
  315:     	    if (exists($versioned{$fullpath})) {
  316:     	        my %anchor_fields = (
  317:     	            'selectfile' => $fullpath,
  318:     	            'continue' => 'false',
  319:     	            'currentpath' => $current_path,
  320:     	        );
  321:     	        if ($show_versions) {
  322:     	            # Must preserve other possible showversion files
  323:     	            my $version_remainder = $env{'form.showversions'};
  324:     	            $version_remainder =~ s/$filename//g;    	            
  325:     	            $anchor_fields{'showversions'} = $version_remainder;
  326:                     $version_flag = &make_anchor('portfolio',\%anchor_fields,
  327:                         '<img class="LC_icon" alt="'.&mt('opened folder').'" src="'.$iconpath.'folder_pointer_opened.gif" />');
  328:     	        } else {
  329:     	            # allow multiple files to show versioned
  330:     	            $anchor_fields{'showversions'} = $env{'form.showversions'}.','.$filename;
  331:                     $version_flag = &make_anchor('portfolio',\%anchor_fields,
  332:                         '<img class="LC_icon" alt="'.&mt('closed folder').'" src="'.$iconpath.'folder_pointer_closed.gif" />');
  333:                 }
  334:     	    } else {
  335:     	        $version_flag = '&nbsp;';
  336:     	    }
  337:             if ($dirptr&$testdir) {
  338: 		my $colspan='colspan="2"';
  339:                 if ($select_mode eq 'true'){
  340: 		    undef($colspan);
  341:                 }
  342: 		$r->print('<tr class="LC_browser_folder"><td '.$colspan.'><img alt="'.&mt('closed folder').'" src="'.$iconpath.'folder_closed.gif" /></td>');
  343:                 $r->print('<td>Go to ...</td>');
  344:                 my %anchor_fields = (
  345:                     'selectfile'    => $filename.'/',
  346:                     'currentpath'   => $current_path.$filename.'/',
  347:                     'mode'          => $env{"form.mode"},
  348:                     'fieldname'     => $env{"form.fieldname"},
  349:                     'continue'      => $env{"form.continue"}
  350:                 );  
  351:                 $r->print('<td>'.$version_flag.'</td><td>'.&make_anchor($url,\%anchor_fields,$filename.'/').'</td>'); 
  352:                 $r->print('</tr>'); 
  353:             } else {
  354: 		my $css_class = 'LC_browser_file';
  355: 		my $line;
  356:                 if ($select_mode eq 'true') {
  357:                     $line='<td><input type="checkbox" name="checkfile" value="'.$filename.'"';
  358: 		    if ($$checked_files{$filename} eq 'selected') {
  359:                         $line.=" checked ";
  360:                     }
  361: 		    $line.=' /></td>';
  362:                 } else {
  363:                     if (exists $locked_files{$fullpath}) {
  364:                         my %anchor_fields = (
  365:                             'lockinfo' => $fullpath
  366:                         );
  367:                         $line.='<td colspan="2">'.&make_anchor($url,\%anchor_fields,'Locked').'</td>';
  368: 			$css_class= 'LC_browser_file_locked';
  369:                     } else {
  370:                         if (!$can_modify) {
  371:                             $line .= '<td colspan="2">';
  372:                         } else {
  373:                             $line .= '<td>';
  374:                         }
  375:                         if ($can_delete) {
  376:                             $line .= '<input type="checkbox" name="selectfile" value="'.$filename.'" />';
  377:                         }
  378:                         if ($can_modify) {
  379:                             my $cat='<img class="LC_icon" alt="'.&mt('Catalog Information').
  380:                             '" src="'.&Apache::loncommon::lonhttpdurl('/res/adm/pages/catalog.gif').'" />';
  381:                             my %anchor_fields = (
  382:                                 'rename' => $filename,
  383:                                 currentpath => $current_path
  384:                             );
  385:                             $line .= &make_anchor($url,\%anchor_fields,'Rename');
  386:                             $line .= '</td><td>'.&make_anchor($href_edit_location.$filename.'.meta',\%anchor_fields,$cat);
  387:                             # '<a href="'.$href_edit_location.$filename.'.meta">'.$cat.'</a>';
  388:                         }
  389:                         $line .= '</td>';
  390:                     }
  391:                 }
  392: 		my $curr_access;
  393: 		if ($select_mode ne 'true') {
  394: 		    my $pub_access = 0;
  395: 		    my $guest_access = 0;
  396: 		    my $cond_access = 0;
  397: 		    foreach my $key (sort(keys(%{$access_controls{$fullpath}}))) {
  398: 			my ($num,$scope,$end,$start) = &unpack_acc_key($key);
  399: 			if (($now > $start) && (!$end || $end > $now)) {
  400: 			    if ($scope eq 'public')  {
  401: 				$pub_access = 1;
  402: 			    } elsif ($scope eq 'guest') {
  403: 				$guest_access = 1;
  404: 			    } else {
  405: 				$cond_access = 1;
  406: 			    }
  407: 			}
  408: 		    }
  409: 		    if (!$pub_access && !$guest_access && !$cond_access) {
  410: 			$curr_access = &mt('Private');
  411: 		    } else {
  412: 			my @allaccesses; 
  413: 			if ($pub_access) {
  414: 			    push(@allaccesses,&mt('Public'));
  415: 			}
  416: 			if ($guest_access) {
  417: 			    push(@allaccesses,&mt('Passphrase-protected'));
  418: 			}
  419: 			if ($cond_access) {
  420: 			    push(@allaccesses,&mt('Conditional'));
  421: 			}
  422: 			$curr_access = join('+ ',@allaccesses);
  423: 		    }
  424: 		}
  425:                 &display_directory_line($r,$select_mode, $filename, $mtime, $size, $css_class, $line, 
  426:                                         \%access_controls, $curr_access,$now, $version_flag, $href_location, 
  427:                                         $url, $current_path, $access_admin_text);
  428: 		if ($show_versions) {
  429: 		    foreach my $dir_line (@{ $versioned{$fullpath} }) {
  430: 		        my ($v_filename,$dom,$testdir,$size,$mtime,$obs) =
  431: 			    @$dir_line;
  432:                         $line = '<td colspan="2">&nbsp;</td>';
  433: 			&display_directory_line($r,$select_mode, $v_filename, $mtime, $size, 
  434: 						$css_class, $line, \%access_controls, $curr_access, $now,
  435: 						undef, $href_location, $url, $current_path, $access_admin_text, 1);
  436: 		    }
  437: 		}
  438:             }
  439:         }
  440:     }
  441:     if ($select_mode eq 'true') {
  442:         $r->print('</table>
  443:             <input type="hidden" name="continue" value="true" />
  444:             <input type="hidden" name="fieldname" value="'.$env{'form.fieldname'}.'" />
  445:             <input type="hidden" name="mode" value="selectfile" />
  446:             <input type="submit" name="submit" value="Select checked files, and continue selecting." /><br />
  447:             <input type="button" name="doit" onClick= "finishSelect();" value="Select checked files, and close window" />
  448:             <input type="hidden" name="currentpath" value="'.$current_path.'" />
  449:         </form>');        
  450:     } else {
  451:         $r->print('</table>');
  452:         if ($can_delete) {
  453:             $r->print('
  454:         <input type="submit" name="doit" value="Delete Checked Files" />'.
  455: 	&Apache::loncommon::help_open_topic('Portfolio DeleteFile').'
  456:         <input type="hidden" name="action" value="delete" />
  457:         <input type="hidden" name="currentpath" value="'.$current_path.'" />
  458:         </form>'
  459:             );
  460:         }
  461:     }
  462: }
  463: 
  464: sub open_form {
  465:     my ($r,$url)=@_;
  466:     my @files=&Apache::loncommon::get_env_multiple('form.selectfile');
  467:     $r->print('<form name="portform" method="post" action="'.$url.'">');
  468:     $r->print('<input type="hidden" name="action" value="'.
  469: 	      $env{'form.action'}.'" />');
  470:     $r->print('<input type="hidden" name="confirmed" value="1" />');
  471:     foreach (@files) {
  472:         $r->print('<input type="hidden" name="selectfile" value="'.
  473: 	      $_.'" />');
  474:     }
  475:     $r->print('<input type="hidden" name="currentpath" value="'.
  476: 	      $env{'form.currentpath'}.'" />');
  477: }
  478: 
  479: sub close_form {
  480:     my ($r,$url,$button_text)=@_;
  481:     if (!defined($button_text)) {
  482:         $button_text = {
  483:                          'continue' => &mt('Continue'),
  484:                          'cancel'   => &mt('Cancel'),
  485:                        };
  486:     }
  487:     $r->print('<p><input type="submit" value="'.$button_text->{'continue'}.'" />');
  488:     $r->print(&group_form_data().'</p></form>');
  489:     $r->print('<form action="'.$url.'" method="post">
  490:                <p>
  491:               <input type="hidden" name="currentpath" value="'.
  492: 	      $env{'form.currentpath'}.'" />'.
  493: 	      &group_form_data());
  494:     $r->print("\n".'   <input type="submit" value="'.$button_text->{'cancel'}.'" />
  495:                </p></form>'); 
  496: }
  497: 
  498: sub display_file {
  499:     my ($path,$filename)=@_;
  500:     my $display_file_text;
  501:     my $file_start='<span class="LC_filename">';
  502:     my $file_end='</span>';
  503:     if (!defined($path)) { $path=$env{'form.currentpath'}; }
  504:     if (!defined($filename)) { 
  505:         $filename=$env{'form.selectfile'};
  506:         $display_file_text = $file_start.$path.$filename.$file_end;
  507:     } elsif (ref($filename) eq "ARRAY") {
  508:         foreach my $file (@$filename) {
  509:             $display_file_text .= $file_start.$path.$file.$file_end.'<br />';
  510:         }
  511:     } elsif (ref($filename) eq "SCALAR") {
  512:         $display_file_text = $file_start.$path.$$filename.$file_end;
  513:     } else {
  514: 	$display_file_text = $file_start.$path.$filename.$file_end;
  515:     }
  516:     return $display_file_text;
  517: }
  518: 
  519: sub done {
  520:     my ($message,$url)=@_;
  521:     unless (defined $message) {
  522:         $message='Done';
  523:     }
  524:     my %anchor_fields = (
  525:         'showversions' => $env{'form.showversions'},
  526:         'currentpath' => $env{'form.currentpath'},
  527:         'fieldname' => $env{'form.fieldname'},
  528:         'mode'      => $env{'form.mode'}
  529:     );
  530:     my $result = '<h3>'.&make_anchor($url,\%anchor_fields,&mt($message)).'</h3>';
  531:     return $result;
  532: }
  533: 
  534: sub delete {
  535:     my ($r,$url)=@_;
  536:     my @check;
  537:     my $file_name = $env{'form.currentpath'}.$env{'form.selectfile'};
  538:     $file_name = &prepend_group($file_name);
  539:     my @files=&Apache::loncommon::get_env_multiple('form.selectfile');
  540:     my ($uname,$udom) = &get_name_dom();
  541:     if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
  542:         $r->print("The file is locked and cannot be deleted.<br />");
  543:         $r->print(&done('Back',$url));
  544:     } else {
  545:         if (scalar(@files)) {
  546:             &open_form($r,$url);
  547:             $r->print('<p>'.&mt('Delete').' '.&display_file(undef,\@files).'?</p>');
  548:             &close_form($r,$url);
  549:         } else {
  550:             $r->print("No file was checked to delete.<br />");
  551:             $r->print(&done(undef,$url));
  552:         }
  553:     }
  554: } 
  555: 
  556: sub delete_confirmed {
  557:     my ($r,$url,$group)=@_;
  558:     my @files=&Apache::loncommon::get_env_multiple('form.selectfile');
  559:     my $result;
  560:     my ($uname,$udom) = &get_name_dom();
  561:     my $port_path = &get_port_path();
  562:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
  563:                                                                         $uname);
  564:     foreach my $delete_file (@files) {
  565:         $result=&Apache::lonnet::removeuserfile($uname,$udom,$port_path.
  566: 					       $env{'form.currentpath'}.
  567: 					       $delete_file);
  568:         if ($result ne 'ok') {
  569: 	    $r->print('<span class="LC_error">'.
  570:                      &mt('An error occurred ([_1]) while trying to delete 
  571:                          [_2].',$result,&display_file(undef, $delete_file)).
  572:                       '</span><br /><br />');
  573:         } else {
  574:             $r->print(&mt('File: [_1] deleted.',
  575:                           &display_file(undef,$delete_file)));
  576:             my $file_name = $env{'form.currentpath'}.$delete_file;
  577:             $file_name = &prepend_group($file_name);
  578:             my %access_controls = 
  579:                     &Apache::lonnet::get_access_controls($current_permissions,
  580:                                                          $group,$file_name);
  581:             if (keys(%access_controls) > 0) {
  582:                 my %changes; 
  583:                 foreach my $key (keys(%{$access_controls{$file_name}})) {
  584:                     $changes{'delete'}{$key} = 1;
  585:                 }
  586:                 if (keys(%changes) > 0) {
  587:                     my ($outcome,$deloutcome,$new_values,$translation) =
  588:                     &Apache::lonnet::modify_access_controls($file_name,\%changes,
  589:                                                             $udom,$uname);
  590:                     if ($outcome ne 'ok') {
  591:                            $r->print('<br />'.&mt("An error occurred ([_1]) while ".
  592:                                "trying to delete access controls for the file.",$outcome).
  593:                                '</span><br /><br />');
  594:                     } else {
  595:                         if ($deloutcome eq 'ok') {
  596:                             $r->print('<br />'.&mt('Access controls also deleted for the file.').'<br /><br />');
  597:                         } else {
  598:                             $r->print('<span class="LC_error">'.'<br />'.
  599:                                &mt("An error occurred ([_1]) while ".
  600:                                    "trying to delete access controls for the file.",$deloutcome).
  601:                                    '</span><br /><br />');
  602:                         }
  603:                     }
  604:                 }
  605:             }
  606:         }
  607:     }
  608:     $r->print(&done(undef,$url));
  609: }
  610: 
  611: sub delete_dir {
  612:     my ($r,$url)=@_;
  613:     &open_form($r,$url);
  614:     $r->print('<p>'.&mt('Delete').' '.&display_file().'?</p>');
  615:     &close_form($r,$url);
  616: } 
  617: 
  618: sub delete_dir_confirmed {
  619:     my ($r,$url)=@_;
  620:     my $directory_name = $env{'form.currentpath'};
  621:     $directory_name =~ s|/$||; # remove any trailing slash
  622:     my ($uname,$udom) = &get_name_dom();
  623:     my $namespace = &get_namespace();
  624:     my $port_path = &get_port_path();
  625:     my $result=&Apache::lonnet::removeuserfile($uname,$udom,$port_path.
  626: 					       $directory_name);
  627: 					       
  628:     if ($result ne 'ok') {
  629: 	$r->print('<span class="LC_error"> An error occurred (dir) ('.$result.
  630: 		  ') while trying to delete '.$directory_name.'</span><br />');
  631:     } else {
  632:         # now remove from recent
  633: #        $r->print('<br /> removing '.$directory_name.'<br /');
  634:         &Apache::lonhtmlcommon::remove_recent($namespace,[$directory_name.'/']);
  635:         my @dirs = split m!/!, $directory_name;
  636:         
  637: #        $directory_name =~ m/^(\/*\/)(\/*.)$/;
  638:         $directory_name='/';
  639:         for (my $i=1; $i < (@dirs - 1); $i ++){
  640:             $directory_name .= $dirs[$i].'/';
  641:         }
  642:         $env{'form.currentpath'} = $directory_name;
  643:     }
  644:     $r->print(&done(undef,$url));
  645: }
  646: 
  647: sub rename {
  648:     my ($r,$url)=@_;
  649:     my $file_name = $env{'form.currentpath'}.$env{'form.rename'};
  650:     my ($uname,$udom) = &get_name_dom();
  651:     $file_name = &prepend_group($file_name);
  652:     if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
  653:         $r->print("The file is locked and cannot be renamed.<br />");
  654:         $r->print(&done(undef,$url));
  655:     } else {
  656:         &open_form($r,$url);
  657:         $r->print('<p>'.&mt('Rename').' '.&display_file().' to 
  658:                    <input name="filenewname" type="input" size="50" />?</p>');
  659:         &close_form($r,$url);
  660:     }
  661: }
  662: 
  663: sub rename_confirmed {
  664:     my ($r,$url,$group)=@_;
  665:     my $filenewname=&Apache::lonnet::clean_filename($env{'form.filenewname'});
  666:     my ($uname,$udom) = &get_name_dom();
  667:     my $port_path = &get_port_path();
  668:     if ($filenewname eq '') {
  669: 	$r->print('<span class="LC_error">'.
  670: 		  &mt("Error: no valid filename was provided to rename to.").
  671: 		  '</span><br />');
  672: 	$r->print(&done(undef,$url));
  673: 	return;
  674:     } 
  675:     my $chg_access;
  676:     my $result=
  677: 	&Apache::lonnet::renameuserfile($uname,$udom,
  678:             $port_path.$env{'form.currentpath'}.$env{'form.selectfile'},
  679:             $port_path.$env{'form.currentpath'}.$filenewname);
  680:     if ($result eq 'ok') {
  681:         $chg_access = &access_for_renamed($filenewname,$group,$udom,$uname);
  682:     } else {      
  683: 	$r->print('<span class="LC_error">'.
  684: 		  &mt('An error occurred ([_1]) while trying to rename [_2]'
  685: 		      .' to [_3]',$result,&display_file(),
  686: 		      &display_file('',$filenewname)).'</span><br />');
  687:         return;
  688:     }
  689:     if ($filenewname ne $env{'form.filenewname'}) {
  690:         $r->print(&mt("The new file name was changed from:<br />[_1] to [_2]",
  691: 		      '<strong>'.&display_file('',$env{'form.filenewname'}).'</strong>',
  692: 		      '<strong>'.&display_file('',$filenewname).'</strong>'));
  693:     }
  694:     $r->print($chg_access);
  695:     $r->print(&done(undef,$url));
  696: }
  697: 
  698: sub access_for_renamed {
  699:     my ($filenewname,$group,$udom,$uname) = @_;
  700:     my $oldfile = $env{'form.currentpath'}.$env{'form.selectfile'};
  701:     $oldfile = &prepend_group($oldfile);
  702:     my $newfile = $env{'form.currentpath'}.$filenewname;
  703:     $newfile = &prepend_group($newfile);
  704:     my $current_permissions =
  705: 	&Apache::lonnet::get_portfile_permissions($udom,$uname);
  706:     my %access_controls =
  707: 	&Apache::lonnet::get_access_controls($current_permissions,
  708: 					     $group,$oldfile);
  709:     my $chg_text;
  710:     if (keys(%access_controls) > 0) {
  711:         my %change_old;
  712:         my %change_new;
  713:         foreach my $key (keys(%{$access_controls{$oldfile}})) {
  714:             $change_old{'delete'}{$key} = 1;
  715:             $change_new{'activate'}{$key} = $access_controls{$oldfile}{$key};
  716:         }
  717:         my ($outcome,$deloutcome,$new_values,$translation) =
  718:             &Apache::lonnet::modify_access_controls($oldfile,\%change_old,
  719: 						    $udom,$uname);
  720:         if ($outcome ne 'ok') {
  721:             $chg_text ='<br /><br />'.&mt("An error occurred ([_1]) while ".
  722:                 "trying to delete access control records for the old name.",$outcome).
  723:                 '</span><br />';
  724:         } else {
  725:             if ($deloutcome ne 'ok') {
  726:                 $chg_text = '<br /><br /><span class="LC_error"><br />'.
  727: 		    &mt("An error occurred ([_1]) while ".
  728: 			"trying to delete access control records for the old name.",$deloutcome).
  729: 			'</span><br />';
  730:             }
  731:         }
  732:         ($outcome,$deloutcome,$new_values,$translation) =
  733:             &Apache::lonnet::modify_access_controls($newfile,\%change_new,
  734:                                                     $udom,$uname);
  735:         if ($outcome ne 'ok') {
  736:             $chg_text .= '<br /><br />'.
  737: 		&mt("An error occurred ([_1]) while ".
  738:                 "trying to update access control records for the new name.",$outcome).
  739:                 '</span><br />';
  740:         }
  741:         if ($chg_text eq '') {
  742:             $chg_text = '<br /><br />'.&mt('Access controls updated to reflect the name change.');
  743:         }
  744:     }
  745:     return $chg_text;
  746: }
  747: 
  748: sub display_access {
  749:     my ($r,$url,$group,$can_setacl,$port_path,$action) = @_;
  750:     my ($uname,$udom) = &get_name_dom();
  751:     my $file_name = $env{'form.currentpath'}.$env{'form.access'};
  752:     $file_name = &prepend_group($file_name);
  753:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
  754:                                                                         $uname);
  755:     my %access_controls = &Apache::lonnet::get_access_controls($current_permissions,$group,$file_name);
  756:     my $aclcount = keys(%access_controls);
  757:     my ($header,$info);
  758:     if ($action eq 'chgaccess') {
  759:         $header = '<h3>'.&mt('Allowing others to retrieve file: [_1]',$port_path.$env{'form.currentpath'}.$env{'form.access'}).'</h3>';
  760:         $info .= &mt('Access to this file by others can be set to be one or more of the following types: public, passphrase-protected or conditional.');
  761:         $info .= '<br /><ul><li>'.&mt('Public files are available to anyone without the need for login.');
  762:         $info .= '</li><li>'.&mt('Passphrase-protected files do not require log-in, but will require the viewer to enter the passphrase you set.');
  763:         $info .= '</li><li>'.&explain_conditionals();
  764:         $info .= '</li></ul>'.
  765:                   &mt('A listing of files viewable without log-in is available at: ')."<a href=\"/adm/$udom/$uname/aboutme/portfolio\">http://$ENV{'SERVER_NAME'}/adm/$udom/$uname/aboutme/portfolio</a>.<br />";
  766:         if ($group eq '') {
  767:             $info .= &mt("For logged in users a 'Display file listing' link will also appear (when there are viewable files) on your personal information page:");
  768:         } else {
  769:             $info .= &mt("For logged in users a 'Display file listing' link will also appear (when there are viewable files) on the course information page:");
  770:         }
  771:         $info .= "<br /><a href=\"/adm/$udom/$uname/aboutme\">http://$ENV{'SERVER_NAME'}/adm/$udom/$uname/aboutme</a><br />";
  772:         if ($group ne '') {
  773:             $info .= &mt("Users with privileges to edit course contents may add a course information page to a course using the 'Course Info' button in DOCS").'<br />';
  774:         }
  775:     } else {
  776:         $header = '<h3>'.&mt('Conditional access controls for file: [_1]',$port_path.$env{'form.currentpath'}.$env{'form.access'}).'</h3>'.
  777:                   &explain_conditionals().'<br />';
  778:     }
  779:     if ($can_setacl) {
  780:         &open_form($r,$url);
  781:         $r->print($header.$info);
  782: 	$r->print('<br />'.&Apache::loncommon::help_open_topic('Portfolio ShareFile SetAccess', 'Help on setting up share access'));
  783: 	$r->print(&Apache::loncommon::help_open_topic('Portfolio ShareFile ChangeSetting', 'Help on changing settings'));
  784: 	$r->print(&Apache::loncommon::help_open_topic('Portfolio ShareFile StopAccess', 'Help on removing share access'));
  785:         &access_setting_table($r,$url,$file_name,$access_controls{$file_name},
  786:                               $action);
  787:         my $button_text = {
  788:                         'continue' => &mt('Proceed'),
  789:                         'cancel' => &mt('Back to directory listing'),
  790:                       };
  791:         &close_form($r,$url,$button_text);
  792:     } else {
  793:         $r->print($header);
  794:         if ($aclcount) {  
  795:             $r->print($info);
  796:         }
  797:         &view_access_settings($r,$url,$access_controls{$file_name},$aclcount);
  798:     }
  799: }
  800: 
  801: sub explain_conditionals {
  802:     return
  803:         &mt('Conditional files are accessible to logged-in users with accounts in the LON-CAPA network, who satisfy the conditions you set.').'<br />'."\n".
  804:         &mt('The conditions can include affiliation with a particular course, or a user account in a specific domain.').'<br />'."\n".
  805:         &mt('Alternatively access can be granted to people with specific LON-CAPA usernames and domains.');
  806: }
  807: 
  808: sub view_access_settings {
  809:     my ($r,$url,$access_controls,$aclcount) = @_;
  810:     my ($showstart,$showend);
  811:     my %todisplay;
  812:     foreach my $key (sort(keys(%{$access_controls}))) {
  813:         my ($num,$scope,$end,$start) = &unpack_acc_key($key);
  814:         $todisplay{$scope}{$key} = $$access_controls{$key};
  815:     }
  816:     if ($aclcount) {
  817:         $r->print(&mt('<h4>Current access controls defined for this file:</h4>'));
  818:         $r->print(&Apache::loncommon::start_data_table());
  819:         $r->print(&Apache::loncommon::start_data_table_header_row());
  820:         $r->print('<th>'.&mt('Access control').'</th><th>'.&mt('Dates available').
  821:                   '</th><th>'.&mt('Additional information').'</th>');
  822:         $r->print(&Apache::loncommon::end_data_table_header_row());
  823:         my $count = 1;
  824:         my $chg = 'none';
  825:         &build_access_summary($r,$count,$chg,%todisplay);
  826:         $r->print(&Apache::loncommon::end_data_table());
  827:     } else {
  828:         $r->print(&mt('No access control settings currently exist for this file.<br />' ));
  829:     }
  830:     my %anchor_fields = (
  831:         'currentpath' => $env{'form.currentpath'}
  832:     );
  833:     $r->print('<br />'.&make_anchor($url, \%anchor_fields, &mt('Return to directory listing')));
  834:     return;
  835: }
  836: 
  837: sub build_access_summary {
  838:     my ($r,$count,$chg,%todisplay) = @_; 
  839:     my ($showstart,$showend);
  840:     my %scope_desc = (
  841:                       public => 'Public',
  842:                       guest => 'Passphrase-protected',
  843:                       domains => 'Conditional: domain-based',
  844:                       users => 'Conditional: user-based',
  845:                       course => 'Conditional: course-based',
  846:                      );
  847:     my @allscopes = ('public','guest','domains','users','course');
  848:     foreach my $scope (@allscopes) {
  849:         if ((!(exists($todisplay{$scope}))) || (ref($todisplay{$scope}) ne 'HASH')) {
  850:             next;
  851:         }
  852:         foreach my $key (sort(keys(%{$todisplay{$scope}}))) {
  853:             if ($count) {
  854:                 $r->print(&Apache::loncommon::start_data_table_row());
  855:             }
  856:             my ($num,$scope,$end,$start) = &unpack_acc_key($key);
  857:             my $content = $todisplay{$scope}{$key};
  858:             if ($chg eq 'delete') {
  859:                 $showstart = &mt('Deleted');
  860:                 $showend = $showstart;
  861:             } else {
  862:                 $showstart = localtime($start);
  863:                 if ($end == 0) {
  864:                     $showend = &mt('No end date');
  865:                 } else {
  866:                     $showend = localtime($end);
  867:                 }
  868:             }
  869:             $r->print('<td>'.&mt($scope_desc{$scope}));
  870:             if ($scope eq 'course') {
  871:                 if ($chg ne 'delete') {
  872:                     my $cid = $content->{'domain'}.'_'.$content->{'number'};
  873:                     my %course_description = &Apache::lonnet::coursedescription($cid);
  874:                     $r->print('<br />('.$course_description{'description'}.')');
  875:                 }
  876:             }
  877:             $r->print('</td><td>'.&mt('Start: ').$showstart.
  878:                   '<br />'.&mt('End: ').$showend.'</td><td>');
  879:             if ($chg ne 'delete') {
  880:                 if ($scope eq 'guest') {
  881:                     $r->print(&mt('Passphrase').': '.$content->{'password'});
  882:                 } elsif ($scope eq 'course') {
  883:                     $r->print('<table width="100%"><tr>');
  884:                     $r->print('<th>'.&mt('Roles').'</th><th>'.
  885:                           &mt('Access').'</th><th>'.
  886:                                           &mt('Sections').'</th>');
  887:                     $r->print('<th>'.&mt('Groups').'</th>');
  888:                     $r->print('</tr>');
  889:                     foreach my $id (sort(keys(%{$content->{'roles'}}))) {
  890:                         $r->print('<tr>');
  891:                         foreach my $item ('role','access','section','group') {
  892:                             $r->print('<td>');
  893:                             if ($item eq 'role') {
  894:                                 my $ucscope = $scope;
  895:                                 $ucscope =~ s/^(\w)/uc($1)/e;
  896:                                 my $role_output;
  897:                                 foreach my $role (@{$content->{'roles'}{$id}{$item}}) {
  898:                                     if ($role eq 'all') {
  899:                                         $role_output .= $role.',';
  900:                                     } elsif ($role =~ /^cr/) {
  901:                                         $role_output .= (split('/',$role))[3].',';
  902:                                     } else {
  903:                                         $role_output .= &Apache::lonnet::plaintext($role,$ucscope).',';
  904:                                     }
  905:                                 }
  906:                                 $role_output =~ s/,$//;
  907:                                 $r->print($role_output);
  908:                             } else {
  909:                                 $r->print(join(',',@{$content->{'roles'}{$id}{$item}}));
  910:                             }
  911:                             $r->print('</td>');
  912:                         }
  913: 			$r->print('</tr>');
  914:                     }
  915: 		    $r->print('</table>');
  916:                 } elsif ($scope eq 'domains') {
  917:                     $r->print(&mt('Domains: ').join(',',@{$content->{'dom'}}));
  918:                 } elsif ($scope eq 'users') {
  919:                     my $curr_user_list = &sort_users($content->{'users'});
  920:                     $r->print(&mt('Users: ').$curr_user_list);
  921:                 } else {
  922:                     $r->print('&nbsp;');
  923:                 }
  924:             } else {
  925:                 $r->print('&nbsp;');
  926:             }
  927:             $r->print('</td>');
  928:             $r->print(&Apache::loncommon::end_data_table_row());
  929:             $count ++;
  930:         }
  931:     }
  932: }
  933: 
  934: 
  935: sub update_access {
  936:     my ($r,$url,$group,$port_path) = @_;
  937:     my $totalprocessed = 0;
  938:     my %processing;
  939:     my %title  = (
  940:                          'activate' => 'New control(s) added',
  941:                          'delete'   => 'Existing control(s) deleted',
  942:                          'update'   => 'Existing control(s) modified',
  943:                      );
  944:     my $changes;
  945:     foreach my $chg (sort(keys(%title))) {     
  946:         @{$processing{$chg}} = &Apache::loncommon::get_env_multiple('form.'.$chg);
  947:         $totalprocessed += @{$processing{$chg}};
  948:         foreach my $num (@{$processing{$chg}}) {
  949:             my $scope = $env{'form.scope_'.$num};
  950:             my ($start,$end) = &get_dates_from_form($num);
  951:             my $newkey = $num.':'.$scope.'_'.$end.'_'.$start;
  952:             if ($chg eq 'delete') {
  953:                 $$changes{$chg}{$newkey} = 1;
  954:             } else {
  955:                 $$changes{$chg}{$newkey} = 
  956:                             &build_access_record($num,$scope,$start,$end,$chg);
  957:             }
  958:         }
  959:     }
  960:     my $file_name = $env{'form.currentpath'}.$env{'form.selectfile'};
  961:     $r->print('<h3>'.&mt('Allowing others to retrieve file: [_1]',
  962:               $port_path.$file_name).'</h3>'."\n");
  963:     $file_name = &prepend_group($file_name);
  964:     my ($uname,$udom) = &get_name_dom();
  965:     my ($errors,$outcome,$deloutcome,$new_values,$translation);
  966:     if ($totalprocessed) {
  967:         ($outcome,$deloutcome,$new_values,$translation) =
  968:         &Apache::lonnet::modify_access_controls($file_name,$changes,$udom,
  969:                                                 $uname);
  970:     }
  971:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
  972:                                                                        $uname);
  973:     my %access_controls = 
  974: 	&Apache::lonnet::get_access_controls($current_permissions,
  975: 					     $group,$file_name);
  976:     if ($totalprocessed) {
  977:         if ($outcome eq 'ok') {
  978:             my $updated_controls = $access_controls{$file_name};
  979:             my ($showstart,$showend);
  980:             $r->print(&Apache::loncommon::start_data_table());
  981:             $r->print(&Apache::loncommon::start_data_table_header_row());
  982:             $r->print('<th>'.&mt('Type of change').'</th><th>'.
  983:                       &mt('Access control').'</th><th>'.&mt('Dates available').
  984:                       '</th><th>'.&mt('Additional information').'</th>');
  985:             $r->print(&Apache::loncommon::end_data_table_header_row());
  986:             foreach my $chg (sort(keys(%processing))) {
  987:                 if (@{$processing{$chg}} > 0) {
  988:                     if ($chg eq 'delete') {
  989:                         if (!($deloutcome eq 'ok')) {
  990:                             $errors .='<span class="LC_error">'.
  991: 				&mt('A problem occurred deleting access controls: [_1]',$deloutcome).
  992: 				'</span>';
  993:                             next;
  994:                         }
  995:                     }
  996:                     my $numchgs = @{$processing{$chg}};
  997:                     $r->print(&Apache::loncommon::start_data_table_row());
  998:                     $r->print('<td rowspan="'.$numchgs.'">'.&mt($title{$chg}).
  999:                               '.</td>');
 1000:                     my $count = 0;
 1001:                     my %todisplay;
 1002:                     foreach my $key (sort(keys(%{$$changes{$chg}}))) {
 1003:                         my ($num,$scope,$end,$start) = &unpack_acc_key($key);
 1004:                         my $newkey = $key;
 1005:                         if ($chg eq 'activate') {
 1006:                             $newkey =~ s/^(\d+)/$$translation{$1}/;
 1007:                         }
 1008:                         $todisplay{$scope}{$newkey} = $$updated_controls{$newkey};
 1009:                     }
 1010:                     &build_access_summary($r,$count,$chg,%todisplay);  
 1011:                 }
 1012:             }
 1013:             $r->print(&Apache::loncommon::end_data_table());
 1014:         } else {
 1015:             if ((@{$processing{'activate'}} > 0) || (@{$processing{'update'}} > 0)) {
 1016:                 $errors .= '<span class="LC_error">'.
 1017: 		    &mt('A problem occurred saving access control settings: [_1]',$outcome).
 1018: 		    '</span>';
 1019:             }
 1020:         }
 1021:         if ($errors) { 
 1022:             $r->print($errors);
 1023:         }
 1024:     }
 1025:     my $allnew = 0;
 1026:     my $totalnew = 0;
 1027:     my $status = 'new';
 1028:     my ($firstitem,$lastitem);
 1029:     foreach my $newitem ('course','domains','users') {
 1030:         $allnew += $env{'form.new'.$newitem};
 1031:     }
 1032:     if ($allnew > 0) {
 1033:         my $now = time;
 1034:         my $then = $now + (60*60*24*180); # six months approx.
 1035:         &open_form($r,$url);
 1036:         foreach my $newitem ('course','domains','users') {
 1037:             if ($env{'form.new'.$newitem} > 0) {
 1038:                 $r->print('<br />'.&mt('Add new <b>[_1]-based</b> access control for portfolio file: <b>[_2]</b>',$newitem,$env{'form.currentpath'}.$env{'form.selectfile'}).'<br /><br />');
 1039:                 $firstitem = $totalnew;
 1040:                 $lastitem = $totalnew + $env{'form.new'.$newitem};
 1041:                 $totalnew = $lastitem;
 1042:                 my @numbers;   
 1043:                 for (my $i=$firstitem; $i<$lastitem; $i++) {
 1044:                     push (@numbers,$i);
 1045:                 }
 1046:                 &display_access_row($r,$status,$newitem,\@numbers,
 1047:                                     $access_controls{$file_name},$now,$then);
 1048:             }
 1049:         }
 1050:         &close_form($r,$url);
 1051:     } else {
 1052:         my %anchor_fields = (
 1053:             'currentpath' => $env{'form.currentpath'},
 1054:             'access' => $env{'form.selectfile'}
 1055:         );
 1056:         $r->print('<br />'.&make_anchor($url, \%anchor_fields, &mt('Display all access settings for this file')));
 1057:         delete $anchor_fields{'access'};
 1058:         $r->print('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&make_anchor($url,\%anchor_fields,&mt('Return to directory listing')));
 1059:     }
 1060:     return;
 1061: }
 1062: 
 1063: sub build_access_record {
 1064:     my ($num,$scope,$start,$end,$chg) = @_;
 1065:     my $record = {
 1066: 	type => $scope,
 1067: 	time => {
 1068: 	    start => $start,
 1069: 	    end   => $end
 1070: 	    },
 1071: 	    };
 1072: 		
 1073:     if ($scope eq 'guest') {	
 1074:         $record->{'password'} = $env{'form.password'};
 1075:     } elsif ($scope eq 'course') {
 1076:         $record->{'domain'} = $env{'form.crsdom_'.$num};
 1077: 	$record->{'number'} = $env{'form.crsnum_'.$num};
 1078:         my @role_ids;
 1079:         my @delete_role_ids =
 1080:             &Apache::loncommon::get_env_multiple('form.delete_role_'.$num);
 1081: 	my @preserves =
 1082: 	    &Apache::loncommon::get_env_multiple('form.preserve_role_'.$num);
 1083: 	if (@delete_role_ids) {
 1084: 	    foreach my $id (@preserves) {
 1085: 		if (grep {$_ = $id} (@delete_role_ids)) {
 1086: 		    next;
 1087: 		}
 1088: 		push(@role_ids,$id); 
 1089: 	    }
 1090: 	} else {
 1091: 	    push(@role_ids,@preserves);
 1092: 	}
 1093: 
 1094: 	my $next_id = $env{'form.add_role_'.$num};
 1095: 	if ($next_id) {
 1096: 	    push(@role_ids,$next_id);
 1097: 	}
 1098: 
 1099:         foreach my $id (@role_ids) {
 1100:             my (@roles,@accesses,@sections,@groups);
 1101:             if (($id == $next_id) && ($chg eq 'update')) {
 1102:                 @roles    = split(/,/,$env{'form.role_'.$num.'_'.$next_id});
 1103:                 @accesses = split(/,/,$env{'form.access_'.$num.'_'.$next_id});
 1104:                 @sections = split(/,/,$env{'form.section_'.$num.'_'.$next_id});
 1105:                 @groups   = split(/,/,$env{'form.group_'.$num.'_'.$next_id});
 1106:             } else {
 1107:                 @roles = &Apache::loncommon::get_env_multiple('form.role_'.$num.'_'.$id);
 1108:                 @accesses = &Apache::loncommon::get_env_multiple('form.access_'.$num.'_'.$id);
 1109:                 @sections = &Apache::loncommon::get_env_multiple('form.section_'.$num.'_'.$id);
 1110:                 @groups = &Apache::loncommon::get_env_multiple('form.group_'.$num.'_'.$id);
 1111:             }
 1112: 	    $record->{'roles'}{$id}{'role'}    = \@roles;
 1113: 	    $record->{'roles'}{$id}{'access'}  = \@accesses;
 1114: 	    $record->{'roles'}{$id}{'section'} = \@sections;
 1115: 	    $record->{'roles'}{$id}{'group'}   = \@groups;
 1116:         }
 1117:     } elsif ($scope eq 'domains') {
 1118:         my @doms = &Apache::loncommon::get_env_multiple('form.dom_'.$num);
 1119: 	$record->{'dom'} = \@doms;
 1120:     } elsif ($scope eq 'users') {
 1121:         my $userlist = $env{'form.users_'.$num};
 1122:         $userlist =~ s/\s+//sg;
 1123: 	my %userhash = map { ($_,1) } (split(/,/,$userlist));
 1124:         foreach my $user (keys(%userhash)) {
 1125:             my ($uname,$udom) = split(/:/,$user);
 1126: 	    push(@{$record->{'users'}}, {
 1127: 		'uname' => $uname,
 1128: 		'udom'  => $udom
 1129: 		});
 1130: 	}
 1131:     }
 1132:     return $record;
 1133: }
 1134: 
 1135: sub get_dates_from_form {
 1136:     my ($id) = @_;
 1137:     my $startdate;
 1138:     my $enddate;
 1139:     $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$id);
 1140:     $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$id);
 1141:     if ( exists ($env{'form.noend_'.$id}) ) {
 1142:         $enddate = 0;
 1143:     }
 1144:     return ($startdate,$enddate);
 1145: }
 1146: 
 1147: sub sort_users {
 1148:     my ($users) = @_; 
 1149:     my @curr_users = map {
 1150: 	$_->{'uname'}.':'.$_->{'udom'}
 1151:     } (@{$users});
 1152:     my $curr_user_list = join(",\n",sort(@curr_users));
 1153:     return $curr_user_list;
 1154: }
 1155: 
 1156: sub access_setting_table {
 1157:     my ($r,$url,$filename,$access_controls,$action) = @_;
 1158:     my ($public,$publictext);
 1159:     $publictext ='Off';
 1160:     my ($guest,$guesttext);
 1161:     $guesttext = 'Off';
 1162:     my @courses = ();
 1163:     my @domains = ();
 1164:     my @users = ();
 1165:     my $now = time;
 1166:     my $then = $now + (60*60*24*180); # six months approx.
 1167:     my ($num,$scope,$publicnum,$guestnum);
 1168:     my (%acl_count,%end,%start,%conditionals);
 1169:     foreach my $key (sort(keys(%{$access_controls}))) {
 1170:         ($num,$scope,$end{$key},$start{$key}) = &unpack_acc_key($key);
 1171:         if ($scope eq 'public') {
 1172:             $public = $key;
 1173:             $publicnum = $num;
 1174:             $publictext = &acl_status($start{$key},$end{$key},$now);
 1175:         } elsif ($scope eq 'guest') {
 1176:             $guest=$key;
 1177:             $guestnum = $num;  
 1178:             $guesttext = &acl_status($start{$key},$end{$key},$now);
 1179:         } else {
 1180:             $conditionals{$scope}{$key} = $$access_controls{$key};
 1181:             if ($scope eq 'course') {
 1182:                 push(@courses,$key);
 1183:             } elsif ($scope eq 'domains') {
 1184:                 push(@domains,$key);
 1185:             } elsif ($scope eq 'users') {
 1186:                 push(@users,$key);
 1187:             }
 1188:         }
 1189:         $acl_count{$scope} ++;
 1190:     }
 1191:     $r->print('<table border="0"><tr><td valign="top">');
 1192:     if ($action eq 'chgaccess') {
 1193:         &standard_settings($r,$now,$then,$url,$filename,\%acl_count,\%start,
 1194:                            \%end,$public,$publicnum,$publictext,$guest,$guestnum,
 1195:                            $guesttext,$access_controls,%conditionals);
 1196:     } else {
 1197:         &condition_setting($r,$access_controls,$now,$then,\%acl_count,
 1198:                            \@domains,\@users,\@courses);
 1199:     }
 1200:     $r->print('</td></tr></table>');
 1201: }
 1202: 
 1203: sub standard_settings {
 1204:     my ($r,$now,$then,$url,$filename,$acl_count,$start,$end,$public,$publicnum,
 1205:       $publictext,$guest,$guestnum,$guesttext,$access_controls,%conditionals)=@_;
 1206:     $r->print('<h3>'.&mt('Public access: [_1]',$publictext).'</h3>');
 1207:     $r->print(&Apache::loncommon::start_data_table());
 1208:     $r->print(&Apache::loncommon::start_data_table_header_row());
 1209:     $r->print('<th>'.&mt('Action').'</th><th>'.&mt('Dates available').'</th>');
 1210:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1211:     $r->print(&Apache::loncommon::start_data_table_row());
 1212:     if ($public) {
 1213:         $r->print('<td>'.&actionbox('old',$publicnum,'public').'</td><td>'.
 1214:              &dateboxes($publicnum,$start->{$public},$end->{$public}).'</td>');
 1215:     } else {
 1216:         $r->print('<td>'.&actionbox('new','0','public').'</td><td>'.
 1217:                   &dateboxes('0',$now,$then).'</td>');
 1218:     }
 1219:     $r->print(&Apache::loncommon::end_data_table_row());
 1220:     $r->print(&Apache::loncommon::end_data_table());
 1221:     $r->print('</td><td width="40">&nbsp;</td><td valign="top">');
 1222:     $r->print('<h3>'.&mt('Passphrase-protected access: [_1]',$guesttext).'</h3>');
 1223:     $r->print(&Apache::loncommon::start_data_table());
 1224:     $r->print(&Apache::loncommon::start_data_table_header_row());
 1225:     $r->print('<th>'.&mt('Action').'</th><th>'.&mt('Dates available').
 1226:               '</th><th>'. &mt('Passphrase').'</th>');
 1227:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1228:     $r->print(&Apache::loncommon::start_data_table_row());
 1229:     my $passwd;
 1230:     if ($guest) {
 1231:         $passwd = $$access_controls{$guest}{'password'};
 1232:         $r->print('<td>'.&actionbox('old',$guestnum,'guest').'</td><td>'.
 1233:               &dateboxes($guestnum,$start->{$guest},$end->{$guest}).'</td>');
 1234:     } else {
 1235:         $r->print('<td>'.&actionbox('new','1','guest').'</td><td>'.
 1236:                   &dateboxes('1',$now,$then).'</td>');
 1237:     }
 1238:     $r->print('<td><input type="text" size="15" name="password" value="'.
 1239:               $passwd.'" /></td>');
 1240:     $r->print(&Apache::loncommon::end_data_table_row());
 1241:     $r->print(&Apache::loncommon::end_data_table());
 1242:     $r->print('</td></tr><tr><td colspan="3">&nbsp;</td></tr>'.
 1243:               '<tr><td colspan="3">');
 1244:     my $numconditionals = 0;
 1245:     my $conditionstext;
 1246:     my %cond_status;
 1247:     foreach my $scope ('domains','users','course') {
 1248:         $numconditionals += $acl_count->{$scope}; 
 1249:         if ($acl_count->{$scope} > 0) {
 1250:             if ($conditionstext ne 'Active') { 
 1251:                 foreach my $key (keys(%{$conditionals{$scope}})) {
 1252:                     $conditionstext = &acl_status($start->{$key},$end->{$key},$now);
 1253:                     if ($conditionstext eq 'Active') {
 1254:                        last;
 1255:                     }
 1256:                 }
 1257:             }
 1258:         }
 1259:     }
 1260:     if ($conditionstext eq '') {
 1261:         $conditionstext = 'Off';
 1262:     }
 1263:     my %anchor_fields = (
 1264:             'access' => $env{'form.selectfile'},
 1265:             'action' => 'chgconditions',
 1266:             'currentpath' => $env{'form.currentpath'},
 1267:         );
 1268:     $r->print('<h3>'.&mt('Conditional access: [_1]',$conditionstext).'</h3>');
 1269:     if ($numconditionals > 0) {
 1270:         my $count = 1;
 1271:         my $chg = 'none';
 1272:         $r->print(&mt('You have previously set [_1] conditional access controls.',$numconditionals).' '.&make_anchor($url,\%anchor_fields,&mt('Change Conditions')).'<br /><br />');
 1273:         $r->print(&Apache::loncommon::start_data_table());
 1274:         $r->print(&Apache::loncommon::start_data_table_header_row());
 1275:         $r->print('<th>'.&mt('Access control').'</th><th>'.&mt('Dates available').
 1276:                   '</th><th>'.&mt('Additional information').'</th>');
 1277:         $r->print(&Apache::loncommon::end_data_table_header_row());
 1278:         &build_access_summary($r,$count,$chg,%conditionals);
 1279:         $r->print(&Apache::loncommon::end_data_table());
 1280:     } else {
 1281:         $r->print(&make_anchor($url,\%anchor_fields,&mt('Add conditional access')).' '.&mt('based on domain, username, or course affiliation.'));
 1282:     }
 1283: }
 1284: 
 1285: sub condition_setting {
 1286:     my ($r,$access_controls,$now,$then,$acl_count,$domains,$users,$courses) = @_;
 1287:     $r->print('<tr><td valign="top">');
 1288:     &access_element($r,'domains',$acl_count,$domains,$access_controls,$now,$then);
 1289:     $r->print('</td><td>&nbsp;</td><td valign="top">');
 1290:     &access_element($r,'users',$acl_count,$users,$access_controls,$now,$then);
 1291:     $r->print('</td></tr><tr><td colspan="3"></td></tr><tr>');
 1292:     if ($acl_count->{course} > 0) {
 1293:         $r->print('<td colspan="3" valign="top">');
 1294:     } else {
 1295:         $r->print('<td valign="top">');
 1296:     }
 1297:     &access_element($r,'course',$acl_count,$courses,$access_controls,$now,$then);
 1298:     $r->print('</td>');
 1299:     $r->print('</td></tr></table>');
 1300: }
 1301: 
 1302: sub acl_status {
 1303:     my ($start,$end,$now) = @_;
 1304:     if ($start > $now) {
 1305:         return 'Inactive';
 1306:     }
 1307:     if ($end && $end<$now) {
 1308:         return 'Inactive';
 1309:     }
 1310:     return 'Active';
 1311: }
 1312: 
 1313: sub access_element {
 1314:     my ($r,$type,$acl_count,$items,$access_controls,$now,$then) = @_;
 1315:     my $title = $type;
 1316:     $title =~ s/s$//;
 1317:     $title =~ s/^(\w)/uc($1)/e;
 1318:     $r->print('<h3>'.&mt('[_1]-based conditional access: ',$title));
 1319:     if ($$acl_count{$type}) {
 1320:         $r->print($$acl_count{$type}.' ');
 1321:         if ($$acl_count{$type} > 1) {
 1322:             $r->print(&mt('conditions'));
 1323:         } else {
 1324:             $r->print(&mt('condition'));
 1325:         }
 1326:     } else {
 1327:         $r->print(&mt('Off'));
 1328:     }
 1329:     $r->print('</h3>');
 1330:     &display_access_row($r,'old',$type,$items,$access_controls,$now,$then);
 1331:     return;
 1332: }
 1333: 
 1334: sub display_access_row {
 1335:     my ($r,$status,$type,$items,$access_controls,$now,$then) = @_;
 1336:     if (@{$items} > 0) {
 1337:         my @all_doms;
 1338:         my $colspan = 3;
 1339:         my $uctype = $type;
 1340:         $uctype =~ s/^(\w)/uc($1)/e;
 1341:         $r->print(&Apache::loncommon::start_data_table());
 1342:         $r->print(&Apache::loncommon::start_data_table_header_row());
 1343:         $r->print('<th>'.&mt('Action?').'</th><th>'.&mt($uctype).'</th><th>'.
 1344:               &mt('Dates available').'</th>');
 1345:         if ($type eq 'course' && $status eq 'old') {
 1346:             $r->print('<th>'.&mt('Allowed [_1] member affiliations',$type).
 1347:                       '</th>');
 1348:             $colspan ++;
 1349:         } elsif ($type eq 'domains') {
 1350:             @all_doms = sort(&Apache::lonnet::all_domains());
 1351:         }
 1352:         $r->print(&Apache::loncommon::end_data_table_header_row());
 1353:         foreach my $key (@{$items}) {
 1354: 	    $r->print(&Apache::loncommon::start_data_table_row());
 1355:             if ($type eq 'course') {
 1356:                 &course_row($r,$status,$type,$key,$access_controls,$now,$then);
 1357:             } elsif ($type eq 'domains') {
 1358:                 &domains_row($r,$status,$key,\@all_doms,$access_controls,$now,
 1359:                             $then);
 1360:             } elsif ($type eq 'users') {
 1361:                 &users_row($r,$status,$key,$access_controls,$now,$then);
 1362:             }
 1363: 	    $r->print(&Apache::loncommon::end_data_table_row());
 1364:         }
 1365:         if ($status eq 'old') {
 1366: 	    $r->print(&Apache::loncommon::start_data_table_row());
 1367:             $r->print('<td colspan="',$colspan.'">'.&additional_item($type).
 1368:                       '</td>');
 1369: 	    $r->print(&Apache::loncommon::end_data_table_row());
 1370:         }
 1371:         $r->print(&Apache::loncommon::end_data_table());
 1372:     } else {
 1373:         $r->print(&mt('No [_1]-based conditions defined.<br />',$type).
 1374:                   &additional_item($type));
 1375:     }
 1376:     return;
 1377: }
 1378: 
 1379: sub course_js {
 1380:     return qq|
 1381: <script type="text/javascript">
 1382: function setRoleOptions(num,roleid,cdom,cnum,type) {
 1383:     updateIndexNum = getIndexByValue('update',num);
 1384:     var addItem = 'add_role_'+num;
 1385:     var addIndexNum = getIndexByName(addItem);
 1386:     if (document.portform.elements[addItem].checked) {
 1387:         document.portform.elements[updateIndexNum].checked = true;
 1388:         var url = '/adm/portfolio?action=rolepicker&setroles='+num+'_'+roleid+'&cnum='+cnum+'&cdom='+cdom+'&type='+type;
 1389:         var title = 'Roles_Chooser';
 1390:         var options = 'scrollbars=1,resizable=1,menubar=0';
 1391:         options += ',width=700,height=600';
 1392:         rolebrowser = open(url,title,options,'1');
 1393:         rolebrowser.focus();
 1394:     } else {
 1395:         addArray = new Array ('role','access','section','group');
 1396:         for (var j=0;j<addArray.length;j++) {
 1397:             var itemIndex = getIndexByName(addArray[j]+'_'+num+'_'+roleid);
 1398:             document.portform.elements[itemIndex].value = '';
 1399:         }
 1400:     }
 1401: }
 1402: 
 1403: function getIndexByName(item) {
 1404:     for (var i=0;i<document.portform.elements.length;i++) {
 1405:         if (document.portform.elements[i].name == item) {
 1406:             return i;
 1407:         }
 1408:     }
 1409:     return -1;
 1410: }
 1411: 
 1412: function getIndexByValue(name,value) {
 1413:     for (var i=0;i<document.portform.elements.length;i++) {
 1414:         if (document.portform.elements[i].name == name && document.portform.elements[i].value == value) {
 1415:             return i;
 1416:         }
 1417:     }
 1418:     return -1;
 1419: }
 1420: 
 1421: </script>
 1422: |;
 1423: }
 1424: 
 1425: sub course_row {
 1426:     my ($r,$status,$type,$item,$access_controls,$now,$then) = @_;
 1427:     my $content;
 1428:     my $defdom = $env{'user.domain'};
 1429:     if ($status eq 'old') {
 1430:         $content = $$access_controls{$item}; 
 1431:         $defdom =  $content->{'domain'};
 1432:     }
 1433:     my $js = &Apache::loncommon::coursebrowser_javascript($defdom)
 1434: 	.&course_js();
 1435:     my $uctype = $type;
 1436:     $uctype =~ s/^(\w)/uc($1)/e;
 1437:     my ($num,$scope,$end,$start) = &set_identifiers($status,$item,$now,$then,
 1438:                                                     $type);
 1439:     $r->print('<td>'.$js.&actionbox($status,$num,$scope).'</td>');
 1440:     if ($status eq 'old') {
 1441:         my $cid = $content->{'domain'}.'_'.$content->{'number'};
 1442:         my %course_description = &Apache::lonnet::coursedescription($cid);
 1443:         $r->print('<td><input type="hidden" name="crsdom_'.$num.'" value="'.$content->{'domain'}.'" /><input type="hidden" name="crsnum_'.$num.'" value="'.$content->{'number'}.'" />'.$course_description{'description'}.'</td>');
 1444:     } elsif ($status eq 'new') {
 1445:         $r->print('<td>'.&Apache::loncommon::selectcourse_link('portform','crsnum_'.$num,'crsdom_'.$num,'description_'.$num,$num.'_1',undef,$uctype).'&nbsp;&nbsp;<input type="text" name="description_'.$num.'" size="30" /><input type="hidden" name="crsdom_'.$num.'" /><input type="hidden" name="crsnum_'.$num.'" /></td>');
 1446:     }
 1447:     $r->print('<td>'.&dateboxes($num,$start,$end));
 1448:     my $newrole_id = 1;
 1449:     if ($status eq 'old') {
 1450:         $r->print('</td><td>');
 1451:         my $max_id = 0;
 1452:         if (keys(%{$content->{'roles'}}) > 0) {
 1453:             $r->print('<table><tr><th>'.&mt('Action').'</th>'.
 1454:                       '<th>'.&mt('Roles').'</th>'.
 1455:                       '<th>'.&mt('Access').'</th>'.
 1456:                       '<th>'.&mt('Sections').'</th>'.
 1457:                       '<th>'.&mt('Groups').'</th></tr>');
 1458:             foreach my $role_id (sort(keys(%{$content->{'roles'}}))) {
 1459:                 if ($role_id > $max_id) {
 1460:                     $max_id = $role_id;
 1461:                 }
 1462:                 $max_id ++;
 1463:                 my $role_selects = &role_selectors($num,$role_id,$type,$content,'display');
 1464:                 $r->print('<tr><td><span style="white-space: nowrap"><label><input type="checkbox" name="delete_role_'.$num.'" value="'.$role_id.'" />'.&mt('Delete').'</label></span><br /><input type="hidden" name="preserve_role_'.$num.'" value="'.$role_id.'" /></td>'.$role_selects.'</tr>');
 1465:             }
 1466:             $r->print('</table>');
 1467:         }
 1468:         $r->print('<br />'.&mt('Add a roles-based condition').
 1469:                   '&nbsp;<input type="checkbox" name ="add_role_'.
 1470:                   $num.'" onClick="javascript:setRoleOptions('."'$num',
 1471:                   '$max_id','$content->{'domain'}','$content->{'number'}',
 1472:                   '$uctype'".')" value="" />');
 1473:         $newrole_id = $max_id;
 1474:     } else {
 1475:         $r->print('<input type="hidden" name ="add_role_'.$num.'" value="" />');
 1476:     }
 1477:     $r->print(&add_course_role($num,$newrole_id));
 1478:     $r->print('</td>');
 1479:     return;
 1480: }
 1481: 
 1482: sub add_course_role {
 1483:     my ($num,$max_id) = @_;
 1484:     my $output;
 1485:     $output .='<input type="hidden" name="role_'.$num.'_'.$max_id.'" />'.
 1486:               '<input type="hidden" name="access_'.$num.'_'.$max_id.'" />'.
 1487:               '<input type="hidden" name="section_'.$num.'_'.$max_id.'" />'.
 1488:               '<input type="hidden" name="group_'.$num.'_'.$max_id.'" />';
 1489:     return $output;
 1490: }
 1491: 
 1492: sub domains_row {
 1493:     my ($r,$status,$item,$all_doms,$access_controls,$now,$then) = @_;
 1494:     my ($num,$scope,$end,$start) = &set_identifiers($status,$item,$now,$then,
 1495:                                                     'domains');
 1496:     my $dom_select = '<select name="dom_'.$num.'" size="4" multiple="true">'.
 1497:                      ' <option value="">'.&mt('Please select').'</option>';
 1498:     if ($status eq 'old') {
 1499:         my $content =  $$access_controls{$item};
 1500: 	foreach my $dom (@{$all_doms}) {
 1501:             if ((@{$content->{'dom'}} > 0) 
 1502: 		&& (grep(/^\Q$dom\E$/,@{$content->{'dom'}}))) {
 1503:                 $dom_select .= '<option value="'.$dom.'" selected>'.
 1504:                                $dom.'</option>';
 1505:             } else {
 1506:                 $dom_select .= '<option value="'.$dom.'">'.$dom.'</option>';
 1507:             }
 1508:         }
 1509:     } else {
 1510:         foreach my $dom (@{$all_doms}) {
 1511:             $dom_select .= '<option value="'.$dom.'">'.$dom.'</option>';
 1512:         }
 1513:     }
 1514:     $dom_select .= '</select>';
 1515:     $r->print('<td>'.&actionbox($status,$num,$scope).'</td><td>'.$dom_select.
 1516:               '</td><td>'.&dateboxes($num,$start,$end).'</td>');
 1517: }
 1518: 
 1519: sub users_row {
 1520:     my ($r,$status,$item,$access_controls,$now,$then) = @_;
 1521:     my ($num,$scope,$end,$start) = &set_identifiers($status,$item,$now,$then,
 1522:                                                     'users');
 1523:     my $curr_user_list;
 1524:     if ($status eq 'old') {
 1525:         my $content = $$access_controls{$item};
 1526:         $curr_user_list = &sort_users($content->{'users'});
 1527:     }
 1528:     $r->print('<td>'.&actionbox($status,$num,$scope).'</td><td>'.&mt("Format for users' username:domain information:").'<br /><tt>sparty:msu,illini:uiuc  ... etc.</tt><br /><textarea name="users_'.$num.'" cols="30"  rows="5">'.$curr_user_list.'</textarea></td><td>'.&dateboxes($num,$start,$end).'</td>');
 1529: }
 1530: 
 1531: sub additional_item {
 1532:     my ($type) = @_;
 1533:     my $output = &mt('Add new [_1] condition(s)?',$type).'&nbsp;'.&mt('Number to add: ').'<input type="text" name="new'.$type.'" size="3" value="0" />';
 1534:     return $output;
 1535: }
 1536: 
 1537: sub actionbox {
 1538:     my ($status,$num,$scope) = @_;
 1539:     my $output = '<span style="white-space: nowrap"><label>';
 1540:     if ($status eq 'new') {
 1541:         my $checkstate;
 1542:         if ($scope eq 'domains' || $scope eq 'users' || $scope eq 'course') {
 1543:             $checkstate = 'checked="checked"';
 1544:         }
 1545:         $output .= '<input type="checkbox" name="activate" value="'.$num.'" '.
 1546:                    $checkstate.'  />'.
 1547:         &mt('Activate');
 1548:     } else {
 1549:         $output .= '<input type="checkbox" name="delete" value="'.$num.
 1550:                    '" />'.&mt('Delete').'</label></span><br /><span style="white-space: nowrap">'.
 1551:                    '<label><input type="checkbox" name="update" value="'.
 1552:                    $num.'" />'.&mt('Update');
 1553:     }
 1554:     $output .= '</label></span><input type="hidden" name="scope_'.$num.                '" value="'.$scope.'" />';
 1555:     return $output;
 1556: }
 1557:                                                                                    
 1558: sub dateboxes {
 1559:     my ($num,$start,$end) = @_;
 1560:     my $noend;
 1561:     if ($end == 0) {
 1562:         $noend = 'checked="checked"';
 1563:     }
 1564:     my $startdate = &Apache::lonhtmlcommon::date_setter('portform',
 1565:                            'startdate_'.$num,$start,undef,undef,undef,1,undef,
 1566:                             undef,undef,1);
 1567:     my $enddate = &Apache::lonhtmlcommon::date_setter('portform',
 1568:                                'enddate_'.$num,$end,undef,undef,undef,1,undef,
 1569:                                 undef,undef,1). '&nbsp;&nbsp;<span style="white-space: nowrap"><label>'.
 1570:                                 '<input type="checkbox" name="noend_'.
 1571:                                 $num.'" '.$noend.' />'.&mt('No end date').
 1572:                                 '</label></span>';
 1573:                                                                                    
 1574:     my $output = &mt('Start: ').$startdate.'<br />'.&mt('End: ').$enddate;
 1575:     return $output;
 1576: }
 1577: 
 1578: sub unpack_acc_key {
 1579:     my ($acc_key) = @_;
 1580:     my ($num,$scope,$end,$start) = ($acc_key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 1581:     return ($num,$scope,$end,$start);
 1582: }
 1583: 
 1584: sub set_identifiers {
 1585:     my ($status,$item,$now,$then,$scope) = @_;
 1586:     if ($status eq 'old') {
 1587:         return(&unpack_acc_key($item));
 1588:     } else {
 1589:         return($item,$scope,$then,$now);
 1590:     }
 1591: } 
 1592: 
 1593: sub role_selectors {
 1594:     my ($num,$role_id,$type,$content,$caller) = @_;
 1595:     my ($output,$cdom,$cnum,$longid);
 1596:     if ($caller eq 'display') {
 1597:         $longid = '_'.$num.'_'.$role_id;
 1598:         $cdom = $$content{'domain'};
 1599:         $cnum = $$content{'number'};
 1600:     } elsif ($caller eq 'rolepicker') {
 1601:          $cdom = $env{'form.cdom'};
 1602:          $cnum = $env{'form.cnum'};
 1603:     }
 1604:     my $uctype = $type;
 1605:     $uctype =~ s/^(\w)/uc($1)/e;
 1606:     my ($sections,$groups,$allroles,$rolehash,$accesshash) =
 1607:             &Apache::loncommon::get_secgrprole_info($cdom,$cnum,1,$uctype);
 1608:     if (!@{$sections}) {
 1609:         @{$sections} = ('none');
 1610:     } else {
 1611:         unshift(@{$sections},('all','none'));
 1612:     }
 1613:     if (!@{$groups}) {
 1614:         @{$groups} = ('none');
 1615:     } else {
 1616:         unshift(@{$groups},('all','none'));
 1617:     }
 1618:     my @allacesses = sort(keys(%{$accesshash}));
 1619:     my (%sectionhash,%grouphash);
 1620:     foreach my $sec (@{$sections}) {
 1621:         $sectionhash{$sec} = $sec;
 1622:     }
 1623:     foreach my $grp (@{$groups}) {
 1624:         $grouphash{$grp} = $grp;
 1625:     }
 1626:     my %lookup = (
 1627:                    'role' => $rolehash,
 1628:                    'access' => $accesshash,
 1629:                    'section' => \%sectionhash,
 1630:                    'group' => \%grouphash,
 1631:                  );
 1632:     my @allaccesses = sort(keys(%{$accesshash}));
 1633:     my %allitems = (
 1634:                     'role' => $allroles,
 1635:                     'access' => \@allaccesses,
 1636:                     'section' => $sections,
 1637:                     'group' => $groups,
 1638:                    );
 1639:     foreach my $item ('role','access','section','group') {
 1640:         $output .= '<td><select name="'.$item.$longid.'" multiple="true" size="4">'."\n";
 1641:         foreach my $entry (@{$allitems{$item}}) {
 1642:             if ($caller eq 'display') {
 1643:                 if ((@{$$content{'roles'}{$role_id}{$item}} > 0) && 
 1644:                     (grep(/^\Q$entry\E$/,@{$$content{'roles'}{$role_id}{$item}}))) {
 1645:                     $output .= '  <option value="'.$entry.'" selected>'.
 1646:                                   $lookup{$item}{$entry}.'</option>';
 1647:                     next;
 1648:                 }
 1649:             }
 1650:             $output .= '  <option value="'.$entry.'">'.
 1651:                        $lookup{$item}{$entry}.'</option>';
 1652:         }
 1653:         $output .= '</select>';
 1654:     }
 1655:     $output .= '</td>';
 1656:     return $output;
 1657: }
 1658: 
 1659: sub role_options_window {
 1660:     my ($r) = @_;
 1661:     my $type = $env{'form.type'};
 1662:     my $rolenum = $env{'form.setroles'};
 1663:     my ($num,$role_id) = ($rolenum =~ /^([\d_]+)_(\d+)$/);
 1664:     my $role_elements;
 1665:     foreach my $item ('role','access','section','group') {
 1666:         $role_elements .= "'".$item.'_'.$rolenum."',";
 1667:     }
 1668:     $role_elements =~ s/,$//; 
 1669:     my $role_selects = &role_selectors($num,$role_id,$type,undef,
 1670:                                        'rolepicker');
 1671:     $r->print(<<"END_SCRIPT");
 1672: <script type="text/javascript">
 1673: function setRoles() {
 1674:     var role_elements = new Array($role_elements);
 1675:     for (var i=0; i<role_elements.length; i++) {
 1676:         var copylist = '';
 1677:         for (var j=0; j<document.rolepicker.elements[i].length; j++) {
 1678:             if (document.rolepicker.elements[i].options[j].selected) {
 1679:                 copylist = copylist + document.rolepicker.elements[i].options[j].value + ',';
 1680:             }
 1681:         }
 1682:         copylist = copylist.substr(0,copylist.length-1);
 1683:         var openerItem = getIndexByName(role_elements[i]);
 1684:         opener.document.portform.elements[openerItem].value = copylist; 
 1685:     }
 1686:     var roleAdder = getIndexByName('add_role_$num');
 1687:     opener.document.portform.elements[roleAdder].value = '$role_id';
 1688:     self.close();
 1689: }
 1690: 
 1691: function getIndexByName(item) {
 1692:     for (var i=0;i<opener.document.portform.elements.length;i++) {
 1693:         if (opener.document.portform.elements[i].name == item) {
 1694:             return i;
 1695:         }
 1696:     }
 1697:     return -1;
 1698: }
 1699: 
 1700: </script>
 1701: END_SCRIPT
 1702:     $r->print(&mt('Select roles, course status, section(s) and group(s) for users who will be able to access the portfolio file.'));
 1703:     $r->print('<form name="rolepicker" action="/adm/portfolio" method="post"><table><tr><th>'.&mt('Roles').'</th><th>'.&mt('[_1] status',$type).'</th><th>'.&mt('Sections').'</th><th>'.&mt('Groups').'</th></tr><tr>'.$role_selects.'</tr></table><br /><input type="button" name="rolepickbutton" value="Save selections" onclick="setRoles()" />');
 1704:     return;
 1705: }
 1706: 
 1707: sub select_files {
 1708:     my ($r) = @_;
 1709:     if ($env{'form.continue'} eq 'true') {
 1710:         # here we update the selections for the currentpath
 1711:         # eventually, have to handle removing those not checked, but . . . 
 1712:         my @items=&Apache::loncommon::get_env_multiple('form.checkfile');
 1713:         if (scalar(@items)){
 1714:              &Apache::lonnet::save_selected_files($env{'user.name'}, $env{'form.currentpath'}, @items);
 1715:         }
 1716:     } else {
 1717:             #empty the file for a fresh start
 1718:             &Apache::lonnet::clear_selected_files($env{'user.name'});
 1719:     }
 1720:     my @files = &Apache::lonnet::files_not_in_path($env{'user.name'}, $env{'form.currentpath'});
 1721:     my $java_files = join ",", @files;
 1722:     if ($java_files) {
 1723:         $java_files.=',';
 1724:     }
 1725:     my $javascript =(<<ENDSMP);
 1726:         <script type="text/javascript">
 1727:         function finishSelect() {
 1728: ENDSMP
 1729:     $javascript .= 'fileList = "'.$java_files.'";';
 1730:     $javascript .= (<<ENDSMP);
 1731:             for (i=0;i<document.forms.checkselect.length;i++) { 
 1732:                 if (document.forms.checkselect[i].checked){
 1733:                     fileList = fileList + document.forms.checkselect.currentpath.value + document.forms.checkselect[i].value + "," ;
 1734:                 }
 1735:             }
 1736:             opener.document.forms.lonhomework.$env{'form.fieldname'}.value=fileList;
 1737:             self.close();
 1738:         }
 1739:         </script>
 1740: ENDSMP
 1741:     $r->print($javascript);
 1742:     $r->print("<h1>Select portfolio files</h1>
 1743:                 Check as many as you wish in response to the problem.<br />");
 1744:     my @otherfiles=&Apache::lonnet::files_not_in_path($env{'user.name'}, $env{'form.currentpath'});
 1745:     if (@otherfiles) {
 1746: 	$r->print("<strong>Files selected from other directories:</strong><br />");
 1747: 	foreach my $file (@otherfiles) {
 1748: 	    $r->print($file."<br />");
 1749: 	}
 1750:     }
 1751: }
 1752: 
 1753: 
 1754: sub check_for_upload {
 1755:     my ($path,$fname,$group,$element) = @_;
 1756:     my $disk_quota = &get_quota($group);
 1757:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 1758: 
 1759:     my $portfolio_root = &get_portfolio_root();
 1760:     my $port_path = &get_port_path();
 1761:     my ($uname,$udom) = &get_name_dom();
 1762:     # Fixme --- Move the checking for existing file to LOND error return
 1763:     my @dir_list=&get_dir_list($portfolio_root,$path);
 1764:     my $found_file = 0;
 1765:     my $locked_file = 0;
 1766:     foreach my $line (@dir_list) {
 1767:         my ($file_name)=split(/\&/,$line,2);
 1768:         if ($file_name eq $fname){
 1769:             $file_name = $path.$file_name;
 1770:             $file_name = &prepend_group($file_name);
 1771:             $found_file = 1;
 1772:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 1773:                 $locked_file = 1;
 1774:             } 
 1775:         }
 1776:     }
 1777:     my $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$portfolio_root);
 1778: 
 1779:     if (($current_disk_usage + $filesize) > $disk_quota){
 1780:         my $msg = '<span class="LC_error">Unable to upload <strong>'.$fname.' (size = '.$filesize.' kilobytes)</strong>. Disk quota will be exceeded.</span>'.
 1781: 	    '<br />Disk quota is '.$disk_quota.' kilobytes. Your current disk usage is '.$current_disk_usage.' kilobytes.';
 1782: 	return ('will_exceed_quota',$msg);
 1783:     } elsif ($found_file) {
 1784:         if ($locked_file) {
 1785:             my $msg = '<span class="LC_error">'.'Unable to upload <strong>'.$fname.'</strong>, a <strong>locked</strong> file by that name was found in <strong>'.$port_path.$path.'</strong></span>'.
 1786: 		'<br />You will be able to rename or delete existing '.$fname.' after a grade has been assigned.';
 1787: 	    return ('file_locked',$msg);
 1788: 	} else {
 1789:             my $msg = '<span class="LC_error">'.'Unable to upload <strong>'.$fname.'</strong>, a file by that name was found in <strong>'.$port_path.$path.'</strong></span>'.
 1790: 		'<br />To upload, rename or delete existing '.$fname.' in '.$port_path.$path;
 1791: 	    return ('file_exists',$msg);
 1792: 	}
 1793:     }
 1794: }
 1795: 
 1796: sub upload {
 1797:     my ($r,$url,$group)=@_;
 1798:     my $fname=&Apache::lonnet::clean_filename($env{'form.uploaddoc.filename'});
 1799: 
 1800:     my ($state,$msg) = &check_for_upload($env{'form.currentpath'},
 1801: 					 $fname,$group,'uploaddoc');
 1802: 
 1803:     if ($state eq 'will_exceed_quota'
 1804: 	|| $state eq 'file_locked'
 1805: 	|| $state eq 'file_exists' ) {
 1806: 	$r->print($msg.&done('Back',$url));
 1807: 	return;
 1808:     }
 1809: 
 1810:     my $port_path = &get_port_path();
 1811:     my (%allfiles,%codebase,$mode);
 1812:     if ($env{'form.uploaddoc.filename'} =~ m/(\.htm|\.html|\.shtml)$/i) {
 1813: 	$mode = 'parse';
 1814: 	
 1815:     }
 1816:     my $result=
 1817: 	&Apache::lonnet::userfileupload('uploaddoc','',
 1818: 					$port_path.$env{'form.currentpath'},
 1819: 					$mode,\%allfiles,\%codebase);
 1820:     if ($result !~ m|^/uploaded/|) {
 1821: 	$r->print('<span class="LC_error">'.'An error occurred ('.$result.
 1822: 		  ') while trying to upload '.&display_file().'</span><br />');
 1823: 	$r->print(&done('Back',$url));
 1824:     } else {
 1825: 	if (%allfiles) {
 1826: 	    my $state = <<STATE;
 1827:     <input type="hidden" name="action"      value="upload_embedded" />
 1828:     <input type="hidden" name="currentpath" value="$env{'form.currentpath'}" />
 1829:     <input type="hidden" name="fieldname"   value="$env{'form.fieldname'}" />
 1830:     <input type="hidden" name="mode"        value="$env{'form.mode'}" />
 1831: STATE
 1832:             $r->print("<h2>".&mt("Reference Warning")."</h2>");
 1833:             $r->print("<p>".&mt("Completed upload of the file. This file contained references to other files. You must upload the referenced files or else the uploaded file may not work properly.")."</p>");
 1834:             $r->print("<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>");
 1835: 	    $r->print(&Apache::londocs::ask_for_embedded_content('/adm/portfolio',$state,\%allfiles,\%codebase,
 1836: 				      {'error_on_invalid_names'   => 1,
 1837: 				       'ignore_remote_references' => 1,}));
 1838: 	    $r->print('<p>Or '.&done('Return to directory listing',$url).'</p>');
 1839: 	} else {
 1840: 	    $r->print(&done(undef,$url));
 1841: 	}
 1842:     }
 1843: }
 1844: 
 1845: sub upload_embedded {
 1846:     my ($r,$url,$group)=@_;
 1847:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 1848: 	next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 1849: 	my $orig_uploaded_filename = 
 1850: 	    $env{'form.embedded_item_'.$i.'.filename'};
 1851: 
 1852: 	$env{'form.embedded_orig_'.$i} = 
 1853: 	    &unescape($env{'form.embedded_orig_'.$i});
 1854: 	my ($path,$fname) = 
 1855: 	    ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 1856: 	# no path, whole string is fname
 1857: 	if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 1858: 
 1859: 	$path = $env{'form.currentpath'}.$path;
 1860: 	$fname = &Apache::lonnet::clean_filename($fname);
 1861: 
 1862: 	my ($state,$msg) = &check_for_upload($path,$fname,$group,
 1863: 					     'embedded_item_'.$i);
 1864: 
 1865: 	if ($state eq 'will_exceed_quota'
 1866: 	    || $state eq 'file_locked'
 1867: 	    || $state eq 'file_exists' ) {
 1868: 	    $r->print($msg);
 1869: 	    next;
 1870: 	}
 1871: 
 1872: 	my $port_path = &get_port_path();
 1873: 	my $src_path = $env{'form.embedded_orig_'.$i};
 1874: 	$env{'form.embedded_item_'.$i.'.filename'}=$fname;
 1875: 	
 1876: 	my $result=
 1877: 	    &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 1878: 					    $port_path.$path);
 1879: 	if ($result !~ m|^/uploaded/|) {
 1880: 	    $r->print('<span class="LC_error">'.'An error occurred ('.$result.
 1881: 		      ') while trying to upload '.$orig_uploaded_filename.' for embedded element '.$env{'form.embedded_orig_'.$i}.'</span><br />');
 1882: 	    next;
 1883: 	} else {
 1884: 	    $r->print("<p> Uploaded ".
 1885: 		      &display_file($port_path.$path,$fname).'</p>');
 1886: 	}
 1887:     }
 1888:     $r->print(&done(undef,$url));
 1889: }
 1890: 
 1891: sub lock_info {
 1892:     my ($r,$url,$group) = @_;
 1893:     my ($uname,$udom) = &get_name_dom();
 1894:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
 1895:                                                                        $uname);
 1896:     my $file_name = $env{'form.lockinfo'};
 1897:     $file_name = &prepend_group($file_name);
 1898:     if (defined($file_name) && defined($$current_permissions{$file_name})) {
 1899:         foreach my $array_item (@{$$current_permissions{$file_name}}) {
 1900:             next if (ref($array_item) ne 'ARRAY');
 1901: 
 1902: 	    my $filetext;
 1903: 	    if (defined($group)) {
 1904: 		$filetext = '<strong>'.$env{'form.lockinfo'}.
 1905: 		    '</strong> (group: '.$group.')'; 
 1906: 	    } else {
 1907: 		$filetext = '<strong>'.$file_name.'</strong>';
 1908: 	    } 
 1909: 	    
 1910: 	    my $title ='<strong>'.&Apache::lonnet::gettitle($$array_item[0]).
 1911: 		'</strong><br />';
 1912: 	    if ($$array_item[-1] eq 'graded') {
 1913: 		$r->print(&mt('[_1] was submitted in response to problem: [_2]',
 1914:                               $filetext,$title));
 1915: 	    } elsif ($$array_item[-1] eq 'handback') {
 1916: 		$r->print(&mt('[_1] was handed back in response to problem: [_2]',
 1917:                               $filetext,$title));
 1918: 	    } else {
 1919: 		# submission style lock
 1920: 		$r->print(&mt('[_1] was submitted in response to problem: [_2]',
 1921:                               $filetext,$title));
 1922: 	    }
 1923: 	    my %course_description = 
 1924: 		&Apache::lonnet::coursedescription($$array_item[1]);
 1925: 	    if ( $course_description{'description'} ne '') {
 1926: 		$r->print(&mt('In the course: <strong>[_1]</strong><br />',
 1927: 			      $course_description{'description'}));
 1928: 	    }
 1929:         }
 1930:     }
 1931:     $r->print(&done('Back',$url));
 1932:     return 'ok';
 1933: }
 1934: 
 1935: sub createdir {
 1936:     my ($r,$url)=@_;
 1937:     my $newdir=&Apache::lonnet::clean_filename($env{'form.newdir'});
 1938:     if ($newdir eq '') {
 1939:     	$r->print('<span class="LC_error">'.
 1940: 	    	  &mt("Error: no directory name was provided.").
 1941: 		      '</span><br />');
 1942: 	    $r->print(&done(undef,$url));
 1943: 	    return;
 1944:     }
 1945:     my $portfolio_root = &get_portfolio_root(); 
 1946:     my @dir_list=&get_dir_list($portfolio_root);
 1947:     my $found_file = 0;
 1948:     foreach my $line (@dir_list) {
 1949:         my ($filename)=split(/\&/,$line,2);
 1950:         if ($filename eq $newdir){
 1951:             $found_file = 1;
 1952:         }
 1953:     }
 1954:     if ($found_file){
 1955:     	    $r->print('<span class="LC_error">'.'Unable to create a directory named <strong>'.$newdir.
 1956:     	            ' </strong>a file or directory by that name already exists.</span><br />');
 1957:     } else {
 1958:         my ($uname,$udom) = &get_name_dom();
 1959:         my $port_path = &get_port_path();
 1960:         my $result=&Apache::lonnet::mkdiruserfile($uname,$udom,
 1961: 	         $port_path.$env{'form.currentpath'}.$newdir);
 1962:         if ($result ne 'ok') {
 1963:     	    $r->print('<span class="LC_error">'.'An error occurred ('.$result.
 1964: 	    	      ') while trying to create a new directory '.&display_file().'</span><br />');
 1965:         }
 1966:     }
 1967:     if ($newdir ne $env{'form.newdir'}) {
 1968:         $r->print("The new directory name was changed from:<br /><strong>".$env{'form.newdir'}."</strong> to <strong>$newdir </strong>");  
 1969:     }
 1970:     $r->print(&done(undef,$url));
 1971: }
 1972: 
 1973: sub get_portfolio_root {
 1974:     my ($udom,$uname,$group) = @_;
 1975:     if (!(defined($udom)) || !(defined($uname))) {
 1976:         ($uname,$udom) = &get_name_dom();
 1977:     }
 1978:     my $path = '/userfiles/portfolio';
 1979:     if (!defined($group)) { 
 1980:         if (defined($env{'form.group'})) {
 1981:             $group = $env{'form.group'};      
 1982:         }
 1983:     }
 1984:     if (defined($group)) {
 1985:         $path = '/userfiles/groups/'.$group.'/portfolio';
 1986:     } 
 1987:     return (&Apache::loncommon::propath($udom,$uname).$path);
 1988: }
 1989: 
 1990: sub get_group_quota {
 1991:     my ($group) = @_;
 1992:     my $group_quota; 
 1993:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1994:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1995:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum,$group);
 1996:     if (%curr_groups) {
 1997:         my %group_info =  &Apache::longroup::get_group_settings(
 1998:                                                     $curr_groups{$group});
 1999:         $group_quota = $group_info{'quota'}; #expressed in Mb
 2000:         if ($group_quota) {
 2001:             $group_quota = 1000 * $group_quota; #expressed in k
 2002:         } 
 2003:     }
 2004:     return $group_quota;
 2005: } 
 2006: 
 2007: sub get_dir_list {
 2008:     my ($portfolio_root,$path) = @_;
 2009:     $path ||= $env{'form.currentpath'};
 2010:     my ($uname,$udom) = &get_name_dom();
 2011:     return &Apache::lonnet::dirlist($path,$udom,$uname,$portfolio_root);
 2012: }
 2013: 
 2014: sub get_name_dom {
 2015:     my ($uname,$udom);
 2016:     if (defined($env{'form.group'})) {
 2017:         $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2018:         $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 2019:     } else {
 2020:         $udom = $env{'user.domain'};
 2021:         $uname = $env{'user.name'};
 2022:     }
 2023:     return ($uname,$udom);
 2024: }
 2025: 
 2026: sub prepend_group {
 2027:     my ($filename) = @_;
 2028:     if (defined($env{'form.group'})) {
 2029:         $filename = $env{'form.group'}.$filename;
 2030:     }
 2031:     return $filename;
 2032: }
 2033: 
 2034: sub get_namespace {
 2035:     my $namespace = 'portfolio';
 2036:     if (defined($env{'form.group'})) {
 2037:         my ($uname,$udom) = &get_name_dom();
 2038:         $namespace .= '_'.$udom.'_'.$uname.'_'.$env{'form.group'};
 2039:     }
 2040:     return $namespace;
 2041: }
 2042: 
 2043: sub get_port_path {
 2044:     my $port_path;
 2045:     if (defined($env{'form.group'})) {
 2046:        $port_path = "groups/$env{'form.group'}/portfolio";
 2047:     } else {
 2048:        $port_path = 'portfolio';
 2049:     }
 2050:     return $port_path;
 2051: }
 2052: 
 2053: sub missing_priv {
 2054:     my ($r,$url,$priv) = @_;
 2055:     my $longtext = {
 2056:                       upload => 'upload files',
 2057:                       delete => 'delete files',
 2058:                       rename => 'rename files',
 2059:                       setacl => 'set access controls for files',
 2060:                    };
 2061:     my $escpath = &HTML::Entities::encode($env{'form.currentpath'},'&<>"');
 2062:     my $rtnlink = '<a href="'.$url;
 2063:     if ($url =~ /\?/) {
 2064:         $rtnlink .= '&';
 2065:     } else {
 2066:         $rtnlink .= '?';
 2067:     }
 2068:     $rtnlink .= 'currentpath='.$escpath;
 2069:     $r->print(&mt('<h3>Action disallowed</h3>'));
 2070:     $r->print(&mt('You do not have sufficient privileges to [_1] ',
 2071:                   $longtext->{$priv}));
 2072:     if (defined($env{'form.group'})) {
 2073:         $r->print(&mt("in the group's file repository."));
 2074:         $rtnlink .= &group_args()
 2075:     } else {
 2076:         $r->print(&mt('in this portfolio.'));
 2077:     }
 2078:     $rtnlink .= '">'.&mt('Return to directory listing page').'</a>';
 2079:     $r->print('<br />'.$rtnlink);
 2080:     $r->print(&Apache::loncommon::end_page());
 2081:     return;
 2082: }
 2083: 
 2084: sub coursegrp_portfolio_header {
 2085:     my ($cdom,$cnum,$grp_desc)=@_;
 2086:     my $gpterm  = &Apache::loncommon::group_term();
 2087:     my $ucgpterm = $gpterm;
 2088:     $ucgpterm =~ s/^(\w)/uc($1)/e;
 2089:     if ($env{'form.ref'}) {
 2090:         &Apache::lonhtmlcommon::add_breadcrumb
 2091:             ({href=>"/adm/coursegroups",
 2092:               text=>"Groups",
 2093:               title=>"Course Groups"});
 2094:     }
 2095:     &Apache::lonhtmlcommon::add_breadcrumb
 2096:         ({href=>"/adm/$cdom/$cnum/$env{'form.group'}/smppg?ref=$env{'form.ref'}",
 2097:           text=>"$ucgpterm: $grp_desc",
 2098:           title=>"Go to group's home page"},
 2099:          {href=>"/adm/coursegrp_portfolio?".&group_args(),
 2100:           text=>"Group Portfolio",
 2101:           title=>"Display group portfolio"});
 2102:     my $output = &Apache::lonhtmlcommon::breadcrumbs(
 2103:                          &mt('[_1] portfolio files - [_2]',$gpterm,$grp_desc));
 2104:     return $output;
 2105: }
 2106: 
 2107: sub get_quota {
 2108:     my ($group) = @_;
 2109:     my $disk_quota;
 2110:     if (defined($group)) {
 2111:         my $grp_quota = &get_group_quota($group); # quota expressed in k
 2112:         if ($grp_quota ne '') {
 2113:             $disk_quota = $grp_quota;
 2114:         } else {
 2115:             $disk_quota = 0;
 2116:         }
 2117:     } else {
 2118:         $disk_quota = &Apache::loncommon::get_user_quota($env{'user.name'},
 2119:                                     $env{'user.domain'}); #expressed in Mb
 2120:         $disk_quota = 1000 * $disk_quota; # convert from Mb to kb
 2121:     }
 2122:     return $disk_quota;
 2123: }
 2124: 
 2125: sub handler {
 2126:     # this handles file management
 2127:     my $r = shift;
 2128:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2129:          ['selectfile','currentpath','meta','lockinfo','currentfile','action',
 2130: 	  'fieldname','mode','rename','continue','group','access','setnum',
 2131:           'cnum','cdom','type','setroles','showversions','ref']);
 2132:     my ($uname,$udom,$portfolio_root,$url,$caller,$title,$group,$grp_desc);
 2133:     if ($r->uri =~ m|^(/adm/)([^/]+)|) {
 2134:         $url = $1.$2;
 2135:         $caller = $2;
 2136:     }
 2137:     my ($can_modify,$can_delete,$can_upload,$can_setacl);
 2138:     if ($caller eq 'coursegrp_portfolio') {
 2139:     #  Needs to be in a course
 2140:         if (! ($env{'request.course.fn'})) {
 2141:         # Not in a course
 2142:             $env{'user.error.msg'}=
 2143:      "/adm/coursegrp_portfolio:rgf:0:0:Cannot view group portfolio";
 2144:             return HTTP_NOT_ACCEPTABLE;
 2145:         }
 2146:         my $earlyout = 0;
 2147:         my $view_permission = 
 2148:            &Apache::lonnet::allowed('vcg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
 2149:         $env{'form.group'} =~ s/\W//g;
 2150: 	$group = $env{'form.group'};
 2151:         if ($group) {
 2152:             ($uname,$udom) = &get_name_dom();
 2153:             my %curr_groups = &Apache::longroup::coursegroups($udom,$uname,
 2154: 							       $group); 
 2155:             if (%curr_groups) {
 2156:                 my %grp_content = &Apache::longroup::get_group_settings(
 2157:                                                          $curr_groups{$group});
 2158:                 $grp_desc = &unescape($grp_content{'description'});
 2159:                 if (($view_permission) || (&Apache::lonnet::allowed('rgf',
 2160:                                       $env{'request.course.id'}.'/'.$group))) {
 2161:                     $portfolio_root = &get_portfolio_root();
 2162:                 } else {
 2163:                     $r->print('You do not have the privileges required to access the shared files space for this group.');
 2164:                     $earlyout = 1;
 2165:                 }
 2166:             } else {
 2167:                 $r->print('Not a valid group for this course');
 2168:                 $earlyout = 1;
 2169:             }
 2170:             $title = &mt('Group files').' for '.$group; 
 2171:         } else {
 2172:             $r->print('Invalid group');
 2173:             $earlyout = 1;
 2174:         }
 2175:         if ($earlyout) { return OK; }
 2176:         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
 2177:             $can_modify = 1;
 2178:             $can_delete = 1;
 2179:             $can_upload = 1;
 2180:             $can_setacl = 1;
 2181:         } else {
 2182:             if (&Apache::lonnet::allowed('agf',$env{'request.course.id'}.'/'.$group)) {
 2183:                 $can_setacl = 1;
 2184:             }
 2185:             if (&Apache::lonnet::allowed('ugf',$env{'request.course.id'}.'/'.$group)) {
 2186:                 $can_upload = 1;
 2187:             }
 2188:             if (&Apache::lonnet::allowed('mgf',$env{'request.course.id'}.'/'.$group)) {
 2189:                 $can_modify = 1;
 2190:             }
 2191:             if (&Apache::lonnet::allowed('dgf',$env{'request.course.id'}.'/'.$group)) {
 2192:                 $can_delete = 1;
 2193:             }
 2194:         }
 2195:     } else {
 2196:         ($uname,$udom) = &get_name_dom();
 2197:         $portfolio_root = &get_portfolio_root();
 2198:         $title = &mt('Portfolio Manager');
 2199:         $can_modify = 1;
 2200:         $can_delete = 1;
 2201:         $can_upload = 1;
 2202:         $can_setacl = 1;
 2203:     }
 2204: 
 2205:     my $port_path = &get_port_path();
 2206:     &Apache::loncommon::no_cache($r);
 2207:     &Apache::loncommon::content_type($r,'text/html');
 2208:     $r->send_http_header;
 2209:     # Give the LON-CAPA page header
 2210:     if ($env{"form.mode"} eq 'selectfile'){
 2211:         $r->print(&Apache::loncommon::start_page($title,undef,
 2212: 						 {'only_body' => 1}));
 2213:     } elsif ($env{'form.action'} eq 'rolepicker') {
 2214:         $r->print(&Apache::loncommon::start_page('New role-based condition',undef,
 2215:                                                  {'no_nav_bar'  => 1, }));
 2216:     } else {
 2217:         $r->print(&Apache::loncommon::start_page($title));
 2218:     }
 2219:     $r->rflush();
 2220:     my ($blocked,$blocktext) = 
 2221:         &Apache::loncommon::blocking_status('port',$uname,$udom);
 2222:     if ($blocked) {
 2223:          $r->print($blocktext);
 2224:          $r->print(&Apache::loncommon::end_page());
 2225:          return OK;
 2226:     }
 2227: 	if (($env{'form.storeupl'}) & (!$env{'form.uploaddoc.filename'})){
 2228:    	    $r->print('<span class="LC_error">'.
 2229: 		      'No file was selected to upload.'.
 2230: 		      'To upload a file, click <strong>Browse...</strong>'.
 2231: 		      ', select a file, then click <strong>Upload</strong>.'.
 2232: 		      '</span>');
 2233: 	}
 2234:     if ($env{'form.meta'}) {
 2235:         &open_form($r,$url);
 2236: #        $r->print(&edit_meta_data($r, $env{'form.currentpath'}.$env{'form.selectfile'}));
 2237:         $r->print('Edit the meta data<br />');
 2238:         &close_form($r,$url);
 2239:     }
 2240:     if ($env{'form.store'}) {
 2241:     }
 2242: 
 2243:     if ($env{'form.uploaddoc.filename'}) {
 2244:         if ($can_upload) {
 2245: 	    &upload($r,$url,$group);
 2246:         } else {
 2247:             &missing_priv($r,$url,'upload');
 2248:         }
 2249:     } elsif ($env{'form.action'} eq 'upload_embedded') {
 2250: 	if ($can_upload) {
 2251: 	    &upload_embedded($r,$url,$group);
 2252:         } else {
 2253:             &missing_priv($r,$url,'upload');
 2254:         }
 2255:     } elsif ($env{'form.action'} eq 'delete' && $env{'form.confirmed'}) {
 2256:         if ($can_delete) {
 2257: 	    &delete_confirmed($r,$url,$group);
 2258:         } else {
 2259:             &missing_priv($r,$url,'delete');
 2260:         }
 2261:     } elsif ($env{'form.action'} eq 'delete') {
 2262:         if ($can_delete) {
 2263: 	    &delete($r,$url);
 2264:         } else {
 2265:             &missing_priv($r,$url,'delete');
 2266:         }
 2267:     } elsif ($env{'form.action'} eq 'deletedir' && $env{'form.confirmed'}) {
 2268:         if ($can_delete) {
 2269: 	    &delete_dir_confirmed($r,$url);
 2270:         } else {
 2271:             &missing_priv($r,$url,'delete');
 2272:         }
 2273:     } elsif ($env{'form.action'} eq 'deletedir') {
 2274:         if ($can_delete) {
 2275: 	    &delete_dir($r,$url);
 2276:         } else {
 2277:             &missing_priv($r,$url,'delete');
 2278:         }
 2279:     } elsif ($env{'form.action'} eq 'rename' && $env{'form.confirmed'}) {
 2280:         if ($can_modify) {
 2281: 	    &rename_confirmed($r,$url,$group);
 2282:         } else {
 2283:             &missing_priv($r,$url,'rename');
 2284:         }
 2285:     } elsif ($env{'form.rename'}) {
 2286:         $env{'form.selectfile'} = $env{'form.rename'};
 2287:         $env{'form.action'} = 'rename';
 2288:         if ($can_modify) {
 2289: 	    &rename($r,$url);
 2290:         } else {
 2291:             &missing_priv($r,$url,'rename');
 2292:         }
 2293:     } elsif ($env{'form.access'}) {
 2294:         $env{'form.selectfile'} = $env{'form.access'};
 2295:         if (!defined($env{'form.action'})) { 
 2296:             $env{'form.action'} = 'chgaccess';
 2297:         }
 2298:         &display_access($r,$url,$group,$can_setacl,$port_path,$env{'form.action'});
 2299:     } elsif (($env{'form.action'} eq 'chgaccess') || 
 2300:              ($env{'form.action'} eq 'chgconditions')) {
 2301:         if ($can_setacl) {
 2302:             &update_access($r,$url,$group,$port_path);
 2303:         } else {
 2304:             &missing_priv($r,$url,'setacl');
 2305:         }
 2306:     } elsif ($env{'form.action'} eq 'rolepicker') {
 2307:         if ($can_setacl) { 
 2308:             &role_options_window($r);
 2309:         } else {
 2310:             &missing_priv($r,$url,'setacl');
 2311:         }
 2312:     } elsif ($env{'form.createdir'}) {
 2313:         if ($can_upload) {
 2314: 	    &createdir($r,$url);
 2315:         } else {
 2316:             &missing_priv($r,$url,'upload');
 2317:         }
 2318:     } elsif ($env{'form.lockinfo'}) {
 2319:         &lock_info($r,$url,$group);
 2320:     } else {
 2321: 	my $current_path='/';
 2322: 	if ($env{'form.currentpath'}) {
 2323: 	    $current_path = $env{'form.currentpath'};
 2324: 	}
 2325:         if ($caller eq 'coursegrp_portfolio') {
 2326:             &Apache::lonhtmlcommon::clear_breadcrumbs();
 2327:             $r->print(&coursegrp_portfolio_header($udom,$uname,$grp_desc));
 2328:         }
 2329:         my @dir_list=&get_dir_list($portfolio_root);
 2330: 	if ($dir_list[0] eq 'no_such_dir'){
 2331: 	    # two main reasons for this:
 2332:             #    1) never been here, so directory structure not created
 2333: 	    #    2) back-button navigation after deleting a directory
 2334: 	    if ($current_path eq '/'){
 2335: 	        &Apache::lonnet::mkdiruserfile($uname,$udom,
 2336: 					       &get_port_path());
 2337: 	    } else {
 2338:                 # some directory that snuck in get rid of the directory
 2339:                 # from the recent pulldown, just in case
 2340: 		&Apache::lonhtmlcommon::remove_recent('portfolio',
 2341: 						      [$current_path]);
 2342: 		$current_path = '/'; # force it back to the root        
 2343: 	    }
 2344: 	    # now grab the directory list again, for the first time
 2345: 	    @dir_list=&Apache::lonnet::dirlist($current_path,
 2346: 					    $udom,$uname,$portfolio_root);
 2347:         }
 2348: 	# need to know if directory is empty so it can be removed if desired
 2349: 	my $is_empty=(@dir_list == 2);
 2350: 	&display_common($r,$url,$current_path,$is_empty,\@dir_list,
 2351: 			$can_upload);
 2352:         &display_directory($r,$url,$current_path,$is_empty,\@dir_list,$group,
 2353:                            $can_upload,$can_modify,$can_delete,$can_setacl);
 2354: 	$r->print(&Apache::loncommon::end_page());
 2355:     }
 2356:     return OK;
 2357: }
 2358: 
 2359: 1;
 2360: __END__

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