File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.253: download - view: text, annotated - select for diffs
Wed Jun 18 17:37:48 2014 UTC (9 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_1, version_2_11_0, HEAD
- Bug 6710
  - Wording change. The "Course Info" button is actually the Group Portfolio
    link/icon in Course Editor -> Collaboration.

    1: # The LearningOnline Network
    2: # portfolio browser
    3: #
    4: # $Id: portfolio.pm,v 1.253 2014/06/18 17:37:48 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::grades::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::grades::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::grades::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 logged-in users with accounts in the LON-CAPA network, who satisfy the conditions you set.').'<br />'."\n".
  946:         &mt('The conditions can include affiliation with a particular course or community, or a user account in a specific domain.').'<br />'."\n".
  947:         &mt('Alternatively access can be granted to people with specific LON-CAPA usernames and domains.');
  948: }
  949: 
  950: sub view_access_settings {
  951:     my ($r,$url,$access_controls,$aclcount) = @_;
  952:     my ($showstart,$showend);
  953:     my %todisplay;
  954:     foreach my $key (sort(keys(%{$access_controls}))) {
  955:         my ($num,$scope,$end,$start) = &unpack_acc_key($key);
  956:         $todisplay{$scope}{$key} = $$access_controls{$key};
  957:     }
  958:     if ($aclcount) {
  959:         $r->print('<h4>'.&mt('Current access controls defined for this file:').'</h4>');
  960:         $r->print(&Apache::loncommon::start_data_table());
  961:         $r->print(&Apache::loncommon::start_data_table_header_row());
  962:         $r->print('<th>'.&mt('Access control').'</th><th>'.&mt('Dates available').
  963:                   '</th><th>'.&mt('Additional information').'</th>');
  964:         $r->print(&Apache::loncommon::end_data_table_header_row());
  965:         my $count = 1;
  966:         my $chg = 'none';
  967:         &build_access_summary($r,$count,$chg,%todisplay);
  968:         $r->print(&Apache::loncommon::end_data_table());
  969:     } else {
  970:         $r->print(&mt('No access control settings currently exist for this file.').'<br />');
  971:     }
  972:     my %anchor_fields = (
  973:         'currentpath' => $env{'form.currentpath'}
  974:     );
  975:     $r->print('<br />'.&make_anchor($url, \%anchor_fields, &mt('Return to directory')));
  976:     return;
  977: }
  978: 
  979: sub build_access_summary {
  980:     my ($r,$count,$chg,%todisplay) = @_; 
  981:     my ($showstart,$showend);
  982:     my %scope_desc = (
  983:                       public => 'Public',
  984:                       guest => 'Passphrase-protected',
  985:                       domains => 'Conditional: domain-based',
  986:                       users => 'Conditional: user-based',
  987:                       course => 'Conditional: course/community-based',
  988:                      );
  989:     my @allscopes = ('public','guest','domains','users','course');
  990:     foreach my $scope (@allscopes) {
  991:         if ((!(exists($todisplay{$scope}))) || (ref($todisplay{$scope}) ne 'HASH')) {
  992:             next;
  993:         }
  994:         foreach my $key (sort(keys(%{$todisplay{$scope}}))) {
  995:             if ($count) {
  996:                 $r->print(&Apache::loncommon::start_data_table_row());
  997:             }
  998:             my ($num,$scope,$end,$start) = &unpack_acc_key($key);
  999:             my $content = $todisplay{$scope}{$key};
 1000:             if ($chg eq 'delete') {
 1001:                 $showstart = &mt('Deleted');
 1002:                 $showend = $showstart;
 1003:             } else {
 1004:                 $showstart = &Apache::lonlocal::locallocaltime($start);
 1005:                 if ($end == 0) {
 1006:                     $showend = &mt('No end date');
 1007:                 } else {
 1008:                     $showend = &Apache::lonlocal::locallocaltime($end);
 1009:                 }
 1010:             }
 1011:             $r->print('<td>'.&mt($scope_desc{$scope}));
 1012:             my $crstype;
 1013:             if ($scope eq 'course') {
 1014:                 if ($chg ne 'delete') {
 1015:                     my $cid = $content->{'domain'}.'_'.$content->{'number'};
 1016:                     my %course_description = &Apache::lonnet::coursedescription($cid);
 1017:                     $r->print('<br />('.$course_description{'description'}.')');
 1018:                     $crstype = 'Course';
 1019:                     if ($course_description{'type'} ne '') {
 1020:                         $crstype = $course_description{'type'};
 1021:                     }
 1022:                 }
 1023:             }
 1024:             $r->print('</td><td>'.&mt('Start: ').$showstart.
 1025:                   '<br />'.&mt('End: ').$showend.'</td><td>');
 1026:             if ($chg ne 'delete') {
 1027:                 if ($scope eq 'guest') {
 1028:                     $r->print(&mt('Passphrase').': '.$content->{'password'});
 1029:                 } elsif ($scope eq 'course') {
 1030:                     $r->print('<table width="100%"><tr>');
 1031:                     $r->print('<th>'.&mt('Roles').'</th><th>'.
 1032:                           &mt('Access').'</th><th>'.
 1033:                                           &mt('Sections').'</th>');
 1034:                     $r->print('<th>'.&mt('Groups').'</th>');
 1035:                     $r->print('</tr>');
 1036:                     foreach my $id (sort(keys(%{$content->{'roles'}}))) {
 1037:                         $r->print('<tr>');
 1038:                         foreach my $item ('role','access','section','group') {
 1039:                             $r->print('<td>');
 1040:                             if ($item eq 'role') {
 1041:                                 my $role_output;
 1042:                                 foreach my $role (@{$content->{'roles'}{$id}{$item}}) {
 1043:                                     if ($role eq 'all') {
 1044:                                         $role_output .= $role.',';
 1045:                                     } elsif ($role =~ /^cr/) {
 1046:                                         $role_output .= (split('/',$role))[3].',';
 1047:                                     } else {
 1048:                                         $role_output .= &Apache::lonnet::plaintext($role,$crstype).',';
 1049:                                     }
 1050:                                 }
 1051:                                 $role_output =~ s/,$//;
 1052:                                 $r->print($role_output);
 1053:                             } else {
 1054:                                 $r->print(join(',',@{$content->{'roles'}{$id}{$item}}));
 1055:                             }
 1056:                             $r->print('</td>');
 1057:                         }
 1058: 			$r->print('</tr>');
 1059:                     }
 1060: 		    $r->print('</table>');
 1061:                 } elsif ($scope eq 'domains') {
 1062:                     $r->print(&mt('Domains: ').join(',',@{$content->{'dom'}}));
 1063:                 } elsif ($scope eq 'users') {
 1064:                     my $curr_user_list = &sort_users($content->{'users'});
 1065:                     $r->print(&mt('Users: ').$curr_user_list);
 1066:                 } else {
 1067:                     $r->print('&nbsp;');
 1068:                 }
 1069:             } else {
 1070:                 $r->print('&nbsp;');
 1071:             }
 1072:             $r->print('</td>');
 1073:             $r->print(&Apache::loncommon::end_data_table_row());
 1074:             $count ++;
 1075:         }
 1076:     }
 1077: }
 1078: 
 1079: 
 1080: sub update_access {
 1081:     my ($r,$url,$group,$port_path) = @_;
 1082:     my $totalprocessed = 0;
 1083:     my %processing;
 1084:     my %title  = (
 1085:                          'activate' => 'New control(s) added',
 1086:                          'delete'   => 'Existing control(s) deleted',
 1087:                          'update'   => 'Existing control(s) modified',
 1088:                      );
 1089:     my $changes;
 1090:     foreach my $chg (sort(keys(%title))) {     
 1091:         @{$processing{$chg}} = &Apache::loncommon::get_env_multiple('form.'.$chg);
 1092:         $totalprocessed += @{$processing{$chg}};
 1093:         foreach my $num (@{$processing{$chg}}) {
 1094:             my $scope = $env{'form.scope_'.$num};
 1095:             my ($start,$end) = &get_dates_from_form($num);
 1096:             my $newkey = $num.':'.$scope.'_'.$end.'_'.$start;
 1097:             if ($chg eq 'delete') {
 1098:                 $$changes{$chg}{$newkey} = 1;
 1099:             } else {
 1100:                 $$changes{$chg}{$newkey} = 
 1101:                             &build_access_record($num,$scope,$start,$end,$chg);
 1102:             }
 1103:         }
 1104:     }
 1105:     my $file_name = $env{'form.currentpath'}.$env{'form.selectfile'};
 1106:     $r->print('<h2>'.&mt('Allowing others to retrieve file: [_1]',
 1107:               '<span class="LC_filename">'.$port_path.$file_name.'</span>').'</h2>'."\n");
 1108:     $file_name = &prepend_group($file_name);
 1109:     my ($uname,$udom) = &get_name_dom($group);
 1110:     my ($errors,$outcome,$deloutcome,$new_values,$translation);
 1111:     if ($totalprocessed) {
 1112:         ($outcome,$deloutcome,$new_values,$translation) =
 1113:         &Apache::lonnet::modify_access_controls($file_name,$changes,$udom,
 1114:                                                 $uname);
 1115:     }
 1116:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
 1117:                                                                        $uname);
 1118:     my %access_controls = 
 1119: 	&Apache::lonnet::get_access_controls($current_permissions,
 1120: 					     $group,$file_name);
 1121:     if ($totalprocessed) {
 1122:         if ($outcome eq 'ok') {
 1123:             my $updated_controls = $access_controls{$file_name};
 1124:             my ($showstart,$showend);
 1125:             $r->print(&Apache::loncommon::start_data_table());
 1126:             $r->print(&Apache::loncommon::start_data_table_header_row());
 1127:             $r->print('<th>'.&mt('Type of change').'</th><th>'.
 1128:                       &mt('Access control').'</th><th>'.&mt('Dates available').
 1129:                       '</th><th>'.&mt('Additional information').'</th>');
 1130:             $r->print(&Apache::loncommon::end_data_table_header_row());
 1131:             foreach my $chg (sort(keys(%processing))) {
 1132:                 if (@{$processing{$chg}} > 0) {
 1133:                     if ($chg eq 'delete') {
 1134:                         if (!($deloutcome eq 'ok')) {
 1135:                             $errors .='<span class="LC_error">'.
 1136: 				&mt('A problem occurred deleting access controls: [_1]',$deloutcome).
 1137: 				'</span>';
 1138:                             next;
 1139:                         }
 1140:                     }
 1141:                     my $numchgs = @{$processing{$chg}};
 1142:                     $r->print(&Apache::loncommon::start_data_table_row());
 1143:                     $r->print('<td rowspan="'.$numchgs.'">'.&mt($title{$chg}).
 1144:                               '.</td>');
 1145:                     my $count = 0;
 1146:                     my %todisplay;
 1147:                     foreach my $key (sort(keys(%{$$changes{$chg}}))) {
 1148:                         my ($num,$scope,$end,$start) = &unpack_acc_key($key);
 1149:                         my $newkey = $key;
 1150:                         if ($chg eq 'activate') {
 1151:                             $newkey =~ s/^(\d+)/$$translation{$1}/;
 1152:                         }
 1153:                         $todisplay{$scope}{$newkey} = $$updated_controls{$newkey};
 1154:                     }
 1155:                     &build_access_summary($r,$count,$chg,%todisplay);  
 1156:                 }
 1157:             }
 1158:             $r->print(&Apache::loncommon::end_data_table());
 1159:         } else {
 1160:             if ((@{$processing{'activate'}} > 0) || (@{$processing{'update'}} > 0)) {
 1161:                 $errors .= '<span class="LC_error">'.
 1162: 		    &mt('A problem occurred saving access control settings: [_1]',$outcome).
 1163: 		    '</span>';
 1164:             }
 1165:         }
 1166:         if ($errors) { 
 1167:             $r->print($errors);
 1168:         }
 1169:     }
 1170:     my $allnew = 0;
 1171:     my $totalnew = 0;
 1172:     my $status = 'new';
 1173:     my ($firstitem,$lastitem);
 1174:     my @types = ('course','domains','users');
 1175:     foreach my $newitem (@types) {
 1176:         $allnew += $env{'form.new'.$newitem};
 1177:     }
 1178:     if ($allnew > 0) {
 1179:         my $now = time;
 1180:         my $then = $now + (60*60*24*180); # six months approx.
 1181:         &open_form($r,$url);
 1182:         my %showtypes = (
 1183:            course  => 'course/community',
 1184:            domains => 'domain',
 1185:            users   => 'user',
 1186:         );
 1187:         foreach my $newitem (@types) {
 1188:             next if ($env{'form.new'.$newitem} <= 0);
 1189:             $r->print(
 1190:                 '<p>'
 1191:                .&mt('Add new [_1]'.$showtypes{$newitem}.'-based[_2] access control for portfolio file: [_3]',
 1192:                     '<b>','</b>',
 1193:                     '<span class="LC_filename"><b>'
 1194:                    .$env{'form.currentpath'}.$env{'form.selectfile'}.'</b></span>')
 1195:                .'</p>');
 1196:             $firstitem = $totalnew;
 1197:             $lastitem = $totalnew + $env{'form.new'.$newitem};
 1198:             $totalnew = $lastitem;
 1199:             my @numbers;   
 1200:             for (my $i=$firstitem; $i<$lastitem; $i++) {
 1201:                 push(@numbers,$i);
 1202:             }
 1203:             &display_access_row($r,$status,$newitem,\@numbers,
 1204:                                 $access_controls{$file_name},$now,$then);
 1205:         }
 1206:         &close_form($r,$url);
 1207:     } else {
 1208:         my %anchor_fields = (
 1209:             'currentpath' => $env{'form.currentpath'},
 1210:             'access' => $env{'form.selectfile'}
 1211:         );
 1212:         my @actions;
 1213:         push(@actions, &make_anchor($url, \%anchor_fields, &mt('Display all access settings for this file')));
 1214:         delete $anchor_fields{'access'};
 1215:         push(@actions, &make_anchor($url,\%anchor_fields,&mt('Return to directory')));
 1216:         $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(\@actions));
 1217:     }
 1218:     return;
 1219: }
 1220: 
 1221: sub build_access_record {
 1222:     my ($num,$scope,$start,$end,$chg) = @_;
 1223:     my $record = {
 1224: 	type => $scope,
 1225: 	time => {
 1226: 	    start => $start,
 1227: 	    end   => $end
 1228: 	    },
 1229: 	    };
 1230: 		
 1231:     if ($scope eq 'guest') {	
 1232:         $record->{'password'} = $env{'form.password'};
 1233:     } elsif ($scope eq 'course') {
 1234:         $record->{'domain'} = $env{'form.crsdom_'.$num};
 1235: 	$record->{'number'} = $env{'form.crsnum_'.$num};
 1236:         my @role_ids;
 1237:         my @delete_role_ids =
 1238:             &Apache::loncommon::get_env_multiple('form.delete_role_'.$num);
 1239: 	my @preserves =
 1240: 	    &Apache::loncommon::get_env_multiple('form.preserve_role_'.$num);
 1241: 	if (@delete_role_ids) {
 1242: 	    foreach my $id (@preserves) {
 1243: 		if (grep {$_ = $id} (@delete_role_ids)) {
 1244: 		    next;
 1245: 		}
 1246: 		push(@role_ids,$id); 
 1247: 	    }
 1248: 	} else {
 1249: 	    push(@role_ids,@preserves);
 1250: 	}
 1251: 
 1252: 	my $next_id = $env{'form.add_role_'.$num};
 1253: 	if ($next_id) {
 1254: 	    push(@role_ids,$next_id);
 1255: 	}
 1256: 
 1257:         foreach my $id (@role_ids) {
 1258:             my (@roles,@accesses,@sections,@groups);
 1259:             if (($id == $next_id) && ($chg eq 'update')) {
 1260:                 @roles    = split(/,/,$env{'form.role_'.$num.'_'.$next_id});
 1261:                 @accesses = split(/,/,$env{'form.access_'.$num.'_'.$next_id});
 1262:                 @sections = split(/,/,$env{'form.section_'.$num.'_'.$next_id});
 1263:                 @groups   = split(/,/,$env{'form.group_'.$num.'_'.$next_id});
 1264:             } else {
 1265:                 @roles = &Apache::loncommon::get_env_multiple('form.role_'.$num.'_'.$id);
 1266:                 @accesses = &Apache::loncommon::get_env_multiple('form.access_'.$num.'_'.$id);
 1267:                 @sections = &Apache::loncommon::get_env_multiple('form.section_'.$num.'_'.$id);
 1268:                 @groups = &Apache::loncommon::get_env_multiple('form.group_'.$num.'_'.$id);
 1269:             }
 1270: 	    $record->{'roles'}{$id}{'role'}    = \@roles;
 1271: 	    $record->{'roles'}{$id}{'access'}  = \@accesses;
 1272: 	    $record->{'roles'}{$id}{'section'} = \@sections;
 1273: 	    $record->{'roles'}{$id}{'group'}   = \@groups;
 1274:         }
 1275:     } elsif ($scope eq 'domains') {
 1276:         my @doms = &Apache::loncommon::get_env_multiple('form.dom_'.$num);
 1277: 	$record->{'dom'} = \@doms;
 1278:     } elsif ($scope eq 'users') {
 1279:         my $userlist = $env{'form.users_'.$num};
 1280:         $userlist =~ s/\s+//sg;
 1281: 	my %userhash = map { ($_,1) } (split(/,/,$userlist));
 1282:         foreach my $user (keys(%userhash)) {
 1283:             my ($uname,$udom) = split(/:/,$user);
 1284: 	    push(@{$record->{'users'}}, {
 1285: 		'uname' => $uname,
 1286: 		'udom'  => $udom
 1287: 		});
 1288: 	}
 1289:     }
 1290:     return $record;
 1291: }
 1292: 
 1293: sub get_dates_from_form {
 1294:     my ($id) = @_;
 1295:     my $startdate;
 1296:     my $enddate;
 1297:     $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate_'.$id);
 1298:     $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate_'.$id);
 1299:     if ( exists ($env{'form.noend_'.$id}) ) {
 1300:         $enddate = 0;
 1301:     }
 1302:     return ($startdate,$enddate);
 1303: }
 1304: 
 1305: sub sort_users {
 1306:     my ($users) = @_; 
 1307:     my @curr_users = map {
 1308: 	$_->{'uname'}.':'.$_->{'udom'}
 1309:     } (@{$users});
 1310:     my $curr_user_list = join(",\n",sort(@curr_users));
 1311:     return $curr_user_list;
 1312: }
 1313: 
 1314: sub access_setting_table {
 1315:     my ($r,$url,$filename,$access_controls,$action) = @_;
 1316:     my ($public,$publictext);
 1317:     $publictext ='Off';
 1318:     my ($guest,$guesttext);
 1319:     $guesttext = 'Off';
 1320:     my @courses = ();
 1321:     my @domains = ();
 1322:     my @users = ();
 1323:     my $now = time;
 1324:     my $then = $now + (60*60*24*180); # six months approx.
 1325:     my ($num,$scope,$publicnum,$guestnum);
 1326:     my (%acl_count,%end,%start,%conditionals);
 1327:     foreach my $key (sort(keys(%{$access_controls}))) {
 1328:         ($num,$scope,$end{$key},$start{$key}) = &unpack_acc_key($key);
 1329:         if ($scope eq 'public') {
 1330:             $public = $key;
 1331:             $publicnum = $num;
 1332:             $publictext = &acl_status($start{$key},$end{$key},$now);
 1333:         } elsif ($scope eq 'guest') {
 1334:             $guest=$key;
 1335:             $guestnum = $num;  
 1336:             $guesttext = &acl_status($start{$key},$end{$key},$now);
 1337:         } else {
 1338:             $conditionals{$scope}{$key} = $$access_controls{$key};
 1339:             if ($scope eq 'course') {
 1340:                 push(@courses,$key);
 1341:             } elsif ($scope eq 'domains') {
 1342:                 push(@domains,$key);
 1343:             } elsif ($scope eq 'users') {
 1344:                 push(@users,$key);
 1345:             }
 1346:         }
 1347:         $acl_count{$scope} ++;
 1348:     }
 1349:     $r->print('<table border="0"><tr><td valign="top">');
 1350:     if ($action eq 'chgaccess') {
 1351:         &standard_settings($r,$now,$then,$url,$filename,\%acl_count,\%start,
 1352:                            \%end,$public,$publicnum,$publictext,$guest,$guestnum,
 1353:                            $guesttext,$access_controls,%conditionals);
 1354:     } else {
 1355:         &condition_setting($r,$access_controls,$now,$then,\%acl_count,
 1356:                            \@domains,\@users,\@courses);
 1357:     }
 1358:     $r->print('</td></tr></table>');
 1359: }
 1360: 
 1361: sub standard_settings {
 1362:     my ($r,$now,$then,$url,$filename,$acl_count,$start,$end,$public,$publicnum,
 1363:       $publictext,$guest,$guestnum,$guesttext,$access_controls,%conditionals)=@_;
 1364:     $r->print('<h3>'.&mt('Public access: [_1]',&mt($publictext)).'</h3>');
 1365:     $r->print(&Apache::loncommon::start_data_table());
 1366:     $r->print(&Apache::loncommon::start_data_table_header_row());
 1367:     $r->print('<th>'.&mt('Action').'</th><th>'.&mt('Dates available').'</th>');
 1368:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1369:     $r->print(&Apache::loncommon::start_data_table_row());
 1370:     if ($public) {
 1371:         $r->print('<td>'.&actionbox('old',$publicnum,'public').'</td><td>'.
 1372:              &dateboxes($publicnum,$start->{$public},$end->{$public}).'</td>');
 1373:     } else {
 1374:         $r->print('<td>'.&actionbox('new','0','public').'</td><td>'.
 1375:                   &dateboxes('0',$now,$then).'</td>');
 1376:     }
 1377:     $r->print(&Apache::loncommon::end_data_table_row());
 1378:     $r->print(&Apache::loncommon::end_data_table());
 1379:     $r->print('</td><td width="40">&nbsp;</td><td valign="top">');
 1380:     $r->print('<h3>'.&mt('Passphrase-protected access: [_1]',&mt($guesttext)).'</h3>');
 1381:     $r->print(&Apache::loncommon::start_data_table());
 1382:     $r->print(&Apache::loncommon::start_data_table_header_row());
 1383:     $r->print('<th>'.&mt('Action').'</th><th>'.&mt('Dates available').
 1384:               '</th><th>'. &mt('Passphrase').'</th>');
 1385:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1386:     $r->print(&Apache::loncommon::start_data_table_row());
 1387:     my $passwd;
 1388:     if ($guest) {
 1389:         $passwd = $$access_controls{$guest}{'password'};
 1390:         $r->print('<td>'.&actionbox('old',$guestnum,'guest').'</td><td>'.
 1391:               &dateboxes($guestnum,$start->{$guest},$end->{$guest}).'</td>');
 1392:     } else {
 1393:         $r->print('<td>'.&actionbox('new','1','guest').'</td><td>'.
 1394:                   &dateboxes('1',$now,$then).'</td>');
 1395:     }
 1396:     $r->print('<td><input type="text" size="15" name="password" value="'.
 1397:               $passwd.'" /></td>');
 1398:     $r->print(&Apache::loncommon::end_data_table_row());
 1399:     $r->print(&Apache::loncommon::end_data_table());
 1400:     $r->print('</td></tr><tr><td colspan="3">&nbsp;</td></tr>'.
 1401:               '<tr><td colspan="3">');
 1402:     my $numconditionals = 0;
 1403:     my $conditionstext;
 1404:     my %cond_status;
 1405:     foreach my $scope ('domains','users','course') {
 1406:         $numconditionals += $acl_count->{$scope}; 
 1407:         if ($acl_count->{$scope} > 0) {
 1408:             if ($conditionstext ne 'Active') { 
 1409:                 foreach my $key (keys(%{$conditionals{$scope}})) {
 1410:                     $conditionstext = &acl_status($start->{$key},$end->{$key},$now);
 1411:                     if ($conditionstext eq 'Active') {
 1412:                        last;
 1413:                     }
 1414:                 }
 1415:             }
 1416:         }
 1417:     }
 1418:     if ($conditionstext eq '') {
 1419:         $conditionstext = 'Off';
 1420:     }
 1421:     my %anchor_fields = (
 1422:             'access' => $env{'form.selectfile'},
 1423:             'action' => 'chgconditions',
 1424:             'currentpath' => $env{'form.currentpath'},
 1425:         );
 1426:     $r->print('<h3>'.&mt('Conditional access: [_1]',&mt($conditionstext)).'</h3>');
 1427:     if ($numconditionals > 0) {
 1428:         my $count = 1;
 1429:         my $chg = 'none';
 1430:         $r->print(&mt('You have previously set [_1] conditional access controls.',$numconditionals).' '.&make_anchor($url,\%anchor_fields,&mt('Change Conditions')).'<br /><br />');
 1431:         $r->print(&Apache::loncommon::start_data_table());
 1432:         $r->print(&Apache::loncommon::start_data_table_header_row());
 1433:         $r->print('<th>'.&mt('Access control').'</th><th>'.&mt('Dates available').
 1434:                   '</th><th>'.&mt('Additional information').'</th>');
 1435:         $r->print(&Apache::loncommon::end_data_table_header_row());
 1436:         &build_access_summary($r,$count,$chg,%conditionals);
 1437:         $r->print(&Apache::loncommon::end_data_table());
 1438:     } else {
 1439:         $r->print(&make_anchor($url,\%anchor_fields,&mt('Add conditional access')).' '.&mt('based on domain, username, or course/community affiliation.'));
 1440:     }
 1441: }
 1442: 
 1443: sub condition_setting {
 1444:     my ($r,$access_controls,$now,$then,$acl_count,$domains,$users,$courses) = @_;
 1445:     $r->print('<tr><td valign="top">');
 1446:     &access_element($r,'domains',$acl_count,$domains,$access_controls,$now,$then);
 1447:     $r->print('</td><td>&nbsp;</td><td valign="top">');
 1448:     &access_element($r,'users',$acl_count,$users,$access_controls,$now,$then);
 1449:     $r->print('</td></tr><tr><td colspan="3"></td></tr><tr>');
 1450:     if ($acl_count->{course} > 0) {
 1451:         $r->print('<td colspan="3" valign="top">');
 1452:     } else {
 1453:         $r->print('<td valign="top">');
 1454:     }
 1455:     &access_element($r,'course',$acl_count,$courses,$access_controls,$now,$then);
 1456:     $r->print('</td>');
 1457:     $r->print('</td></tr></table>');
 1458: }
 1459: 
 1460: sub acl_status {
 1461:     my ($start,$end,$now) = @_;
 1462:     if ($start > $now) {
 1463:         return 'Inactive';
 1464:     }
 1465:     if ($end && $end<$now) {
 1466:         return 'Inactive';
 1467:     }
 1468:     return 'Active';
 1469: }
 1470: 
 1471: sub access_element {
 1472:     my ($r,$type,$acl_count,$items,$access_controls,$now,$then) = @_;
 1473:     my %typetext = (
 1474:         domains => 'Domain',
 1475:         users   => 'User',
 1476:         course  => 'Course/Community'
 1477:     );
 1478:     $r->print('<h3>'.&mt($typetext{$type}.'-based conditional access:').' ');
 1479:     if ($$acl_count{$type}) {
 1480:         $r->print(&mt('[quant,_1,condition]',$$acl_count{$type}));
 1481:     } else {
 1482:         $r->print(&mt('Off'));
 1483:     }
 1484:     $r->print('</h3>');
 1485:     &display_access_row($r,'old',$type,$items,$access_controls,$now,$then);
 1486:     return;
 1487: }
 1488: 
 1489: sub display_access_row {
 1490:     my ($r,$status,$type,$items,$access_controls,$now,$then) = @_;
 1491:     my ($showtype, $infotype);
 1492:     if ($type eq 'course') {
 1493:         $showtype = &mt('Courses/Communities');
 1494:         $infotype = 'Course/Community';
 1495:     } elsif ($type eq 'domains') {
 1496:         $showtype = &mt('Domains');
 1497:         $infotype = 'Domain';
 1498:     } elsif ($type eq 'users') {
 1499:         $showtype = &mt('Users');
 1500:         $infotype = 'User';
 1501:     }
 1502:     if (@{$items} > 0) {
 1503:         my @all_doms;
 1504:         my $colspan = 3;
 1505:         $r->print(&Apache::loncommon::start_data_table());
 1506:         $r->print(&Apache::loncommon::start_data_table_header_row());
 1507:         $r->print('<th>'.&mt('Action?').'</th><th>'.$showtype.'</th><th>'.
 1508:               &mt('Dates available').'</th>');
 1509:         if ($type eq 'course' && $status eq 'old') {
 1510:             
 1511:             $r->print('<th>'.&mt('Allowed course/community affiliations').
 1512:                       '</th>');
 1513:             $colspan ++;
 1514:         } elsif ($type eq 'domains') {
 1515:             @all_doms = sort(&Apache::lonnet::all_domains());
 1516:         }
 1517:         $r->print(&Apache::loncommon::end_data_table_header_row());
 1518:         foreach my $key (@{$items}) {
 1519: 	    $r->print(&Apache::loncommon::start_data_table_row());
 1520:             if ($type eq 'course') {
 1521:                 &course_row($r,$status,$type,$key,$access_controls,$now,$then);
 1522:             } elsif ($type eq 'domains') {
 1523:                 &domains_row($r,$status,$key,\@all_doms,$access_controls,$now,
 1524:                             $then);
 1525:             } elsif ($type eq 'users') {
 1526:                 &users_row($r,$status,$key,$access_controls,$now,$then);
 1527:             }
 1528: 	    $r->print(&Apache::loncommon::end_data_table_row());
 1529:         }
 1530:         if ($status eq 'old') {
 1531: 	    $r->print(&Apache::loncommon::start_data_table_row());
 1532:             $r->print('<td colspan="',$colspan.'">'.&additional_item($type).
 1533:                       '</td>');
 1534: 	    $r->print(&Apache::loncommon::end_data_table_row());
 1535:         }
 1536:         $r->print(&Apache::loncommon::end_data_table());
 1537:     } else {
 1538:         $r->print(
 1539:             '<p class="LC_info">'
 1540:            .&mt('No '.$infotype.'-based conditions defined')
 1541:            .'</p>'
 1542:            .&additional_item($type)
 1543:         );
 1544:     }
 1545:     return;
 1546: }
 1547: 
 1548: sub course_js {
 1549:     return qq|
 1550: <script type="text/javascript">
 1551: // <![CDATA[
 1552: function setRoleOptions(num,roleid,cdom,cnum,type) {
 1553:     updateIndexNum = getIndexByValue('update',num);
 1554:     var addItem = 'add_role_'+num;
 1555:     var addIndexNum = getIndexByName(addItem);
 1556:     if (document.portform.elements[addItem].checked) {
 1557:         document.portform.elements[updateIndexNum].checked = true;
 1558:         var url = '/adm/portfolio?action=rolepicker&setroles='+num+'_'+roleid+'&cnum='+cnum+'&cdom='+cdom+'&type='+type;
 1559:         var title = 'Roles_Chooser';
 1560:         var options = 'scrollbars=1,resizable=1,menubar=0';
 1561:         options += ',width=700,height=600';
 1562:         rolebrowser = open(url,title,options,'1');
 1563:         rolebrowser.focus();
 1564:     } else {
 1565:         addArray = new Array ('role','access','section','group');
 1566:         for (var j=0;j<addArray.length;j++) {
 1567:             var itemIndex = getIndexByName(addArray[j]+'_'+num+'_'+roleid);
 1568:             document.portform.elements[itemIndex].value = '';
 1569:         }
 1570:     }
 1571: }
 1572: 
 1573: function getIndexByName(item) {
 1574:     for (var i=0;i<document.portform.elements.length;i++) {
 1575:         if (document.portform.elements[i].name == item) {
 1576:             return i;
 1577:         }
 1578:     }
 1579:     return -1;
 1580: }
 1581: 
 1582: function getIndexByValue(name,value) {
 1583:     for (var i=0;i<document.portform.elements.length;i++) {
 1584:         if (document.portform.elements[i].name == name && document.portform.elements[i].value == value) {
 1585:             return i;
 1586:         }
 1587:     }
 1588:     return -1;
 1589: }
 1590: 
 1591: // ]]>
 1592: </script>
 1593: |;
 1594: }
 1595: 
 1596: sub course_row {
 1597:     my ($r,$status,$type,$item,$access_controls,$now,$then) = @_;
 1598:     my $content;
 1599:     my $defdom = $env{'user.domain'};
 1600:     if ($status eq 'old') {
 1601:         $content = $$access_controls{$item}; 
 1602:         $defdom =  $content->{'domain'};
 1603:     }
 1604:     my $js = &Apache::loncommon::coursebrowser_javascript($defdom)
 1605: 	.&course_js();
 1606:     my $showtype = &mt('Course/Community');
 1607:     my $crstype = 'Course';
 1608:     my ($num,$scope,$end,$start) = &set_identifiers($status,$item,$now,$then,
 1609:                                                     $type);
 1610:     $r->print('<td>'.$js.&actionbox($status,$num,$scope).'</td>');
 1611:     if ($status eq 'old') {
 1612:         my $cid = $content->{'domain'}.'_'.$content->{'number'};
 1613:         my %course_description = &Apache::lonnet::coursedescription($cid);
 1614:         if ($course_description{'type'} ne '') {
 1615:             $crstype = $course_description{'type'};
 1616:         }
 1617:         $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>');
 1618:     } elsif ($status eq 'new') {
 1619:         $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>');
 1620:     }
 1621:     $r->print('<td>'.&dateboxes($num,$start,$end));
 1622:     my $newrole_id = 1;
 1623:     if ($status eq 'old') {
 1624:         $r->print('</td><td>');
 1625:         my $max_id = 0;
 1626:         if (keys(%{$content->{'roles'}}) > 0) {
 1627:             $r->print('<table><tr><th>'.&mt('Action').'</th>'.
 1628:                       '<th>'.&mt('Roles').'</th>'.
 1629:                       '<th>'.&mt('Access').'</th>'.
 1630:                       '<th>'.&mt('Sections').'</th>'.
 1631:                       '<th>'.&mt('Groups').'</th></tr>');
 1632:             foreach my $role_id (sort(keys(%{$content->{'roles'}}))) {
 1633:                 if ($role_id > $max_id) {
 1634:                     $max_id = $role_id;
 1635:                 }
 1636:                 $max_id ++;
 1637:                 my $role_selects = &role_selectors($num,$role_id,$crstype,$content,'display');
 1638:                 $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>');
 1639:             }
 1640:             $r->print('</table>');
 1641:         }
 1642:         $r->print('<br />'.&mt('Add a roles-based condition').
 1643:                   '&nbsp;<input type="checkbox" name="add_role_'.
 1644:                   $num.'" onclick="javascript:setRoleOptions('."'$num',
 1645:                   '$max_id','$content->{'domain'}','$content->{'number'}',
 1646:                   '$showtype'".')" value="" />');
 1647:         $newrole_id = $max_id;
 1648:     } else {
 1649:         $r->print('<input type="hidden" name="add_role_'.$num.'" value="" />');
 1650:     }
 1651:     $r->print(&add_course_role($num,$newrole_id));
 1652:     $r->print('</td>');
 1653:     return;
 1654: }
 1655: 
 1656: sub add_course_role {
 1657:     my ($num,$max_id) = @_;
 1658:     my $output;
 1659:     $output .='<input type="hidden" name="role_'.$num.'_'.$max_id.'" />'.
 1660:               '<input type="hidden" name="access_'.$num.'_'.$max_id.'" />'.
 1661:               '<input type="hidden" name="section_'.$num.'_'.$max_id.'" />'.
 1662:               '<input type="hidden" name="group_'.$num.'_'.$max_id.'" />';
 1663:     return $output;
 1664: }
 1665: 
 1666: sub domains_row {
 1667:     my ($r,$status,$item,$all_doms,$access_controls,$now,$then) = @_;
 1668:     my ($num,$scope,$end,$start) = &set_identifiers($status,$item,$now,$then,
 1669:                                                     'domains');
 1670:     my $dom_select = '<select name="dom_'.$num.'" size="4" multiple="multiple">'.
 1671:                      ' <option value="">'.&mt('Please select').'</option>';
 1672:     if ($status eq 'old') {
 1673:         my $content =  $$access_controls{$item};
 1674: 	foreach my $dom (@{$all_doms}) {
 1675:             if ((@{$content->{'dom'}} > 0) 
 1676: 		&& (grep(/^\Q$dom\E$/,@{$content->{'dom'}}))) {
 1677:                 $dom_select .= '<option value="'.$dom.'" selected="selected">'.
 1678:                                $dom.'</option>';
 1679:             } else {
 1680:                 $dom_select .= '<option value="'.$dom.'">'.$dom.'</option>';
 1681:             }
 1682:         }
 1683:     } else {
 1684:         foreach my $dom (@{$all_doms}) {
 1685:             $dom_select .= '<option value="'.$dom.'">'.$dom.'</option>';
 1686:         }
 1687:     }
 1688:     $dom_select .= '</select>';
 1689:     $r->print('<td>'.&actionbox($status,$num,$scope).'</td><td>'.$dom_select.
 1690:               '</td><td>'.&dateboxes($num,$start,$end).'</td>');
 1691: }
 1692: 
 1693: sub users_row {
 1694:     my ($r,$status,$item,$access_controls,$now,$then) = @_;
 1695:     my ($num,$scope,$end,$start) = &set_identifiers($status,$item,$now,$then,
 1696:                                                     'users');
 1697:     my $curr_user_list;
 1698:     if ($status eq 'old') {
 1699:         my $content = $$access_controls{$item};
 1700:         $curr_user_list = &sort_users($content->{'users'});
 1701:     }
 1702:     $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>');
 1703: }
 1704: 
 1705: sub additional_item {
 1706:     my ($type) = @_;
 1707:     my $showtype;
 1708:     if ($type eq 'course') {
 1709:         $showtype = 'course/community';
 1710:     } elsif ($type eq 'domains') {
 1711:         $showtype = 'domain';
 1712:     } elsif ($type eq 'users') {
 1713:         $showtype = 'user';
 1714:     }
 1715:     return
 1716:         &mt('Add new '.$showtype.'-based condition(s)?')
 1717:        .'&nbsp;'.&mt('Number to add: ')
 1718:        .'<input type="text" name="new'.$type.'" size="3" value="0" />';
 1719: }
 1720: 
 1721: sub actionbox {
 1722:     my ($status,$num,$scope) = @_;
 1723:     my $output = '<span class="LC_nobreak"><label>';
 1724:     if ($status eq 'new') {
 1725:         my $checkstate;
 1726:         if ($scope eq 'domains' || $scope eq 'users' || $scope eq 'course') {
 1727:             $checkstate = 'checked="checked"';
 1728:         }
 1729:         $output .= '<input type="checkbox" name="activate" value="'.$num.'" '.
 1730:                    $checkstate.'  />'.
 1731:         &mt('Activate');
 1732:     } else {
 1733:         $output .= '<input type="checkbox" name="delete" value="'.$num.
 1734:                    '" />'.&mt('Delete').'</label></span><br /><span class="LC_nobreak">'.
 1735:                    '<label><input type="checkbox" name="update" value="'.
 1736:                    $num.'" />'.&mt('Update');
 1737:     }
 1738:     $output .= '</label></span><input type="hidden" name="scope_'.$num.                '" value="'.$scope.'" />';
 1739:     return $output;
 1740: }
 1741:                                                                                    
 1742: sub dateboxes {
 1743:     my ($num,$start,$end) = @_;
 1744:     my $noend;
 1745:     if ($end == 0) {
 1746:         $noend = 'checked="checked"';
 1747:     }
 1748:     my $startdate = &Apache::lonhtmlcommon::date_setter('portform',
 1749:                            'startdate_'.$num,$start,undef,undef,undef,1,undef,
 1750:                             undef,undef,1);
 1751:     my $enddate = &Apache::lonhtmlcommon::date_setter('portform',
 1752:                                'enddate_'.$num,$end,undef,undef,undef,1,undef,
 1753:                                 undef,undef,1). '&nbsp;&nbsp;<span class="LC_nobreak"><label>'.
 1754:                                 '<input type="checkbox" name="noend_'.
 1755:                                 $num.'" '.$noend.' />'.&mt('No end date').
 1756:                                 '</label></span>';
 1757:                                                                                    
 1758:     my $output = &mt('Start: ').$startdate.'<br />'.&mt('End: ').$enddate;
 1759:     return $output;
 1760: }
 1761: 
 1762: sub unpack_acc_key {
 1763:     my ($acc_key) = @_;
 1764:     my ($num,$scope,$end,$start) = ($acc_key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 1765:     return ($num,$scope,$end,$start);
 1766: }
 1767: 
 1768: sub set_identifiers {
 1769:     my ($status,$item,$now,$then,$scope) = @_;
 1770:     if ($status eq 'old') {
 1771:         return(&unpack_acc_key($item));
 1772:     } else {
 1773:         return($item,$scope,$then,$now);
 1774:     }
 1775: } 
 1776: 
 1777: sub role_selectors {
 1778:     my ($num,$role_id,$type,$content,$caller) = @_;
 1779:     my ($output,$cdom,$cnum,$longid);
 1780:     if ($caller eq 'display') {
 1781:         $longid = '_'.$num.'_'.$role_id;
 1782:         $cdom = $$content{'domain'};
 1783:         $cnum = $$content{'number'};
 1784:     } elsif ($caller eq 'rolepicker') {
 1785:          $cdom = $env{'form.cdom'};
 1786:          $cnum = $env{'form.cnum'};
 1787:     }
 1788:     my $crstype = 'Course';
 1789:     if ($cnum =~ /^$match_community$/) {
 1790:         $crstype = 'Community'
 1791:     }
 1792:     my ($sections,$groups,$allroles,$rolehash,$accesshash) =
 1793:             &Apache::loncommon::get_secgrprole_info($cdom,$cnum,1,$crstype);
 1794:     if (!@{$sections}) {
 1795:         @{$sections} = ('none');
 1796:     } else {
 1797:         unshift(@{$sections},('all','none'));
 1798:     }
 1799:     if (!@{$groups}) {
 1800:         @{$groups} = ('none');
 1801:     } else {
 1802:         unshift(@{$groups},('all','none'));
 1803:     }
 1804:     my @allacesses = sort(keys(%{$accesshash}));
 1805:     my (%sectionhash,%grouphash);
 1806:     foreach my $sec (@{$sections}) {
 1807:         $sectionhash{$sec} = $sec;
 1808:     }
 1809:     foreach my $grp (@{$groups}) {
 1810:         $grouphash{$grp} = $grp;
 1811:     }
 1812:     my %lookup = (
 1813:                    'role' => $rolehash,
 1814:                    'access' => $accesshash,
 1815:                    'section' => \%sectionhash,
 1816:                    'group' => \%grouphash,
 1817:                  );
 1818:     my @allaccesses = sort(keys(%{$accesshash}));
 1819:     my %allitems = (
 1820:                     'role' => $allroles,
 1821:                     'access' => \@allaccesses,
 1822:                     'section' => $sections,
 1823:                     'group' => $groups,
 1824:                    );
 1825:     foreach my $item ('role','access','section','group') {
 1826:         $output .= '<td><select name="'.$item.$longid.'" multiple="multiple" size="4">'."\n";
 1827:         foreach my $entry (@{$allitems{$item}}) {
 1828:             if ($caller eq 'display') {
 1829:                 if ((@{$$content{'roles'}{$role_id}{$item}} > 0) && 
 1830:                     (grep(/^\Q$entry\E$/,@{$$content{'roles'}{$role_id}{$item}}))) {
 1831:                     $output .= '  <option value="'.$entry.'" selected="selected">'.
 1832:                                   $lookup{$item}{$entry}.'</option>';
 1833:                     next;
 1834:                 }
 1835:             }
 1836:             $output .= '  <option value="'.$entry.'">'.
 1837:                        $lookup{$item}{$entry}.'</option>';
 1838:         }
 1839:         $output .= '</select>';
 1840:     }
 1841:     $output .= '</td>';
 1842:     return $output;
 1843: }
 1844: 
 1845: sub role_options_window {
 1846:     my ($r) = @_;
 1847:     my $type = $env{'form.type'};
 1848:     my $rolenum = $env{'form.setroles'};
 1849:     my ($num,$role_id) = ($rolenum =~ /^([\d_]+)_(\d+)$/);
 1850:     my $role_elements;
 1851:     foreach my $item ('role','access','section','group') {
 1852:         $role_elements .= "'".$item.'_'.$rolenum."',";
 1853:     }
 1854:     $role_elements =~ s/,$//; 
 1855:     my $role_selects = &role_selectors($num,$role_id,$type,undef,
 1856:                                        'rolepicker');
 1857:     $r->print(<<"END_SCRIPT");
 1858: <script type="text/javascript">
 1859: function setRoles() {
 1860:     var role_elements = new Array($role_elements);
 1861:     for (var i=0; i<role_elements.length; i++) {
 1862:         var copylist = '';
 1863:         for (var j=0; j<document.rolepicker.elements[i].length; j++) {
 1864:             if (document.rolepicker.elements[i].options[j].selected) {
 1865:                 copylist = copylist + document.rolepicker.elements[i].options[j].value + ',';
 1866:             }
 1867:         }
 1868:         copylist = copylist.substr(0,copylist.length-1);
 1869:         var openerItem = getIndexByName(role_elements[i]);
 1870:         opener.document.portform.elements[openerItem].value = copylist; 
 1871:     }
 1872:     var roleAdder = getIndexByName('add_role_$num');
 1873:     opener.document.portform.elements[roleAdder].value = '$role_id';
 1874:     self.close();
 1875: }
 1876: 
 1877: function getIndexByName(item) {
 1878:     for (var i=0;i<opener.document.portform.elements.length;i++) {
 1879:         if (opener.document.portform.elements[i].name == item) {
 1880:             return i;
 1881:         }
 1882:     }
 1883:     return -1;
 1884: }
 1885: 
 1886: </script>
 1887: END_SCRIPT
 1888:     $r->print(
 1889:         '<p>'
 1890:        .&mt('Select roles, '.lc($type).' status, section(s) and group(s) for users'
 1891:            .' who will be able to access the portfolio file.')
 1892:        .'</p>'
 1893:     );
 1894:     $r->print(
 1895:         '<form name="rolepicker" action="/adm/portfolio" method="post">'
 1896:        .'<table><tr>'
 1897:        .'<th>'.&mt('Roles').'</th>'
 1898:        .'<th>'.&mt("$type status").'</th>'
 1899:        .'<th>'.&mt('Sections').'</th>'
 1900:        .'<th>'.&mt('Groups').'</th>'
 1901:        .'</tr><tr>'.$role_selects.'</tr>'
 1902:        .'</table><br />'
 1903:        .'<input type="button" name="rolepickbutton" value="'.&mt('Save').'" onclick="setRoles()" />'
 1904:     );
 1905:     return;
 1906: }
 1907: 
 1908: sub select_files {
 1909:     my ($r,$dir_list) = @_;
 1910:     if ($env{'form.continue'} eq 'true') {
 1911:         # here we update the selections for the currentpath
 1912:         # eventually, have to handle removing those not checked, but . . . 
 1913:         my @items=&Apache::loncommon::get_env_multiple('form.checkfile');
 1914:         if (scalar(@items)){
 1915:             my @ok_items;
 1916:             if (ref($dir_list) eq 'ARRAY') {
 1917:                 foreach my $dir_line (@{$dir_list}) {
 1918:                     my ($filename,undef,undef,undef,undef,undef,undef,undef,$size)=split(/\&/,$dir_line,10);
 1919:                     if (grep(/^\Q$filename\E$/,@items)) {
 1920:                         if ($size) {
 1921:                             push(@ok_items,$filename); 
 1922:                         }
 1923:                     }
 1924:                 }
 1925:             }
 1926:             &Apache::lonnet::save_selected_files($env{'user.name'}, $env{'form.currentpath'}, @ok_items);
 1927:         }
 1928:     } else {
 1929:             #empty the file for a fresh start
 1930:             &Apache::lonnet::clear_selected_files($env{'user.name'});
 1931:     }
 1932:     my @files = &Apache::lonnet::files_not_in_path($env{'user.name'}, $env{'form.currentpath'});
 1933:     my $java_files = join ",", @files;
 1934:     if ($java_files) {
 1935:         $java_files.=',';
 1936:     }
 1937:     my $javascript =(<<ENDSMP);
 1938:         <script type="text/javascript">
 1939:         function finishSelect() {
 1940: ENDSMP
 1941:     $javascript .= 'fileList = "'.$java_files.'";';
 1942:     $javascript .= (<<ENDSMP);
 1943:             for (i=0;i<document.forms.checkselect.length;i++) { 
 1944:                 if (document.forms.checkselect[i].checked){
 1945:                     fileList = fileList + document.forms.checkselect.currentpath.value + document.forms.checkselect[i].value + "," ;
 1946:                 }
 1947:             }
 1948:             var hwfield = opener.document.getElementsByName('$env{'form.fieldname'}');
 1949:             hwfield[0].value = fileList;
 1950:             self.close();
 1951:         }
 1952:         </script>
 1953: ENDSMP
 1954:     $r->print($javascript);
 1955:     $r->print("<h1>".&mt('Select portfolio files')."</h1>");
 1956:     my @otherfiles=&Apache::lonnet::files_not_in_path($env{'user.name'}, $env{'form.currentpath'});
 1957:     if (@otherfiles) {
 1958: 	$r->print(&Apache::loncommon::start_data_table()
 1959:                  .&Apache::loncommon::start_data_table_header_row()
 1960:                  .'<th>'.&mt('Files selected from other directories:')."</th>"
 1961:                  .&Apache::loncommon::end_data_table_header_row()
 1962:         );
 1963: 	foreach my $file (@otherfiles) {
 1964: 	    $r->print(&Apache::loncommon::start_data_table_row()
 1965:                      .'<td>'.$file."</td>"
 1966:                      .&Apache::loncommon::end_data_table_row()
 1967:             );
 1968: 	}
 1969:         $r->print(&Apache::loncommon::end_data_table()
 1970:                  .'<br />'
 1971:         );
 1972:     }
 1973:     $r->print('<div>'
 1974:              .&mt('Check as many files as you wish in response to the problem:')
 1975:              .'</div>'
 1976:     );
 1977: }
 1978: 
 1979: sub upload {
 1980:     my ($r,$url,$group)=@_;
 1981:     my $formname = 'uploaddoc';
 1982:     my $fname = &Apache::lonnet::clean_filename($env{'form.'.$formname.'.filename'});
 1983:     my ($state,$msg);
 1984:     if ($fname eq '') {
 1985:         $r->print(
 1986:             &Apache::loncommon::confirmwrapper(
 1987:                 &Apache::lonhtmlcommon::confirm_success(
 1988:                     &mt('Invalid filename: [_1]; the name of the uploaded file did not contain any letters, '.
 1989:                       'so after eliminating special characters there was nothing left.',
 1990:                       '<span class="LC_filename">'.$env{'form.uploaddoc.filename'}.'</span>'),1)));
 1991: 
 1992:         $r->print(&done(undef,$url));
 1993:         return;
 1994:     }
 1995:     my $disk_quota = &get_quota($group);
 1996:     my $portfolio_root = &get_portfolio_root();
 1997:     my $port_path = &get_port_path();
 1998:     my ($uname,$udom) = &get_name_dom($group);
 1999:     my $getpropath = 1;
 2000:     my $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$portfolio_root,$getpropath);
 2001:     ($state,$msg) = 
 2002:         &Apache::loncommon::check_for_upload($env{'form.currentpath'},$fname,
 2003: 		                             $group,$formname,$portfolio_root,
 2004:                                              $port_path,$disk_quota,
 2005:                                              $current_disk_usage,$uname,$udom);
 2006:     if ($state eq 'will_exceed_quota'
 2007: 	|| $state eq 'file_locked'
 2008:         || $state eq 'zero_bytes') {
 2009: 	$r->print($msg.&done(undef,$url));
 2010: 	return;
 2011:     }
 2012: 
 2013:     my (%allfiles,%codebase,$mode,$mimetype);
 2014:     if ($env{'form.'.$formname.'.filename'} =~ m/(\.htm|\.html|\.shtml)$/i) {
 2015:         if ($env{'form.parserflag'}) {
 2016: 	    $mode = 'parse';
 2017:         }
 2018:     }
 2019:     my $context;
 2020:     if ($state eq 'existingfile') {
 2021:         $context = $state;
 2022:     }
 2023:     my $subdir = $port_path.$env{'form.currentpath'};
 2024:     $subdir =~ s{(/)$}{};
 2025:     my ($result,$timestamp) =
 2026: 	&Apache::lonnet::userfileupload($formname,$context,$subdir,
 2027: 					$mode,\%allfiles,\%codebase,undef,undef,
 2028:                                         undef,undef,undef,undef,\$mimetype);
 2029:     if ($state eq 'existingfile') {
 2030:         my $group_elem;
 2031:         my $rootdir = $r->dir_config('lonDaemons').'/tmp/overwrites';
 2032:         if ($group eq '') {
 2033:             $rootdir .= '/'.$env{'user.domain'}.'/'.$env{'user.name'};
 2034:         } else {
 2035:             $rootdir .= '/'.$env{'course.'.$env{'request.course.id'}.'.domain'}.
 2036:                         '/'.$env{'course.'.$env{'request.course.id'}.'.num'};
 2037:             $group_elem = '<input type="hidden" name="group" value="'.$group.'" />';
 2038:         }
 2039:         if (($result eq $rootdir.'/'.$port_path.$env{'form.currentpath'}.$fname) && ($timestamp =~ /^\d+$/)) {
 2040:             my $showfname = &HTML::Entities::encode($fname,'&<>"');
 2041:             my %lt = &Apache::lonlocal::texthash (
 2042:                                                    over => 'Overwrite existing file?',
 2043:                                                    yes  => 'Yes',
 2044:                                                    no   => 'No',
 2045:                                                    undo => 'This action can not be undone.',
 2046:                                                    conf => 'Are you sure you want to overwrite an existing file?',
 2047:                                                    cont => 'Continue',
 2048:                                                  );
 2049:             my $parserflag;
 2050:             my $hidden = &hidden_elems();
 2051:             if ($mode eq 'parse') {
 2052:                 $parserflag = '<input type="hidden" name="parserflag" value="1" />';
 2053:             }
 2054:             $r->print(<<"END");
 2055: <script type="text/javascript">
 2056: // <![CDATA[
 2057: function confirmOverwrite() {
 2058:     var chosen;
 2059:     if (document.existingfile.overwrite.length) {
 2060:         for (var i=0; i<document.existingfile.overwrite.length; i++) {
 2061:             if (document.existingfile.overwrite[i].checked) {
 2062:                 chosen = document.existingfile.overwrite[i].value;
 2063:             }
 2064:         }
 2065:     }
 2066:     if (chosen == 1) {
 2067:         if (confirm('$lt{'conf'}')) {
 2068:             document.existingfile.action.value = "process_overwrite";
 2069:             return true;
 2070:         } else {
 2071:             document.existingfile.action.value = "cancel_overwrite";
 2072:             if (document.existingfile.overwrite.length) {
 2073:                 for (var i=0; i<document.existingfile.overwrite.length; i++) {
 2074:                     if (document.existingfile.overwrite[i].value == "0") {
 2075:                         document.existingfile.overwrite[i].checked = true;
 2076:                     }
 2077:                 }
 2078:             }
 2079:             return false;
 2080:         }
 2081:     } else {
 2082:         document.existingfile.action.value = "cancel_overwrite";
 2083:         return true;
 2084:     }
 2085: }
 2086: // ]]>
 2087: </script>
 2088: <p>
 2089: $msg
 2090: </p>
 2091: <form method="post" action="$url" name="existingfile" onsubmit="return confirmOverwrite();">
 2092: <p class="LC_nobreak">$lt{'over'}
 2093: <label><input type="radio" name="overwrite" value="1" />
 2094: $lt{'yes'}</label>&nbsp;
 2095: <label><input type="radio" name="overwrite" value="0" checked="checked" />$lt{'no'}</label></p>
 2096: <p>
 2097: <input type="hidden" name="action" value="cancel_overwrite" />
 2098: <input type="hidden" name="filename" value="$showfname" />
 2099: <input type="hidden" name="timestamp" value="$timestamp" />
 2100: $hidden
 2101: $parserflag
 2102: $group_elem
 2103: <input type="submit" name="process" value="$lt{'cont'}" />
 2104: </p>
 2105: </form>
 2106: END
 2107:         } else {
 2108:         $r->print(
 2109:             &Apache::loncommon::confirmwrapper(
 2110:                 &Apache::lonhtmlcommon::confirm_success(
 2111:                     &mt('An error occurred ([_1]) while trying to upload [_2].'
 2112:                         ,$result,&display_file(undef,$fname)),1)));
 2113:             $r->print(&done(undef,$url));
 2114:         }
 2115:     } elsif ($result !~ m|^/uploaded/|) {
 2116:         $r->print(
 2117:             &Apache::loncommon::confirmwrapper(
 2118:                 &Apache::lonhtmlcommon::confirm_success(
 2119:                     &mt('An error occurred ([_1]) while trying to upload [_2].'
 2120:                         ,$result,&display_file(undef,$fname)),1)));
 2121: 	$r->print(&done(undef,$url));
 2122:     } else {
 2123:         if (!&suppress_embed_prompt()) {
 2124:             if ($mimetype eq 'text/html') {
 2125: 	        if (keys(%allfiles) > 0) {
 2126:                     &print_dependency_form($r,$url,\%allfiles,\%codebase,$result);
 2127:                     return;
 2128: 	        } else {
 2129:                     $r->print('<p class="LC_warning">'.&mt('No embedded items identified.').'</p>');
 2130:                 }
 2131:             }
 2132:         }
 2133:         $r->print(
 2134:             &Apache::loncommon::confirmwrapper(
 2135:                 &Apache::lonhtmlcommon::confirm_success(
 2136:                     &mt('File successfully uploaded'))));
 2137: 	$r->print(&done(undef,$url));
 2138:     }
 2139:     return;
 2140: }
 2141: 
 2142: sub hidden_elems {
 2143:     my $contelem;
 2144:     if ($env{'form.mode'} eq 'selectfile') {
 2145:         $contelem = '<input type="hidden" name="continue" value="true" />';
 2146:     }
 2147:     return <<END;
 2148: <input type="hidden" name="currentpath" value="$env{'form.currentpath'}" />
 2149: <input type="hidden" name="symb" value="$env{'form.symb'}" />
 2150: <input type="hidden" name="fieldname" value="$env{'form.fieldname'}" />
 2151: <input type="hidden" name="mode" value="$env{'form.mode'}" />
 2152: <input type="hidden" name="showversions" value="$env{'form.showversions'}" />
 2153: $contelem
 2154: END
 2155: }
 2156: 
 2157: sub print_dependency_form {
 2158:     my ($r,$url,$allfiles,$codebase,$result) = @_;
 2159:     my $container = &HTML::Entities::encode($result,'<>"&');
 2160:     my $state = &embedded_form_elems($container);
 2161:     my ($embedded,$num,$pathchg) = &Apache::loncommon::ask_for_embedded_content($url,$state,$allfiles,$codebase,
 2162:                                   {'error_on_invalid_names'   => 1,
 2163:                                    'ignore_remote_references' => 1,});
 2164:     if ($embedded) {
 2165:         if ($num || $pathchg) {
 2166:             $r->print('<h3>'.&mt("Reference Warning").'</h3>');
 2167:         } else {
 2168:             $r->print('<h3>'.&mt("Reference Information").'</h3>');
 2169:         }
 2170:         if ($num) {
 2171:             $r->print('<p>'.&mt('Completed upload of the file.').' '.
 2172:                       &mt('This file contained references to other files.').' '.
 2173:                       &mt('You must upload the referenced files or else the uploaded file may not work properly.').
 2174:                       '</p>'.
 2175:                       '<p>'.&mt("Please select the locations from which the referenced files are to be uploaded.").'</p>'.
 2176:                        $embedded.
 2177:                        '<p>'.&mt('or').'</p>'.&done('Return to directory',$url));
 2178:         } else {
 2179:             $r->print('<p>'.&mt("Completed upload of the file. This file contained references to other files.").'</p>'.
 2180:                       $embedded.
 2181:                       '<p>'.&done('Return to directory',$url).'</p>');
 2182:         }
 2183:     } else {
 2184:         $r->print(&done(undef,$url));
 2185:     }
 2186:     return;
 2187: }
 2188: 
 2189: sub overwrite {
 2190:     my ($r,$url,$group)=@_;
 2191:     my $formname = 'existingfile';
 2192:     my $port_path = &get_port_path();
 2193:     my $fname = &Apache::lonnet::clean_filename($env{'form.filename'});
 2194:     my (%allfiles,%codebase,$mode,$mimetype);
 2195:     unless (&suppress_embed_prompt()) {
 2196:         if ($env{'form.parserflag'}) {
 2197:             if ($fname =~ /\.s?html?$/i) {
 2198:                 $mode = 'parse';
 2199:             }
 2200:         }
 2201:     }
 2202:     if ($fname eq '') {
 2203:         $r->print(
 2204:             &Apache::loncommon::confirmwrapper(
 2205:                 &Apache::lonhtmlcommon::confirm_success(
 2206:                     &mt('Invalid filename: [_1]; the name of the uploaded file did not contain any letters, '.
 2207:                       'so after eliminating special characters there was nothing left.',
 2208:                       '<span class="LC_filename">'.$env{'form.filename'}.'</span>'),1)));
 2209:         $r->print(&done(undef,$url));
 2210:         return;
 2211:     }
 2212:     $env{'form.'.$formname.'.filename'} = $fname;
 2213:     my $subdir = $port_path.$env{'form.currentpath'};
 2214:     $subdir =~ s{(/)$}{};
 2215:     my $result=
 2216:         &Apache::lonnet::userfileupload($formname,'overwrite',$subdir,$mode,
 2217:                                         \%allfiles,\%codebase,undef,undef,undef,
 2218:                                         undef,undef,undef,\$mimetype);
 2219:     if ($result !~ m|^/uploaded/|) {
 2220:         $r->print(
 2221:             &Apache::loncommon::confirmwrapper(
 2222:                 &Apache::lonhtmlcommon::confirm_success(
 2223:                     &mt('An error occurred ([_1]) while trying to overwrite [_2].'
 2224:                        ,$result,&display_file(undef,$fname)),1)));
 2225:     } else {
 2226:         if ($mode eq 'parse') {
 2227:             if ($mimetype eq 'text/html') {
 2228:                 if (keys(%allfiles) > 0) {
 2229:                     &print_dependency_form($r,$url,\%allfiles,\%codebase,$result);
 2230:                     return;
 2231:                 } else {
 2232:                     $r->print(
 2233:                         &Apache::loncommon::confirmwrapper(
 2234:                             &Apache::lonhtmlcommon::confirm_success(
 2235:                                 &mt('Overwriting completed.'))
 2236:                            .'<br />'.&mt('No embedded items identified.')));
 2237:                 }
 2238:             }
 2239:         } else {
 2240:             $r->print(
 2241:                 &Apache::loncommon::confirmwrapper(
 2242:                     &Apache::lonhtmlcommon::confirm_success(
 2243:                         &mt('Overwriting completed.'))));
 2244:         }
 2245:     }
 2246: 
 2247:     my $group_elem;
 2248:     if (defined($env{'form.group'})) {
 2249:         $group_elem = '<input type="hidden" name="group" value="'.$env{'form.group'}.'" />';
 2250:         if (defined($env{'form.ref'})) {
 2251:             $group_elem .= '<input type="hidden" name="ref" value="'.$env{'form.ref'}.'" />'."\n";
 2252:         }
 2253:     }
 2254:     my $hidden = &hidden_elems();
 2255:     $r->print(
 2256:         &Apache::lonhtmlcommon::actionbox(
 2257:             ['<a href="javascript:document.overwritedone.submit();">'
 2258:             .&mt('Return to directory')
 2259:             .'</a>'])
 2260:        .'<form name="overwritedone" method="post" action="'.$url.'">'
 2261:        .$hidden
 2262:        .$group_elem
 2263:        .'</form>'
 2264:     );
 2265:     return;
 2266: }
 2267: 
 2268: sub lock_info {
 2269:     my ($r,$url,$group) = @_;
 2270:     my ($uname,$udom) = &get_name_dom($group);
 2271:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($udom,
 2272:                                                                        $uname);
 2273:     my $file_name = $env{'form.lockinfo'};
 2274:     $file_name = &prepend_group($file_name);
 2275:     if (defined($file_name) && defined($$current_permissions{$file_name})) {
 2276:         foreach my $array_item (@{$$current_permissions{$file_name}}) {
 2277:             next if (ref($array_item) ne 'ARRAY');
 2278: 
 2279: 	    my $filetext;
 2280: 	    if (defined($group)) {
 2281: 		$filetext = '<strong>'.$env{'form.lockinfo'}.
 2282: 		    '</strong> (group: '.$group.')'; 
 2283: 	    } else {
 2284: 		$filetext = '<span class="LC_filename">'.$file_name.'</span>';
 2285: 	    } 
 2286: 	    
 2287: 	    my $title ='<strong>'.&Apache::lonnet::gettitle($$array_item[0]).
 2288: 		'</strong><br />';
 2289: 	    if ($$array_item[-1] eq 'graded') {
 2290: 		$r->print(&mt('[_1] was submitted in response to problem: [_2]',
 2291:                               $filetext,$title));
 2292: 	    } elsif ($$array_item[-1] eq 'handback') {
 2293: 		$r->print(&mt('[_1] was handed back in response to problem: [_2]',
 2294:                               $filetext,$title));
 2295: 	    } else {
 2296: 		# submission style lock
 2297: 		$r->print(&mt('[_1] was submitted in response to problem: [_2]',
 2298:                               $filetext,$title));
 2299: 	    }
 2300: 	    my %course_description = 
 2301: 		&Apache::lonnet::coursedescription($$array_item[1]);
 2302: 	    if ( $course_description{'description'} ne '') {
 2303: 		$r->print(&mt('In the course:').' <strong>'.$course_description{'description'}.'</strong><br />');
 2304: 	    }
 2305:         }
 2306:     }
 2307:     $r->print(&done(undef,$url));
 2308:     return 'ok';
 2309: }
 2310: 
 2311: sub createdir {
 2312:     my ($r,$url,$group)=@_;
 2313:     my $newdir=&Apache::lonnet::clean_filename($env{'form.newdir'});
 2314:     # Display warning in case of directory name cleaning has changed the directory name
 2315:     if ($newdir ne $env{'form.newdir'}) {
 2316:         $r->print(
 2317:             '<p><span class="LC_warning">'
 2318:            .&mt('Invalid characters')
 2319:            .'</span><br />'
 2320:            .&mt('The new directory name was changed from [_1] to [_2].'
 2321:                       ,'<span class="LC_filename">'.$env{'form.newdir'}.'</span>'
 2322:                       ,'<span class="LC_filename">'.$newdir.'</span>')
 2323:            .'</p>'
 2324:         );
 2325:     }
 2326: 
 2327:     # Directory name empty?
 2328:     if ($newdir eq '') {
 2329:         $r->print(
 2330:             &Apache::loncommon::confirmwrapper(
 2331:                 &Apache::lonhtmlcommon::confirm_success(
 2332:                     &mt('Error: no directory name was provided.'),1)));
 2333:             $r->print(&done(undef,$url));
 2334:             return;
 2335:     }
 2336: 
 2337:     my $portfolio_root = &get_portfolio_root(); 
 2338:     my ($dirlistref,$listerror) = &get_dir_list($portfolio_root,undef,$group);
 2339:     my $found_file = 0;
 2340:     if (ref($dirlistref) eq 'ARRAY') {
 2341:         foreach my $line (@{$dirlistref}) {
 2342:             my ($filename)=split(/\&/,$line,2);
 2343:             if ($filename eq $newdir){
 2344:                 $found_file = 1;
 2345:             }
 2346:         }
 2347:     }
 2348:     if ($found_file) {
 2349:         $r->print(
 2350:             &Apache::loncommon::confirmwrapper(
 2351:                 &Apache::lonhtmlcommon::confirm_success(
 2352:                     &mt('Unable to create a directory named [_1].'
 2353:                         ,'<span class="LC_filename">'.$newdir.'</span>'),1)
 2354:                .'<br />'.&mt('A file or directory by that name already exists.')));
 2355:     } else {
 2356:         my ($uname,$udom) = &get_name_dom($group);
 2357:         my $port_path = &get_port_path();
 2358:         my $result=&Apache::lonnet::mkdiruserfile($uname,$udom,
 2359: 	         $port_path.$env{'form.currentpath'}.$newdir);
 2360:         if ($result ne 'ok') {
 2361:         $r->print(
 2362:             &Apache::loncommon::confirmwrapper(
 2363:                 &Apache::lonhtmlcommon::confirm_success(
 2364:                     &mt('An error occurred ([_1]) while trying to create a new directory [_2].'
 2365:                         ,$result,&display_file()),1)));
 2366: 
 2367:         } else {
 2368:         $r->print(
 2369:             &Apache::loncommon::confirmwrapper(
 2370:                 &Apache::lonhtmlcommon::confirm_success(
 2371:                     &mt('Directory successfully created'))));
 2372:         }
 2373:     }
 2374:     $r->print(&done(undef,$url));
 2375: }
 2376: 
 2377: sub get_portfolio_root {
 2378:     my ($udom,$uname,$group) = @_;
 2379:     if (!(defined($udom)) || !(defined($uname))) {
 2380:         ($uname,$udom) = &get_name_dom($group);
 2381:     }
 2382:     my $path = '/userfiles/portfolio';
 2383:     if (!defined($group)) { 
 2384:         if (defined($env{'form.group'})) {
 2385:             $group = $env{'form.group'};      
 2386:         }
 2387:     }
 2388:     if (defined($group)) {
 2389:         $path = '/userfiles/groups/'.$group.'/portfolio';
 2390:     } 
 2391:     return $path;
 2392: }
 2393: 
 2394: sub get_group_quota {
 2395:     my ($group) = @_;
 2396:     my $group_quota; 
 2397:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2398:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2399:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum,$group);
 2400:     if (%curr_groups) {
 2401:         my %group_info =  &Apache::longroup::get_group_settings(
 2402:                                                     $curr_groups{$group});
 2403:         $group_quota = $group_info{'quota'}; #expressed in MB
 2404:         if ($group_quota) {
 2405:             $group_quota = 1000 * $group_quota; #expressed in k
 2406:         }
 2407:     }
 2408:     return $group_quota;
 2409: }
 2410: 
 2411: sub get_dir_list {
 2412:     my ($portfolio_root,$path,$group) = @_;
 2413:     $path ||= $env{'form.currentpath'};
 2414:     my ($uname,$udom) = &get_name_dom($group);
 2415:     my $getpropath = 1;
 2416:     return &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
 2417: }
 2418: 
 2419: sub get_name_dom {
 2420:     my ($group) = @_;
 2421:     my ($uname,$udom);
 2422:     if (defined($group)) {
 2423:         $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2424:         $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 2425:     } else {
 2426:         $udom = $env{'user.domain'};
 2427:         $uname = $env{'user.name'};
 2428:     }
 2429:     return ($uname,$udom);
 2430: }
 2431: 
 2432: sub prepend_group {
 2433:     my ($filename) = @_;
 2434:     if (defined($env{'form.group'})) {
 2435:         $filename = $env{'form.group'}.$filename;
 2436:     }
 2437:     return $filename;
 2438: }
 2439: 
 2440: sub get_namespace {
 2441:     my $namespace = 'portfolio';
 2442:     if (defined($env{'form.group'})) {
 2443:         my ($uname,$udom) = &get_name_dom($env{'form.group'});
 2444:         $namespace .= '_'.$udom.'_'.$uname.'_'.$env{'form.group'};
 2445:     }
 2446:     return $namespace;
 2447: }
 2448: 
 2449: sub get_port_path {
 2450:     my $port_path;
 2451:     if (defined($env{'form.group'})) {
 2452:        $port_path = "groups/$env{'form.group'}/portfolio";
 2453:     } else {
 2454:        $port_path = 'portfolio';
 2455:     }
 2456:     return $port_path;
 2457: }
 2458: 
 2459: sub missing_priv {
 2460:     my ($r,$url,$priv) = @_;
 2461:     my %longtext = 
 2462:         &Apache::lonlocal::texthash(
 2463:                       upload => 'upload files',
 2464:                       delete => 'delete files',
 2465:                       rename => 'rename files',
 2466:                       setacl => 'set access controls for files',
 2467:     );
 2468:     my $escpath = &HTML::Entities::encode($env{'form.currentpath'},'&<>"');
 2469:     my $rtnlink = '<a href="'.$url;
 2470:     if ($url =~ /\?/) {
 2471:         $rtnlink .= '&';
 2472:     } else {
 2473:         $rtnlink .= '?';
 2474:     }
 2475:     $rtnlink .= 'currentpath='.$escpath;
 2476:     $r->print('<h3>'.&mt('Action disallowed').'</h3>');
 2477:     $r->print(&mt('You do not have sufficient privileges to [_1]',
 2478:                   $longtext{$priv}));
 2479:     if (defined($env{'form.group'})) {
 2480:         $r->print(' '.&mt("in the group's group portfolio."));
 2481:         $rtnlink .= &group_args()
 2482:     } else {
 2483:         $r->print(' '.&mt('in this portfolio.'));
 2484:     }
 2485:     $rtnlink .= '">'.&mt('Return to directory').'</a>';
 2486:     $r->print('<br />'.$rtnlink);
 2487:     return;
 2488: }
 2489: 
 2490: sub coursegrp_portfolio_header {
 2491:     my ($cdom,$cnum,$grp_desc)=@_;
 2492:     my $gpterm  = &Apache::loncommon::group_term();
 2493:     my $ucgpterm = $gpterm;
 2494:     $ucgpterm =~ s/^(\w)/uc($1)/e;
 2495:     if ($env{'form.ref'}) {
 2496:         &Apache::lonhtmlcommon::add_breadcrumb
 2497:             ({href=>"/adm/coursegroups",
 2498:               text=>"Groups",
 2499:               title=>"Course Groups"});
 2500:     }
 2501:     &Apache::lonhtmlcommon::add_breadcrumb
 2502:         ({href=>"/adm/$cdom/$cnum/$env{'form.group'}/smppg?ref=$env{'form.ref'}",
 2503:           text=>"$ucgpterm: $grp_desc",
 2504:           title=>"Go to group's home page"},
 2505:          {href=>"/adm/coursegrp_portfolio?".&group_args(),
 2506:           text=>"Group Portfolio",
 2507:           title=>"Display group portfolio"});
 2508:     my $output = &Apache::lonhtmlcommon::breadcrumbs(
 2509:                          &mt('[_1] portfolio files - [_2]',$gpterm,$grp_desc));
 2510:     return $output;
 2511: }
 2512: 
 2513: sub get_quota {
 2514:     my ($group) = @_;
 2515:     my $disk_quota;
 2516:     if (defined($group)) {
 2517:         my $grp_quota = &get_group_quota($group); # quota expressed in k
 2518:         if ($grp_quota ne '') {
 2519:             $disk_quota = $grp_quota;
 2520:         } else {
 2521:             $disk_quota = 0;
 2522:         }
 2523:     } else {
 2524:         $disk_quota = &Apache::loncommon::get_user_quota($env{'user.name'},
 2525:                                     $env{'user.domain'}); #expressed in MB
 2526:         $disk_quota = 1000 * $disk_quota; # convert from MB to kB
 2527:     }
 2528:     return $disk_quota;
 2529: }
 2530: 
 2531: sub suppress_embed_prompt {
 2532:     my $suppress_prompt = 0;
 2533:     if (($env{'request.role'} =~ /^st/) && ($env{'request.course.id'} ne '')) {
 2534:         if ($env{'course.'.$env{'request.course.id'}.'.suppress_embed_prompt'} eq 'yes') {
 2535:             $suppress_prompt = 1;
 2536:         }
 2537:     }
 2538:     return $suppress_prompt;
 2539: }
 2540: 
 2541: sub embedded_form_elems {
 2542:     my ($container) = @_;
 2543:     my $state = <<STATE;
 2544:     <input type="hidden" name="currentpath" value="$env{'form.currentpath'}" />
 2545:     <input type="hidden" name="symb" value="$env{'form.symb'}" />
 2546:     <input type="hidden" name="fieldname" value="$env{'form.fieldname'}" />
 2547:     <input type="hidden" name="mode" value="$env{'form.mode'}" />
 2548:     <input type="hidden" name="container" value="$container" />
 2549: STATE
 2550:     if ($env{'form.group'} ne '') {
 2551:         $state .= '<input type="hidden" name="group" value="'.$env{'form.group'}.'" />'."\n";
 2552:     }
 2553:     return $state;
 2554: }
 2555: 
 2556: sub handler {
 2557:     # this handles file management
 2558:     my $r = shift;
 2559:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2560:          ['selectfile','currentpath','meta','lockinfo','currentfile','action',
 2561: 	  'fieldname','mode','rename','continue','group','access','setnum',
 2562:           'cnum','cdom','type','setroles','showversions','ref','symb']);
 2563:     my ($uname,$udom,$portfolio_root,$url,$caller,$title,$group,$grp_desc);
 2564:     if ($r->uri =~ m|^(/adm/)([^/]+)|) {
 2565:         $url = $1.$2;
 2566:         $caller = $2;
 2567:     }
 2568:     my ($can_modify,$can_delete,$can_upload,$can_setacl);
 2569:     if ($caller eq 'coursegrp_portfolio') {
 2570:     #  Needs to be in a course
 2571:         if (! ($env{'request.course.fn'})) {
 2572:         # Not in a course
 2573:             $env{'user.error.msg'}=
 2574:      "/adm/coursegrp_portfolio:rgf:0:0:Cannot view group portfolio";
 2575:             return HTTP_NOT_ACCEPTABLE;
 2576:         }
 2577:         my $earlyout = 0;
 2578:         my $view_permission = 
 2579:            &Apache::lonnet::allowed('vcg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''));
 2580:         $env{'form.group'} =~ s/\W//g;
 2581: 	$group = $env{'form.group'};
 2582:         if ($group ne '') {
 2583:             ($uname,$udom) = &get_name_dom($group);
 2584:             my %curr_groups = &Apache::longroup::coursegroups($udom,$uname,
 2585: 							       $group); 
 2586:             if (%curr_groups) {
 2587:                 my %grp_content = &Apache::longroup::get_group_settings(
 2588:                                                          $curr_groups{$group});
 2589:                 $grp_desc = &unescape($grp_content{'description'});
 2590:                 if (($view_permission) || (&Apache::lonnet::allowed('rgf',
 2591:                                       $env{'request.course.id'}.'/'.$group))) {
 2592:                     $portfolio_root = &get_portfolio_root();
 2593:                 } else {
 2594:                     $r->print(&mt('You do not have the privileges required to access the shared files space for this group.'));
 2595:                     $earlyout = 1;
 2596:                 }
 2597:             } else {
 2598:                 $r->print(&mt('Not a valid group for this course'));
 2599:                 $earlyout = 1;
 2600:             }
 2601:             $title = &mt('Group portfolio for [_1]', $group); 
 2602:         } else {
 2603:             $r->print(&mt('Invalid group'));
 2604:             $earlyout = 1;
 2605:         }
 2606:         if ($earlyout) { return OK; }
 2607:         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
 2608:             $can_modify = 1;
 2609:             $can_delete = 1;
 2610:             $can_upload = 1;
 2611:             $can_setacl = 1;
 2612:         } else {
 2613:             if (&Apache::lonnet::allowed('agf',$env{'request.course.id'}.'/'.$group)) {
 2614:                 $can_setacl = 1;
 2615:             }
 2616:             if (&Apache::lonnet::allowed('ugf',$env{'request.course.id'}.'/'.$group)) {
 2617:                 $can_upload = 1;
 2618:             }
 2619:             if (&Apache::lonnet::allowed('mgf',$env{'request.course.id'}.'/'.$group)) {
 2620:                 $can_modify = 1;
 2621:             }
 2622:             if (&Apache::lonnet::allowed('dgf',$env{'request.course.id'}.'/'.$group)) {
 2623:                 $can_delete = 1;
 2624:             }
 2625:         }
 2626:     } else {
 2627:         ($uname,$udom) = &get_name_dom();
 2628:         $portfolio_root = &get_portfolio_root();
 2629:         $title = 'My Space';
 2630:         $can_modify = 1;
 2631:         $can_delete = 1;
 2632:         $can_upload = 1;
 2633:         $can_setacl = 1;
 2634:     }
 2635: 
 2636:     my $port_path = &get_port_path();
 2637:     &Apache::loncommon::no_cache($r);
 2638:     &Apache::loncommon::content_type($r,'text/html');
 2639:     $r->send_http_header;
 2640:     # Give the LON-CAPA page header
 2641:     my $brcrum = [{href=>"/adm/portfolio",text=>"Portfolio Manager"}];
 2642: 
 2643:     if ($env{"form.mode"} eq 'selectfile'){
 2644:         $r->print(&Apache::loncommon::start_page($title,undef,
 2645: 						 {'only_body' => 1}));
 2646:     } elsif ($env{'form.action'} eq 'rolepicker') {
 2647:         $r->print(&Apache::loncommon::start_page('New role-based condition',undef,
 2648:                                                  {'no_nav_bar'  => 1, }));
 2649:     } elsif ($caller eq 'coursegrp_portfolio') {
 2650:         $r->print(&Apache::loncommon::start_page($title));
 2651:     } else {
 2652:         $r->print(&Apache::loncommon::start_page($title,undef,
 2653:                                                  {'bread_crumbs' => $brcrum}));
 2654:         if (!&Apache::lonnet::usertools_access($uname,$udom,'portfolio')) {
 2655:             $r->print('<h2>'.&mt('No user portfolio available') .'</h2>'.
 2656:                       &mt('This is a result of one of the following:').'<ul>'.
 2657:                       '<li>'.&mt('The administrator of this domain has disabled portfolio functionality for this specific user.').'</li>'.
 2658:                       '<li>'.&mt('The domain has been configured to disable, by default, portfolio functionality for all users in the domain.').'</li>'.
 2659:                       '</ul>');
 2660:             $r->print(&Apache::loncommon::end_page());
 2661:             return OK;
 2662:         }
 2663:     }
 2664:     $r->rflush();
 2665:     # Check if access to portfolio is blocked by one or more blocking events in courses.
 2666:     my ($blocked,$blocktext) = 
 2667:         &Apache::loncommon::blocking_status('port',$uname,$udom);
 2668:     if ($blocked) {
 2669:         my $evade_block;
 2670:         # If portfolio display is in a window popped up from a "Select Portfolio Files"
 2671:         # link in a .task resource, check if access to the task included proctor validation
 2672:         # of check-in to a slot limited by IP.
 2673:         # If so, and the slot is between its open and close dates, override the block. 
 2674:         if ($env{'request.course.id'} && $env{'form.symb'}) {
 2675:             (undef,undef,my $res) = &Apache::lonnet::decode_symb($env{'form.symb'});
 2676:             if ($res =~ /\.task$/i) {
 2677:                 my %history =
 2678:                     &Apache::lonnet::restore($env{'form.symb'},$env{'request.course.id'},
 2679:                                              $env{'user.domain'},$env{'user.name'});
 2680:                 my $version = $history{'resource.0.version'};
 2681:                 if ($history{'resource.'.$version.'.0.checkedin'}) {
 2682:                     if ($history{'resource.'.$version.'.0.checkedin.slot'}) {
 2683:                         my %slot = &Apache::lonnet::get_slot($history{'resource.'.$version.'.0.checkedin.slot'});
 2684:                         if ($slot{'ip'}) {
 2685:                             if (&Apache::loncommon::check_ip_acc($slot{'ip'})) {
 2686:                                 my $now = time;
 2687:                                 if (($slot{'slottime'} < $now) && ($slot{'endtime'} > $now)) {
 2688:                                     $evade_block = 1;
 2689:                                 }
 2690:                             }
 2691:                         }
 2692:                     }
 2693:                 }
 2694:             }
 2695:         }
 2696:         unless ($evade_block) {
 2697:             $r->print($blocktext);
 2698:             $r->print(&Apache::loncommon::end_page());
 2699:             return OK;
 2700:         }
 2701:     }
 2702:     if (($env{'form.storeupl'}) & (!$env{'form.uploaddoc.filename'})){
 2703:    	$r->print(
 2704:             '<p><span class="LC_warning">'
 2705:            .&mt('No file was selected to upload.')
 2706:            .'</span><br />'
 2707:            .&mt('To upload a file, click [_1]Browse...[_2] and select a file, then click [_1]Upload[_2].'
 2708:                 ,'<strong>','</strong>')
 2709:            .'</p>'
 2710:         );
 2711:     }
 2712:     if ($env{'form.meta'}) {
 2713:         &open_form($r,$url);
 2714:         $r->print(&mt('Edit Metadata').'<br />');
 2715:         &close_form($r,$url);
 2716:     }
 2717:     if ($env{'form.uploaddoc.filename'}) {
 2718:         if ($can_upload) {
 2719: 	    &upload($r,$url,$group);
 2720:         } else {
 2721:             &missing_priv($r,$url,'upload');
 2722:         }
 2723:     } elsif ($env{'form.action'} eq 'process_overwrite') {
 2724:         if ($can_upload) {
 2725:             &overwrite($r,$url,$group);
 2726:         } else {
 2727:             &missing_priv($r,$url,'existingfile');
 2728:         }
 2729:     } elsif ($env{'form.action'} eq 'upload_embedded') {
 2730: 	if ($can_upload) {
 2731:             my $disk_quota = &get_quota($group);
 2732:             my $getpropath = 1;
 2733:             my $current_disk_usage = 
 2734:                 &Apache::lonnet::diskusage($udom,$uname,$portfolio_root,$getpropath);
 2735:             my $container = &HTML::Entities::encode($env{'form.container'},'<>&"');
 2736:             my $state = &embedded_form_elems($container).
 2737:                         '<input type="hidden" name="action" value="modify_orightml" />';
 2738: 	    my ($result,$flag) =
 2739:                 &Apache::loncommon::upload_embedded('portfolio',$port_path,$uname,$udom,
 2740:                     $group,$portfolio_root,$group,$disk_quota,$current_disk_usage,$state,$url);
 2741:             $r->print($result.&done('Return to directory',$url));
 2742:         } else {
 2743:             &missing_priv($r,$url,'upload');
 2744:         }
 2745:     } elsif ($env{'form.action'} eq 'modify_orightml') {
 2746:         if ($can_upload) {
 2747:             my $result = 
 2748:                 &Apache::loncommon::modify_html_refs('portfolio',$port_path,$uname,
 2749:                                                      $udom,$portfolio_root);
 2750:             $r->print($result.
 2751:                       &done('Return to directory',$url));
 2752:         } else {
 2753:             &missing_priv($r,$url,'upload');
 2754:         }
 2755:     } elsif ($env{'form.action'} eq 'delete' && $env{'form.confirmed'}) {
 2756:         if ($can_delete) {
 2757: 	    &delete_confirmed($r,$url,$group);
 2758:         } else {
 2759:             &missing_priv($r,$url,'delete');
 2760:         }
 2761:     } elsif ($env{'form.action'} eq 'delete') {
 2762:         if ($can_delete) {
 2763: 	    &delete($r,$url,$group);
 2764:         } else {
 2765:             &missing_priv($r,$url,'delete');
 2766:         }
 2767:     } elsif ($env{'form.action'} eq 'deletedir' && $env{'form.confirmed'}) {
 2768:         if ($can_delete) {
 2769: 	    &delete_dir_confirmed($r,$url,$group);
 2770:         } else {
 2771:             &missing_priv($r,$url,'delete');
 2772:         }
 2773:     } elsif ($env{'form.action'} eq 'deletedir') {
 2774:         if ($can_delete) {
 2775: 	    &delete_dir($r,$url);
 2776:         } else {
 2777:             &missing_priv($r,$url,'delete');
 2778:         }
 2779:     } elsif ($env{'form.action'} eq 'rename' && $env{'form.confirmed'}) {
 2780:         if ($can_modify) {
 2781: 	    &rename_confirmed($r,$url,$group);
 2782:         } else {
 2783:             &missing_priv($r,$url,'rename');
 2784:         }
 2785:     } elsif ($env{'form.rename'}) {
 2786:         $env{'form.selectfile'} = $env{'form.rename'};
 2787:         $env{'form.action'} = 'rename';
 2788:         if ($can_modify) {
 2789: 	    &rename($r,$url,$group);
 2790:         } else {
 2791:             &missing_priv($r,$url,'rename');
 2792:         }
 2793:     } elsif ($env{'form.access'}) {
 2794:         $env{'form.selectfile'} = $env{'form.access'};
 2795:         if (!defined($env{'form.action'})) { 
 2796:             $env{'form.action'} = 'chgaccess';
 2797:         }
 2798:         &display_access($r,$url,$group,$can_setacl,$port_path,$env{'form.action'});
 2799:     } elsif (($env{'form.action'} eq 'chgaccess') || 
 2800:              ($env{'form.action'} eq 'chgconditions')) {
 2801:         if ($can_setacl) {
 2802:             &update_access($r,$url,$group,$port_path);
 2803:         } else {
 2804:             &missing_priv($r,$url,'setacl');
 2805:         }
 2806:     } elsif ($env{'form.action'} eq 'rolepicker') {
 2807:         if ($can_setacl) { 
 2808:             &role_options_window($r);
 2809:         } else {
 2810:             &missing_priv($r,$url,'setacl');
 2811:         }
 2812:     } elsif ($env{'form.createdir'}) {
 2813:         if ($can_upload) {
 2814: 	    &createdir($r,$url,$group);
 2815:         } else {
 2816:             &missing_priv($r,$url,'upload');
 2817:         }
 2818:     } elsif ($env{'form.lockinfo'}) {
 2819:         &lock_info($r,$url,$group);
 2820:     } else {
 2821:         if ($env{'form.action'} eq 'cancel_overwrite') {
 2822:             if ($can_upload) {
 2823:                 my $formname = 'existingfile';
 2824:                 my $fname = &Apache::lonnet::clean_filename($env{'form.filename'});
 2825:                 $env{'form.'.$formname.'.filename'} = $fname;
 2826:                 my $subdir = $port_path.$env{'form.currentpath'};
 2827:                 $subdir =~ s{(/)$}{};
 2828:                 &Apache::lonnet::userfileupload($formname,'canceloverwrite',$subdir);
 2829:             }
 2830:         }
 2831: 	my $current_path='/';
 2832: 	if ($env{'form.currentpath'}) {
 2833: 	    $current_path = $env{'form.currentpath'};
 2834: 	}
 2835:         if ($caller eq 'coursegrp_portfolio') {
 2836:             &Apache::lonhtmlcommon::clear_breadcrumbs();
 2837:             $r->print(&coursegrp_portfolio_header($udom,$uname,$grp_desc));
 2838:         }
 2839:         my ($dirlistref,$listerror) =
 2840:             &get_dir_list($portfolio_root,$current_path,$group);
 2841: 	if ($listerror eq 'no_such_dir'){
 2842: 	    # two main reasons for this:
 2843:             #    1) never been here, so directory structure not created
 2844: 	    #    2) back-button navigation after deleting a directory
 2845: 	    if ($current_path eq '/'){
 2846: 	        &Apache::lonnet::mkdiruserfile($uname,$udom,
 2847: 					       &get_port_path());
 2848: 	    } else {
 2849:                 # some directory that snuck in get rid of the directory
 2850:                 # from the recent pulldown, just in case
 2851: 		&Apache::lonhtmlcommon::remove_recent('portfolio',
 2852: 						      [$current_path]);
 2853: 		$current_path = '/'; # force it back to the root        
 2854: 	    }
 2855: 	    # now grab the directory list again, for the first time
 2856:             ($dirlistref,$listerror) =
 2857:                 &get_dir_list($portfolio_root,$current_path,$group);
 2858:         }
 2859: 	# need to know if directory is empty so it can be removed if desired
 2860:         my $is_empty;
 2861:         if ($listerror eq 'empty') {
 2862:             $is_empty = 1;
 2863:         } elsif (ref($dirlistref) eq 'ARRAY') {
 2864:             if ((scalar(@{$dirlistref}) == 2) && ($dirlistref->[0] =~ /^\.+\&/)
 2865:                 && ($dirlistref->[1] =~ /^\.+\&/))  {
 2866:                 $is_empty = 1;
 2867:             }
 2868:         }
 2869: 	&display_common($r,$url,$current_path,$is_empty,$dirlistref,
 2870: 			$can_upload,$group);
 2871:         &display_directory($r,$url,$current_path,$is_empty,$dirlistref,$group,
 2872:                            $can_upload,$can_modify,$can_delete,$can_setacl);
 2873:     }
 2874:     $r->print(&Apache::loncommon::end_page());
 2875:     return OK;
 2876: }
 2877: 
 2878: 1;
 2879: __END__

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