File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.195: download - view: text, annotated - select for diffs
Mon Jun 16 23:34:12 2008 UTC (15 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_7_X, version_2_7_1, version_2_7_0, version_2_6_99_1, version_2_6_99_0, HEAD
- &upload_embedded() moved from portfolio.pm to loncommon.pm to be more widely available.
- &check_for_upload() to prevent overwriting of existing files with uploaded embedded objects moved from portfolio.pm to loncommon.pm.
- &suppress_embed_prompt() added to allow course-wide suppression of embedded object checking for uploded web pages for students in course context.
- checkbox added to allow users to opt out of embedded object checking when uploading web pages to portfolio (default is to check).

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

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