File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.256: download - view: text, annotated - select for diffs
Thu Jun 18 20:19:06 2015 UTC (9 years ago) by musolffc
Branches: MAIN
CVS tags: HEAD
File size checking for uploaded files

A new javascript file, file_upload.js, handles client side file size checking.
The function, checkUploadSize(), accepts an html file input element and a maximum
file size (in bytes) as input.  If the size of the file to be uploaded exceeds the
size allowed, a message is displayed the the element is cleared.  Server side
checking is still used if it passes this test.

Loading file_upload.js adds event handlers to file input elements with
class="flUpload".
    <input type="file" class="flUpload" />

It also looks for a hidden element with id="free_space" that contains the maximum
upload size.
    <input type="hidden" id="free_space" value="$free_space" />

The free space is usually calculated by subtracting a user's disk usage from their
quota allowance.  In some cases it is a fixed value.

I have implemented this for every upload instance I could find.  These include:
* Message attachments
* Authoring space
* Portfolio
* Course editor
* Essay response problems
* Helpdesk request forms
* RSS feed uploads

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

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