File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.191: download - view: text, annotated - select for diffs
Wed Apr 16 23:11:06 2008 UTC (16 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &get_name_dom() can now take $group as an (optional) argument.
- arguments in calls to lonnet::dirlist() and lonnet::diskusage() modified to use new versions of these subs and to eliminate the need to call &propath() on session server side.

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

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