File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.233: download - view: text, annotated - select for diffs
Mon Oct 17 12:41:30 2011 UTC (12 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
- Change to way lonnet::dirlist() reports an error condition (i.e., no_host,
  con_lost, no_such_dir, empty etc.) when retrieving directory list information
  with ls3, ls2 or ls.
  - error is passed as second item in a pair of return values.
  - first item in return values is a reference to an array of actual files.

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

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