File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.241: download - view: text, annotated - select for diffs
Fri Apr 12 17:21:09 2013 UTC (11 years, 1 month ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Portfolio - Improved navigation, layout, and feedback:

- Standard layout and navigation
    - Use confirm_success and action_box after an action, e.g. upload a file
    - Added explicit action confirmation for each successful action
    - Consistent and improved back link after processing an action
    - Fitting header level (h3 -> h2)

- Styles
    - Filename style for filenames
    - Warning style instead of error style for messages with user related errors, e.g. filename not provided and restrict error style for actual errors, e.g. renaming failed

- Improved order of actions
    First check and display cleaning of filename / directory name due to invalid characters, then show empty name or file exists error and exit

- Internationalization
    - Added missing &mt() call
    - Excluded HTML tags from phrase to be translated
    - Eliminated double translation

[Work in progress; Works fine and as intended for changed parts]

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

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