File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.255: download - view: text, annotated - select for diffs
Sun Dec 7 19:45:19 2014 UTC (9 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support for submission of files to externalresponse.
  - New routine: &portfiles_versioning() in lonnet.pm called after grading
    externalresponse to handle versioning of submitted files in portfolio.
  - &get_next_version(), &version_selected_portfile(), &file_name_version_ext()
    moved from grades.pm to lonnet.pm to facilitate re-use.

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

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