File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.187: download - view: text, annotated - select for diffs
Mon Jan 21 11:36:07 2008 UTC (16 years, 4 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Localization:
Added missing &mt(...) and optimzied the usage at some places

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

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