File:  [LON-CAPA] / loncom / interface / portfolio.pm
Revision 1.194: download - view: text, annotated - select for diffs
Mon Jun 9 22:34:55 2008 UTC (16 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Move &ask_for_embedded_content() from londocs.pm to loncommon.pm
- &lonnet::extract_embedded_items() - argument change.
  - Path to file to be parsed to look for embedded objects now in a single argunment (first arg), instead of as separate $filepath and $fname.

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

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