File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.254.2.2.2.1: download - view: text, annotated - select for diffs
Wed Nov 1 02:50:05 2017 UTC (6 years, 6 months ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.254.2.2: preferred, unified
- For 2.11.2 (modified)
  - Include changes in 1.259.

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

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