File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.246: download - view: text, annotated - select for diffs
Tue Jul 2 19:04:37 2013 UTC (11 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Disk quotas for authoring spaces.
  - Default is 500 MB, unless set at domain level, or individual user level.
  - Domain default set via "Blogs, personal web pages, webDAV/quotas, portfolio" in
    "Set domain configuration" by DC.
  - Quota for individual user's authoring space set via:
    "Create users or modify the roles and privileges of users" by DC
  - &display_usage() moved from portfolio.pm to lonhtmlcommon.pm to
    facilitate re-use. In portfolio.pm &display_portfolio_usage() now calls
    lonhtmlcommon::display_usage().

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

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