File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.235: download - view: text, annotated - select for diffs
Fri Jun 8 12:25:59 2012 UTC (11 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Portfolio file selection for submission to a Bridge Task which includes IP
  access control avoids blocking of portfolio access from exam blocks.

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

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