--- loncom/interface/lonmeta.pm	2007/01/15 23:39:16	1.198
+++ loncom/interface/lonmeta.pm	2008/01/23 17:23:16	1.210
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Metadata display handler
 #
-# $Id: lonmeta.pm,v 1.198 2007/01/15 23:39:16 banghart Exp $
+# $Id: lonmeta.pm,v 1.210 2008/01/23 17:23:16 bisitz Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -265,7 +265,7 @@ sub fieldnames {
          'correct'    => 'Material appears to be correct',
          'technical'  => 'Resource is technically correct', 
          'avetries'   => 'Average number of tries till solved',
-         'stdno'      => 'Total number of students who have worked on this problem',
+         'stdno'      => 'Statistics calculated for number of students',
          'difficulty' => 'Degree of difficulty',
          'disc'       => 'Degree of discrimination',
 	     'dependencies' => 'Resources used by this resource',
@@ -383,7 +383,40 @@ sub select_course {
 	$Apache::lonpublisher::metadatafields{'courserestricted'};
     my $selected = ($current_restriction eq 'none' ? 'selected="selected"' 
 		                                   : '');
-
+    if ($current_restriction =~ /^course\.($match_domain\_$match_courseid)$/) {
+        my $assoc_crs = $1;
+        my $added_metadata_fields = &Apache::lonparmset::get_added_meta_fieldnames($assoc_crs);
+        if (ref($added_metadata_fields) eq 'HASH') {
+            if (keys(%{$added_metadata_fields}) > 0) {
+                my $transfernotes;
+                foreach my $field_name (keys(%{$added_metadata_fields})) {
+                    my $value = $Apache::lonpublisher::metadatafields{$field_name};
+                    if ($value) {
+                        $transfernotes .= 
+                            &Apache::loncommon::start_data_table_row(). 
+                            '<td><input type="checkbox" name="transfer_'.
+                            $field_name.'" value="1" /></td><td>'.
+                            $field_name.'</td><td>'.$value.'</td>'.
+                            &Apache::loncommon::end_data_table_row();
+                    }
+                }
+                if ($transfernotes ne '') {
+                    my %courseinfo = &Apache::lonnet::coursedescription($assoc_crs,{'one_time' => 1});
+                    my $assoc_crs_description = $courseinfo{'description'};
+                    $output .= &mt('This resource is currently associated with a course ([_1]) which includes added metadata fields specific to the course.',$assoc_crs_description).'<br />'."\n".
+                    &mt('You can choose to transfer data from the added fields to the "Notes" field if you are planning to change the course association.').'<br /><br />'.
+                    &Apache::loncommon::start_data_table().
+                    &Apache::loncommon::start_data_table_header_row().
+                    '<th>Copy to notes?</th>'."\n".
+                    '<th>Field name</th>'."\n".
+                    '<th>Values</th>'."\n".
+                    &Apache::loncommon::end_data_table_header_row().
+                    $transfernotes.
+                    &Apache::loncommon::end_data_table().'<br />';
+                }
+            }
+        }
+    }
     $output .= '<select name="new_courserestricted" >';
     $output .= '<option value="none" '.$selected.'>'.
 	&mt('None').'</option>'.$/;
@@ -598,14 +631,15 @@ sub prettyinput {
                 if ($meta_options{$item}) {
                     push(@cur_values_inst,$item);
                 } else {
-                    if ($item ne 'Not Specified') {
+                    if ($item ne '') {
                         $cur_values_stu .= $item.',';
                     }
                 }
             }
+             $cur_values_stu =~ s/,$//;
             my @key_order = sort(keys(%meta_options));
-            unshift (@key_order,'Not Specified');
-            $meta_options{'Not Specified'} = 'Not Specified';
+            unshift(@key_order,'');
+            $meta_options{''} = 'Not specified';
             $meta_options{'select_form_order'} = \@key_order;
         } else {
             $cur_values_stu = $value;
@@ -614,11 +648,10 @@ sub prettyinput {
             return (&select_course());
             # return ('<input type="hidden" name="new_courserestricted" value="'.$course_key.'" />');
         }
-        my $course = $env{'request.course.id'};
         if (($type eq 'keywords') || ($type eq 'subject')
              || ($type eq 'author')||($type eq  'notes')
              || ($type eq  'abstract')|| ($type eq  'title')|| ($type eq  'standards')
-             || (exists($env{'course.'.$env{'request.course.id'}.'.metadata.'.$type.'.added'}))) {
+             || (exists($env{$course_key.'.metadata.'.$type.'.added'}))) {
             
             if ($values) {
                 if ($only_one) {
@@ -771,8 +804,10 @@ sub handler {
         &present_editable_metadata($r,$uri,'groups');    
     } elsif ($uri=~m|^/~|) { 
         # Construction space
-        $r->print(&Apache::loncommon::start_page('Edit Catalog nformation',
-						 undef,
+        $r->print(&Apache::loncommon::start_page('Edit Catalog Information',
+						"\n".'<script type="text/javascript">'."\n".
+                                                &Apache::loncommon::browser_and_searcher_javascript().
+                                                "\n".'</script>',
 						 {'domain' => $resdomain,}));
         &present_editable_metadata($r,$uri);
     } else {
@@ -991,17 +1026,17 @@ sub print_dynamic_metadata {
             #
             # New assessment statistics
             $r->print('<h4>'.
-                      &mt('Detailed Assessment Statistical Data').
+                      &mt('Recent Detailed Assessment Statistical Data').
                       '</h4>');
             my $table = '<table cellspacing="2" border="0">'.
                 '<tr>'.
-                '<th>Course</th>'.
-                '<th>Section(s)</th>'.
-                '<th>Num Students</th>'.
-                '<th>Mean Tries</th>'.
-                '<th>Degree of Difficulty</th>'.
-                '<th>Degree of Discrimination</th>'.
-                '<th>Time of computation</th>'.
+                '<th>'.&mt('Course').'</th>'.
+                '<th>'.&mt('Section(s)').'</th>'.
+                '<th>'.&mt('Num Student').'s</th>'.
+                '<th>'.&mt('Mean Tries').'</th>'.
+                '<th>'.&mt('Degree of Difficulty').'</th>'.
+                '<th>'.&mt('Degree of Discrimination').'</th>'.
+                '<th>'.&mt('Time of computation').'</th>'.
                 '</tr>'.$/;
             foreach my $identifier (sort(keys(%{$dynmeta{'stats'}}))) {
                 my $data = $dynmeta{'stats'}->{$identifier};
@@ -1039,7 +1074,7 @@ sub print_dynamic_metadata {
             $table .= '</table>'.$/;
             $r->print($table);
         } else {
-            $r->print('No new dynamic data found.');
+            $r->print(&mt('No new dynamic data found.'));
         }
     } else {
         $r->print('<h4>'.
@@ -1177,11 +1212,16 @@ ENDBOMBS
 <input type="submit" name="clearmsg" value="$clear" />
 ENDDEL
         } else {
-            $r->print('<a href="'.$disuri.'" />'.$goback.'</a>');
+            $r->print('<p><a href="'.$disuri.'">'.$goback.'</a></p>');
+	    if ($env{'form.clearmsg'}) {
+		my ($diruri) = ($disuri =~ m{(.*/)[^/]*});
+		$r->print('<p><a href="'.$diruri.'">'.
+			  &mt('Back To Directory').'</a></p>');
+	    }
 	}
 	$r->print('<br />'.$bombs);
     } else {
-        my $displayfile='Catalog Information for '.$disuri;
+        my $displayfile=&mt('Catalog Information for').' '.$disuri;
         if ($disuri=~/\/default$/) {
             my $dir=$disuri;
             $dir=~s/default$//;
@@ -1197,13 +1237,26 @@ ENDDEL
         } else {
             &Apache::lonpublisher::metaeval($result);
         }
+        if ($env{'form.new_courserestricted'}) {
+            my $new_assoc_course = $env{'form.new_courserestricted'};
+            my $prev_courserestricted = $Apache::lonpublisher::metadatafields{'courserestricted'};
+            if (($prev_courserestricted) && 
+                ($prev_courserestricted ne $new_assoc_course)) {
+                my $transfers = [];
+                foreach my $key (keys(%env)) {
+                    if ($key =~ /^form\.transfer_(.+)$/) {
+                        push(@{$transfers},$1);
+                    }
+                }
+                if (@{$transfers} > 0) {
+                    &store_transferred_addedfields($fn,$uri,$transfers);
+                }
+            }
+        }
         $r->print(<<ENDEDIT);
 <h1>$displayfile</h1>
 <form method="post" action="" name="defaultmeta">
 ENDEDIT
-        $r->print('<script type="JavaScript">'.
-                  &Apache::loncommon::browser_and_searcher_javascript().
-                  '</script>');
         my %lt=&fieldnames($file_type);
 	my $output;
 	my @fields;
@@ -1259,6 +1312,11 @@ ENDEDIT
 		$Apache::lonpublisher::metadatafields{'owner'} =
 		    $env{'user.name'}.':'.$env{'user.domain'};
 	    }
+	    if (! $Apache::lonpublisher::metadatafields{'author'}) {
+		$Apache::lonpublisher::metadatafields{'author'} =
+		    &Apache::loncommon::plainname($env{'user.name'},
+						  $env{'user.domain'});
+	    }
 	    if ($Apache::lonpublisher::metadatafields{'courserestricted'} ne 'none') {
 
                 if ($file_type eq 'portfolio') {
@@ -1274,7 +1332,7 @@ ENDEDIT
                         ".description"}.'</strong>').'<br />');
                 }
 	    } else {
-		$r->print('<a href="'.$uri.'?changecourse=true">This resource is not associated with a course.</a><br />');
+		$r->print('<a href="'.$uri.'?changecourse=true">'.&mt('This resource is not associated with a course.').'</a><br />');
 	    }
 	}
 	if (@added_order) {
@@ -1292,8 +1350,15 @@ ENDEDIT
         my $row_alt = 1;
         foreach my $field_name (@fields) {
             if (defined($env{'form.new_'.$field_name})) {
-                $Apache::lonpublisher::metadatafields{$field_name}=
-                    join(',',&Apache::loncommon::get_env_multiple('form.new_'.$field_name));
+                my @values = &Apache::loncommon::get_env_multiple('form.new_'.$field_name);
+                my $newvalue = '';
+                foreach my $item (@values) {
+                    if ($item ne '') {
+                        $newvalue .= $item.',';
+                    }
+                }
+                $newvalue =~ s/,$//; 
+                $Apache::lonpublisher::metadatafields{$field_name}=$newvalue;
             }
             if ($Apache::lonpublisher::metadatafields{'courserestricted'} ne 'none'
 		&& exists($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'})) {
@@ -1322,60 +1387,11 @@ ENDEDIT
         }
         $output .= &Apache::loncommon::end_data_table();
 	if ($env{'form.store'}) {
-	    my $mfh;
-	    my $formname='store'; 
-	    my $file_content;
-	    if (&Apache::loncommon::get_env_multiple('form.new_keywords')) {
-		$Apache::lonpublisher::metadatafields{'keywords'} = 
-		    join (',', &Apache::loncommon::get_env_multiple('form.new_keywords'));
-	    }
-	    foreach my $field (sort(keys(%Apache::lonpublisher::metadatafields))) {
-		next if ($field =~ /\./);
-		my $unikey=$field;
-		$unikey=~/^([A-Za-z_]+)/;
-		my $tag=$1;
-		$tag=~tr/A-Z/a-z/;
-		$file_content.= "\n\<$tag";
-		foreach my $key (split(/\,/,
-				       $Apache::lonpublisher::metadatakeys{$unikey})
-				 ) {
-		    my $value=
-			$Apache::lonpublisher::metadatafields{$unikey.'.'.$key};
-		    $value=~s/\"/\'\'/g;
-		    $file_content.=' '.$key.'="'.$value.'"' ;
-		}
-		$file_content.= '>'.
-		    &HTML::Entities::encode
-		    ($Apache::lonpublisher::metadatafields{$unikey},
-		     '<>&"').
-		     '</'.$tag.'>';
-	    }
-	    if ($fn =~ m|^$Apache::lonnet::perlvar{'lonDocRoot'}/userfiles|) {
-	        my ($path, $new_fn);
-	        if ($fn =~ m|$match_name/groups/\w+/portfolio/|) {
-                    ($path, $new_fn) = ($fn =~ m|/(groups/\w+/portfolio.*)/([^/]*)$|);
-	        } else {
-		    ($path, $new_fn) = ($fn =~ m|/(portfolio.*)/([^/]*)$|);
-	        }
-                $r->print(&store_portfolio_metadata($formname,$file_content,$path,
-                                                    $new_fn,$uri));
-            } else {
-		if (! ($mfh=Apache::File->new('>'.$fn))) {
-		    $r->print('<p><font color="red">'.
-			      &mt('Could not write metadata').', '.
-			      &mt('FAIL').'</font></p>');
-		} else {
-		    print $mfh ($file_content);
-                    close($mfh);
-                    &update_metadata_table($uri);
-		    $r->print('<p><font color="blue">'.&mt('Wrote Metadata').
-			      ' '.&Apache::lonlocal::locallocaltime(time).
-			      '</font></p>');
-		}
-	    }
+            my ($outcome,$result) = &store_metadata($fn,$uri,'store');
+            $r->print($result);
 	}
 	$r->print($output.'<br /><input type="submit" name="store" value="'.
-                  &mt('Store Catalog Information').'" />');
+                  &mt('Save Catalog Information').'" />');
 
 	if ($file_type eq 'portfolio' || $file_type eq 'groups') {
 	    my ($port_path,$group) = &get_port_path_and_group($uri);
@@ -1397,20 +1413,114 @@ ENDEDIT
     return;
 }
 
+sub store_metadata {
+    my ($fn,$uri,$caller) = @_;
+    my $mfh;
+    my $formname='store';
+    my ($file_content,$output,$outcome);
+    if (&Apache::loncommon::get_env_multiple('form.new_keywords')) {
+        $Apache::lonpublisher::metadatafields{'keywords'} =
+            join (',', &Apache::loncommon::get_env_multiple('form.new_keywords'));
+            }
+    foreach my $field (sort(keys(%Apache::lonpublisher::metadatafields))) {
+        next if ($field =~ /\./);
+        my $unikey=$field;
+        $unikey=~/^([A-Za-z_]+)/;
+        my $tag=$1;
+        $tag=~tr/A-Z/a-z/;
+        $file_content.= "\n\<$tag";
+        foreach my $key (split(/\,/,$Apache::lonpublisher::metadatakeys{$unikey})) {
+            my $value = $Apache::lonpublisher::metadatafields{$unikey.'.'.$key};
+            $value=~s/\"/\'\'/g;
+            $file_content.=' '.$key.'="'.$value.'"' ;
+        }
+        $file_content.= '>'.
+            &HTML::Entities::encode
+                ($Apache::lonpublisher::metadatafields{$unikey},'<>&"').
+                '</'.$tag.'>';
+    }
+    if ($fn =~ m|^$Apache::lonnet::perlvar{'lonDocRoot'}/userfiles|) {
+        my ($path, $new_fn);
+        if ($fn =~ m|$match_name/groups/\w+/portfolio/|) {
+            ($path, $new_fn) = ($fn =~ m|/(groups/\w+/portfolio.*)/([^/]*)$|);
+        } else {
+            ($path, $new_fn) = ($fn =~ m|/(portfolio.*)/([^/]*)$|);
+        }
+        ($outcome,my $result) = 
+            &store_portfolio_metadata($formname,$file_content,
+                                      $path,$new_fn,$uri,$caller);
+        $output .= $result;
+    } else {
+        if (! ($mfh=Apache::File->new('>'.$fn))) {
+            $output .= '<p><font color="red">';
+            if ($caller eq 'transfer') {
+                $output .= &mt('Could not transfer data in added fields to notes');
+            } else { 
+                $output .= &mt('Could not write metadata');
+            }
+            $output .= ', '.&mt('FAIL').'</font></p>';
+            $outcome = 'fail';
+        } else {
+            print $mfh ($file_content);
+            close($mfh);
+            &update_metadata_table($uri);
+            $output .= '<p><font color="blue">';
+            if ($caller eq 'transfer') {
+                $output .= &mt('Transferred data in added fields to notes');
+            } else {
+                $output .= &mt('Wrote Metadata');
+            }
+            $output .= ' '.&Apache::lonlocal::locallocaltime(time).
+                       '</font></p>';
+            $outcome = 'ok';
+        }
+    }
+    return ($outcome,$output);
+}
+
+sub store_transferred_addedfields {
+    my ($fn,$uri,$transfers) = @_;
+    foreach my $item (@{$transfers}) {
+        $Apache::lonpublisher::metadatafields{'notes'} .= 
+           ' '.$item.' = '.$Apache::lonpublisher::metadatafields{$item};
+    }
+    my ($outcome,$output) = &store_metadata($fn,$uri,'transfer');
+    if ($outcome eq 'ok') {
+        foreach my $item (@{$transfers}) {
+            delete($Apache::lonpublisher::metadatafields{$item});
+        }
+    }
+}
+
 sub store_portfolio_metadata {
-    my ($formname,$content,$path,$new_fn,$uri) = @_;
+    my ($formname,$content,$path,$new_fn,$uri,$caller) = @_;
+    my ($outcome,$output);
     $env{'form.'.$formname}=$content."\n";
     $env{'form.'.$formname.'.filename'}=$new_fn;
     my $result =&Apache::lonnet::userfileupload($formname,'',$path);
     if ($result =~ /(error|notfound)/) {
-        return '<p><font color="red">'.
-                  &mt('Could not write metadata').', '.
-                  &mt('FAIL').'</font></p>';
+        $output = '<p><font color="red">';
+        if ($caller eq 'transfer') {
+            $output .= 
+                &mt('Could not transfer data in added fields to notes'); 
+        } else {
+            $output .= &mt('Could not write metadata');
+        }
+        $output .= ', '.&mt('FAIL').'</font></p>';
+        $outcome = 'fail';
     } else {
         &update_metadata_table($uri);
-        return '<p><font color="blue">'.&mt('Wrote Metadata').
-                  ' '.&Apache::lonlocal::locallocaltime(time).'</font></p>';
+        $output = '<p><font color="blue">';
+        if ($caller eq 'transfer') {
+            $output .= &mt('Transferred data in added fields to notes');
+        } else {
+            $output .= &mt('Wrote Metadata');
+        }
+        $output .= ' '.&Apache::lonlocal::locallocaltime(time).
+                   '</font></p>';
+        $outcome = 'ok';
     }
+    return ($outcome,$output);
 }
 
 sub update_metadata_table {