File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.186: download - view: text, annotated - select for diffs
Tue Jul 10 20:51:46 2007 UTC (16 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_2_6_1, version_2_6_0, version_2_5_X, version_2_5_99_1, version_2_5_99_0, version_2_5_2, version_2_5_1, version_2_5_0, version_2_4_99_0, HEAD
- fix the use of Drop Box items in a .page

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

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