File:  [LON-CAPA] / loncom / interface / lonmeta.pm
Revision 1.257: download - view: text, annotated - select for diffs
Tue Nov 7 21:31:11 2023 UTC (6 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Support domain default or user override in new metadata file for:
  Default Copyright/Distribution and Default Source Available.

    1: # The LearningOnline Network with CAPA
    2: # Metadata display handler
    3: #
    4: # $Id: lonmeta.pm,v 1.257 2023/11/07 21:31:11 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::lonmeta;
   30: 
   31: use strict;
   32: use LONCAPA::lonmetadata();
   33: use Apache::Constants qw(:common);
   34: use Apache::lonnet;
   35: use Apache::loncommon();
   36: use Apache::lonhtmlcommon(); 
   37: use Apache::lonmsg;
   38: use Apache::lonpublisher;
   39: use Apache::lonlocal;
   40: use Apache::lonmysql;
   41: use Apache::lonmsg;
   42: use LONCAPA qw(:DEFAULT :match);
   43: 
   44: 
   45: sub get_dynamic_metadata_from_sql {
   46:     my ($url) = shift();
   47:     my ($authordom,$author)=($url=~m{^/res/($match_domain)/($match_username)/});
   48:     if (! defined($authordom)) {
   49:         $authordom = shift();
   50:     }
   51:     if  (! defined($author)) { 
   52:         $author = shift();
   53:     }
   54:     if (! defined($authordom) || ! defined($author)) {
   55:         return ();
   56:     }
   57:     my $query = 'SELECT * FROM metadata WHERE url LIKE "'.$url.'%"';
   58:     my $server = &Apache::lonnet::homeserver($author,$authordom);
   59:     my $reply = &Apache::lonnet::metadata_query($query,undef,undef,
   60:                                                 ,[$server]);
   61:     return () if (! defined($reply) || ref($reply) ne 'HASH');
   62:     my $filename = $reply->{$server};
   63:     if (! defined($filename) || $filename =~ /^error/) {
   64:         return ();
   65:     }
   66:     my $max_time = time + 10; # wait 10 seconds for results at most
   67:     my %ReturnHash;
   68:     #
   69:     # Look for results
   70:     my $finished = 0;
   71:     while (! $finished && time < $max_time) {
   72:         my $datafile=$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename;
   73:         if (! -e "$datafile.end") { next; }
   74:         my $fh;
   75:         if (!($fh=Apache::File->new($datafile))) { next; }
   76:         while (my $result = <$fh>) {
   77:             chomp($result);
   78:             next if (! $result);
   79:             my %hash=&LONCAPA::lonmetadata::metadata_col_to_hash('metadata',
   80: 								 map { &unescape($_) } split(/\,/,$result));
   81:             foreach my $key (keys(%hash)) {
   82:                 $ReturnHash{$hash{'url'}}->{$key}=$hash{$key};
   83:             }
   84:         }
   85:         $finished = 1;
   86:     }
   87:     #
   88:     return %ReturnHash;
   89: }
   90: 
   91: 
   92: # Fetch and evaluate dynamic metadata
   93: sub dynamicmeta {
   94:     my $url=&Apache::lonnet::declutter(shift);
   95:     $url=~s/\.meta$//;
   96:     my ($adomain,$aauthor)=($url=~/^($match_domain)\/($match_username)\//);
   97:     my $regexp=$url;
   98:     $regexp=~s/(\W)/\\$1/g;
   99:     $regexp='___'.$regexp.'___';
  100:     my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
  101: 				       $aauthor,$regexp);
  102:     my %DynamicData = &LONCAPA::lonmetadata::process_reseval_data(\%evaldata);
  103:     my %Data = &LONCAPA::lonmetadata::process_dynamic_metadata($url,
  104:                                                                \%DynamicData);
  105:     #
  106:     # Deal with 'count' separately
  107:     $Data{'count'} = &access_count($url,$aauthor,$adomain);
  108:     #
  109:     # Debugging code I will probably need later
  110:     if (0) {
  111:         &Apache::lonnet::logthis('Dynamic Metadata');
  112:         while(my($k,$v)=each(%Data)){
  113:             &Apache::lonnet::logthis('    "'.$k.'"=>"'.$v.'"');
  114:         }
  115:         &Apache::lonnet::logthis('-------------------');
  116:     }
  117:     return %Data;
  118: }
  119: 
  120: sub access_count {
  121:     my ($src,$author,$adomain) = @_;
  122:     my %countdata=&Apache::lonnet::dump('nohist_accesscount',$adomain,
  123:                                         $author,$src);
  124:     if (! exists($countdata{$src})) {
  125:         return &mt('Not Available');
  126:     } else {
  127:         return $countdata{$src};
  128:     }
  129: }
  130: 
  131: # Try to make an alt tag if there is none
  132: sub alttag {
  133:     my ($base,$src)=@_;
  134:     my $fullpath=&Apache::lonnet::hreflocation($base,$src);
  135:     my $alttag=&Apache::lonnet::metadata($fullpath,'title').' '.
  136:         &Apache::lonnet::metadata($fullpath,'subject').' '.
  137:         &Apache::lonnet::metadata($fullpath,'abstract');
  138:     $alttag=~s/\s+/ /gs;
  139:     $alttag=~s/\"//gs;
  140:     $alttag=~s/\'//gs;
  141:     $alttag=~s/\s+$//gs;
  142:     $alttag=~s/^\s+//gs;
  143:     if ($alttag) { 
  144:         return $alttag; 
  145:     } else { 
  146:         return &mt('No information available'); 
  147:     }
  148: }
  149: 
  150: # Author display
  151: sub authordisplay {
  152:     my ($aname,$adom)=@_;
  153:     return &Apache::loncommon::aboutmewrapper
  154:         (&Apache::loncommon::plainname($aname,$adom),
  155:          $aname,$adom,'preview').' <tt>['.$aname.':'.$adom.']</tt>';
  156: }
  157: 
  158: # Pretty display
  159: sub evalgraph {
  160:     my $value=shift;
  161:     if (! $value) { 
  162:         return '';
  163:     }
  164:     my $val=int($value*10.+0.5)-10;
  165:     my $output='<table border="0" cellpadding="0" cellspacing="0"><tr>';
  166:     if ($val>=20) {
  167: 	$output.='<td width="20" bgcolor="#555555">'.('&nbsp;' x2).'</td>';
  168:     } else {
  169:         $output.='<td width="'.($val).'" bgcolor="#555555">&nbsp;</td>'.
  170:                  '<td width="'.(20-$val).'" bgcolor="#FF3333">&nbsp;</td>';
  171:     }
  172:     $output.='<td bgcolor="#FFFF33">&nbsp;</td>';
  173:     if ($val>20) {
  174: 	$output.='<td width="'.($val-20).'" bgcolor="#33FF33">&nbsp;</td>'.
  175:                  '<td width="'.(40-$val).'" bgcolor="#555555">&nbsp;</td>';
  176:     } else {
  177:         $output.='<td width="20" bgcolor="#555555">'.('&nbsp;' x2).'</td>';
  178:     }
  179:     $output.='<td> ('.sprintf("%5.2f",$value).') </td></tr></table>';
  180:     return $output;
  181: }
  182: 
  183: sub diffgraph {
  184:     my $value=shift;
  185:     if (! $value) { 
  186:         return '';
  187:     }
  188:     my $val=int(40.0*$value+0.5);
  189:     my @colors=('#FF9933','#EEAA33','#DDBB33','#CCCC33',
  190:                 '#BBDD33','#CCCC33','#DDBB33','#EEAA33');
  191:     my $output='<table border="0" cellpadding="0" cellspacing="0"><tr>';
  192:     for (my $i=0;$i<8;$i++) {
  193: 	if ($val>$i*5) {
  194:             $output.='<td width="5" bgcolor="'.$colors[$i].'">&nbsp;</td>';
  195:         } else {
  196: 	    $output.='<td width="5" bgcolor="#555555">&nbsp;</td>';
  197: 	}
  198:     }
  199:     $output.='<td> ('.sprintf("%3.2f",$value).') </td></tr></table>';
  200:     return $output;
  201: }
  202: 
  203: 
  204: # The field names
  205: sub fieldnames {
  206:     my $file_type=shift;
  207:     my %fields = 
  208:         ('title' => 'Title',
  209:          'author' =>'Author(s)',
  210:          'authorspace' => 'Author Space',
  211:          'modifyinguser' => 'Last Modifying User',
  212:          'subject' => 'Subject',
  213:          'standards' => 'Standards',
  214:          'keywords' => 'Keyword(s)',
  215:          'notes' => 'Notes',
  216:          'abstract' => 'Abstract',
  217:          'lowestgradelevel' => 'Lowest Grade Level',
  218:          'highestgradelevel' => 'Highest Grade Level');
  219:     
  220:     if ( !defined($file_type) || ($file_type ne 'portfolio' && $file_type ne 'groups') ) {
  221:         %fields = 
  222:         (%fields,
  223:          'domain' => 'Domain',
  224:          'mime' => 'MIME Type',
  225:          'language' => 'Language',
  226:          'creationdate' => 'Creation Date',
  227:          'lastrevisiondate' => 'Last Revision Date',
  228:          'owner' => 'Publisher/Owner',
  229:          'copyright' => 'Copyright/Distribution',
  230:          'customdistributionfile' => 'Custom Distribution File',
  231:          'sourceavail' => 'Source Available',
  232:          'sourcerights' => 'Source Custom Distribution File',
  233:          'obsolete' => 'Obsolete',
  234:          'obsoletereplacement' => 'Suggested Replacement for Obsolete File',
  235:          'count'      => 'Network-wide number of accesses (hits)',
  236:          'course'     => 'Network-wide number of courses using resource',
  237:          'course_list' => 'Network-wide courses using resource',
  238:          'sequsage'      => 'Number of resources using or importing resource',
  239:          'sequsage_list' => 'Resources using or importing resource',
  240:          'goto'       => 'Number of resources that follow this resource in maps',
  241:          'goto_list'  => 'Resources that follow this resource in maps',
  242:          'comefrom'   => 'Number of resources that lead up to this resource in maps',
  243:          'comefrom_list' => 'Resources that lead up to this resource in maps',
  244:          'clear'      => 'Material presented in clear way',
  245:          'depth'      => 'Material covered with sufficient depth',
  246:          'helpful'    => 'Material is helpful',
  247:          'correct'    => 'Material appears to be correct',
  248:          'technical'  => 'Resource is technically correct', 
  249:          'avetries'   => 'Average number of tries till solved',
  250:          'stdno'      => 'Statistics calculated for number of students',
  251:          'difficulty' => 'Degree of difficulty',
  252:          'disc'       => 'Degree of discrimination',
  253: 	     'dependencies' => 'Resources used by this resource',
  254:          );
  255:     }
  256:     return &Apache::lonlocal::texthash(%fields);
  257: }
  258: 
  259: sub portfolio_linked_path {
  260:     my ($path,$group,$port_path) = @_;
  261: 
  262:     my $start = 'portfolio';
  263:     if ($group) {
  264: 	$start = "groups/$group/".$start;
  265:     }
  266:     my %anchor_fields = (
  267:         'selectfile'  => $start,
  268:         'currentpath' => '/'
  269:     );
  270:     my $result = &Apache::portfolio::make_anchor($port_path,\%anchor_fields,$start);
  271:     my $fullpath = '/';
  272:     my (undef,@tree) = split('/',$path);
  273:     my $filename = pop(@tree);
  274:     foreach my $dir (@tree) {
  275: 	$fullpath .= $dir.'/';
  276: 	$result .= '/';
  277: 	my %anchor_fields = (
  278:             'selectfile'  => $dir,
  279:             'currentpath' => $fullpath
  280:         );
  281: 	$result .= &Apache::portfolio::make_anchor($port_path,\%anchor_fields,$dir);
  282:     }
  283:     $result .= "/$filename";
  284:     return $result;
  285: }
  286: 
  287: sub get_port_path_and_group {
  288:     my ($uri)=@_;
  289: 
  290:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  291:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  292: 
  293:     my ($port_path,$group);
  294:     if ($uri =~ m{^/editupload/\Q$cdom\E/\Q$cnum\E/groups/}) {
  295: 	$group = (split('/',$uri))[5];
  296: 	$port_path = '/adm/coursegrp_portfolio';
  297:     } else {
  298: 	$port_path = '/adm/portfolio';
  299:     }
  300:     if ($env{'form.group'} ne $group) {
  301: 	$env{'form.group'} = $group;
  302:     }
  303:     return ($port_path,$group);
  304: }
  305: 
  306: sub portfolio_display_uri {
  307:     my ($uri,$as_links)=@_;
  308: 
  309:     my ($port_path,$group) = &get_port_path_and_group($uri);
  310: 
  311:     $uri =~ s|.*/(portfolio/.*)$|$1|;
  312:     my ($res_uri,$meta_uri) = ($uri,$uri);
  313:     if ($uri =~ /\.meta$/) {
  314: 	$res_uri =~ s/\.meta//;
  315:     } else {
  316: 	$meta_uri .= '.meta';
  317:     }
  318: 
  319:     my ($path) = ($res_uri =~ m|^portfolio(.*/)[^/]*$|);
  320:     if ($as_links) {
  321: 	$res_uri = &portfolio_linked_path($res_uri,$group,$port_path);
  322: 	$meta_uri = &portfolio_linked_path($meta_uri,$group,$port_path);
  323:     }
  324:     return ($res_uri,$meta_uri,$path);
  325: }
  326: 
  327: sub pre_select_course {
  328:     my ($r,$uri) = @_;
  329:     my $output;
  330:     my $fn=&Apache::lonnet::filelocation('',$uri);
  331:     my ($res_uri,$meta_uri,$path) = &portfolio_display_uri($uri);
  332:     %Apache::lonpublisher::metadatafields=();
  333:     %Apache::lonpublisher::metadatakeys=();
  334:     my $result=&Apache::lonnet::getfile($fn);
  335:     if ($result == -1){
  336:         $r->print(&mt('Creating new file [_1]'),$meta_uri);
  337:     } else {
  338:         &Apache::lonpublisher::metaeval($result);
  339:     }
  340:     $r->print('<hr /><form method="post" action="" >');
  341:     $r->print('<p>'.&mt('If you would like to associate this resource ([_1]) with a current or previous course, please select one from the list below, otherwise select, "None".','<tt>'.$res_uri.'</tt>').'</p>');
  342:     $output = &select_course();
  343:     $r->print($output.'<br /><input type="submit" name="store" value="'.
  344:                   &mt('Associate Resource With Selected Course').'" />');
  345:     $r->print('<input type="hidden" name="currentpath" value="'.$env{'form.currentpath'}.'" />');
  346:     $r->print('<input type="hidden" name="associate" value="true" />');
  347:     $r->print('</form>');
  348:     
  349:     my ($port_path,$group) = &get_port_path_and_group($uri);
  350:     my $group_input;
  351:     if ($group) {
  352:         $group_input = '<input type="hidden" name="group" value="'.$group.'" />';
  353:     } 
  354:     $r->print(' <form method="post" action="'.$port_path.'">'.
  355:               '<input type="hidden" name="currentpath" value="'.$path.'" />'.
  356: 	      $group_input.
  357: 	      '<input type="submit" name="cancel" value="'.&mt('Cancel').'" />'.
  358: 	      '</form>');
  359: 
  360:     return;
  361: }
  362: sub select_course {
  363:     my $output=$/;
  364:     my $current_restriction=
  365: 	$Apache::lonpublisher::metadatafields{'courserestricted'};
  366:     my $selected = ($current_restriction eq 'none' ? 'selected="selected"' 
  367: 		                                   : '');
  368:     if ($current_restriction =~ /^course\.($match_domain\_$match_courseid)$/) {
  369:         my $assoc_crs = $1;
  370:         my $added_metadata_fields = &Apache::lonparmset::get_added_meta_fieldnames($assoc_crs);
  371:         if (ref($added_metadata_fields) eq 'HASH') {
  372:             if (keys(%{$added_metadata_fields}) > 0) {
  373:                 my $transfernotes;
  374:                 foreach my $field_name (keys(%{$added_metadata_fields})) {
  375:                     my $value = $Apache::lonpublisher::metadatafields{$field_name};
  376:                     if ($value) {
  377:                         $transfernotes .= 
  378:                             &Apache::loncommon::start_data_table_row(). 
  379:                             '<td><input type="checkbox" name="transfer_'.
  380:                             $field_name.'" value="1" /></td><td>'.
  381:                             $field_name.'</td><td>'.$value.'</td>'.
  382:                             &Apache::loncommon::end_data_table_row();
  383:                     }
  384:                 }
  385:                 if ($transfernotes ne '') {
  386:                     my %courseinfo = &Apache::lonnet::coursedescription($assoc_crs,{'one_time' => 1});
  387:                     my $assoc_crs_description = $courseinfo{'description'};
  388:                     $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".
  389:                     &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 />'.
  390:                     &Apache::loncommon::start_data_table().
  391:                     &Apache::loncommon::start_data_table_header_row().
  392:                     '<th>'.&mt('Copy to notes?').'</th>'."\n".
  393:                     '<th>'.&mt('Field Name').'</th>'."\n".
  394:                     '<th>'.&mt('Values').'</th>'."\n".
  395:                     &Apache::loncommon::end_data_table_header_row().
  396:                     $transfernotes.
  397:                     &Apache::loncommon::end_data_table().'<br />';
  398:                 }
  399:             }
  400:         }
  401:     }
  402:     $output .= '<select name="new_courserestricted" >';
  403:     $output .= '<option value="none" '.$selected.'>'.
  404: 	&mt('None').'</option>'.$/;
  405:     my %courses;
  406:     foreach my $key (keys(%env)) {
  407:         if ($key !~ m/^course\.(.+)\.description$/) { next; }
  408: 	my $cid = $1;
  409:         if ($env{$key} !~ /\S/) { next; }
  410: 	$courses{$key} = $cid;
  411:     }
  412:     foreach my $key (sort { lc($env{$a}) cmp lc($env{$b}) } (keys(%courses))) {
  413: 	my $cid = 'course.'.$courses{$key};
  414: 	my $selected = ($current_restriction eq $cid ? 'selected="selected"' 
  415: 		                                     : '');
  416:         if ($env{$key} !~ /\S/) { next; }
  417: 	$output .= '<option value="'.$cid.'" '.$selected.'>';
  418: 	$output .= $env{$key};
  419: 	$output .= '</option>'.$/;
  420: 	$selected = '';
  421:     }
  422:     $output .= '</select><br />';
  423:     return ($output);
  424: }
  425: # Pretty printing of metadata field
  426: 
  427: sub prettyprint {
  428:     my ($type,$value,$target,$prefix,$form)=@_;
  429: # $target,$prefix,$form are optional and for filecrumbs only
  430:     if (! defined($value)) { 
  431:         return '&nbsp;'; 
  432:     }
  433:     # Title
  434:     if ($type eq 'title') {
  435: 	return $value;
  436:     }
  437:     # Dates
  438:     if (($type eq 'creationdate') ||
  439: 	($type eq 'lastrevisiondate')) {
  440: 	return ($value?&Apache::lonlocal::locallocaltime(
  441: 			  &Apache::lonmysql::unsqltime($value)):
  442: 		&mt('not available'));
  443:     }
  444:     # Language
  445:     if ($type eq 'language') {
  446: 	return &Apache::loncommon::languagedescription($value);
  447:     }
  448:     # Copyright
  449:     if ($type eq 'copyright') {
  450: 	return &Apache::loncommon::copyrightdescription($value);
  451:     }
  452:     # Copyright
  453:     if ($type eq 'sourceavail') {
  454: 	return &Apache::loncommon::source_copyrightdescription($value);
  455:     }
  456:     # MIME
  457:     if ($type eq 'mime') {
  458:         return '<img src="'.&Apache::loncommon::icon($value).'" alt="" />&nbsp;'.
  459:             &Apache::loncommon::filedescription($value);
  460:     }
  461:     # Person
  462:     if (($type eq 'author') || 
  463: 	($type eq 'owner') ||
  464: 	($type eq 'modifyinguser') ||
  465: 	($type eq 'authorspace')) {
  466: 	$value=~s/($match_username)(\:|\@)($match_domain)/&authordisplay($1,$3)/gse;
  467: 	return $value;
  468:     }
  469:     # Gradelevel
  470:     if (($type eq 'lowestgradelevel') ||
  471: 	($type eq 'highestgradelevel')) {
  472: 	return &Apache::loncommon::gradeleveldescription($value);
  473:     }
  474:     # Only for advance users below
  475:     if (! $env{'user.adv'}) { 
  476:         return '<i>- '.&mt('not displayed').' -</i>';
  477:     }
  478:     # File
  479:     if (($type eq 'customdistributionfile') ||
  480: 	($type eq 'obsoletereplacement') ||
  481: 	($type eq 'goto_list') ||
  482: 	($type eq 'comefrom_list') ||
  483: 	($type eq 'sequsage_list') ||
  484: 	($type eq 'dependencies')) {
  485: 	return '<ul class="LC_fontsize_medium">'.join("\n",map {
  486:             my $url = &Apache::lonnet::clutter_with_no_wrapper($_);
  487:             my $title = &Apache::lonnet::gettitle($url);
  488:             if ($title eq '') {
  489:                 $title = 'Untitled';
  490:                 if ($url =~ /\.sequence$/) {
  491:                     $title .= ' Sequence';
  492:                 } elsif ($url =~ /\.page$/) {
  493:                     $title .= ' Page';
  494:                 } elsif ($url =~ /\.problem$/) {
  495:                     $title .= ' Problem';
  496:                 } elsif ($url =~ /\.html$/) {
  497:                     $title .= ' HTML document';
  498:                 } elsif ($url =~ m:/syllabus$:) {
  499:                     $title .= ' Syllabus';
  500:                 } 
  501:             }
  502:             $_ = '<li>'.$title.' '.
  503:                  &Apache::lonhtmlcommon::crumbs($url,$target,$prefix,$form).
  504:                  '</li>'
  505: 	    } split(/\s*\,\s*/,$value)).'</ul>';
  506:     }
  507:     # Evaluations
  508:     if (($type eq 'clear') ||
  509: 	($type eq 'depth') ||
  510: 	($type eq 'helpful') ||
  511: 	($type eq 'correct') ||
  512: 	($type eq 'technical')) {
  513: 	return &evalgraph($value);
  514:     }
  515:     # Difficulty
  516:     if ($type eq 'difficulty' || $type eq 'disc') {
  517: 	return &diffgraph($value);
  518:     }
  519:     # List of courses
  520:     if ($type=~/\_list/) {
  521:         my @Courses = split(/\s*\,\s*/,$value);
  522:         my $Str='<ul class="LC_fontsize_medium">';
  523: 	my %descriptions;
  524:         foreach my $course (@Courses) {
  525:             my %courseinfo =
  526: 		&Apache::lonnet::coursedescription($course,
  527: 						   {'one_time' => 1});
  528:             if (! exists($courseinfo{'num'}) || $courseinfo{'num'} eq '') {
  529:                 next;
  530:             }
  531: 	    $descriptions{join('\0',@courseinfo{'domain','description'})} .= 
  532: 		'<li><a href="/public/'.$courseinfo{'domain'}.'/'.
  533:                 $courseinfo{'num'}.'/syllabus" target="preview">'.
  534:                 $courseinfo{'description'}.' ('.$courseinfo{'domain'}.
  535: 		')</a></li>';
  536:         }
  537: 	foreach my $course (sort {lc($a) cmp lc($b)} (keys(%descriptions))) {
  538: 	    $Str .= $descriptions{$course};
  539: 	}
  540: 
  541: 	return $Str.'</ul>';
  542:     }
  543:     # No pretty print found
  544:     return $value;
  545: }
  546: 
  547: # Pretty input of metadata field
  548: sub direct {
  549:     return shift;
  550: }
  551: 
  552: sub selectbox {
  553:     my ($name,$value,$readonly,$functionref,@idlist)=@_;
  554:     if (! defined($functionref)) {
  555:         $functionref=\&direct;
  556:     }
  557:     my $disabled;
  558:     if ($readonly) {
  559:         $disabled = ' disabled="disabled"';
  560:     }
  561:     my $selout='<select name="'.$name.'">';
  562:     foreach my $id (@idlist) {
  563:         $selout.='<option value="'.$id.'"'.$disabled;
  564:         if ($id eq $value) {
  565: 	    $selout.=' selected="selected">'.&{$functionref}($id).'</option>';
  566:         } else {
  567:             $selout.='>'.&{$functionref}($id).'</option>';
  568:         }
  569:     }
  570:     return $selout.'</select>';
  571: }
  572: 
  573: sub relatedfield {
  574:     my ($show,$relatedsearchflag,$relatedsep,$fieldname,$relatedvalue)=@_;
  575:     if (! $relatedsearchflag) { 
  576:         return '';
  577:     }
  578:     if (! defined($relatedsep)) {
  579:         $relatedsep=' ';
  580:     }
  581:     if (! $show) {
  582:         return $relatedsep.'&nbsp;';
  583:     }
  584:     return $relatedsep.'<input type="checkbox" name="'.$fieldname.'_related"'.
  585: 	($relatedvalue?' checked="checked"':'').' />';
  586: }
  587: 
  588: sub prettyinput {
  589:     my ($type,$value,$readonly,$fieldname,$formname,
  590: 	$relatedsearchflag,$relatedsep,$relatedvalue,$size,$course_key)=@_;
  591:     if (! defined($size)) {
  592:         $size = 80;
  593:     }
  594:     my $output;
  595:     if (defined($course_key) 
  596: 	&& exists($env{$course_key.'.metadata.'.$type.'.options'})) {
  597:         my $stu_add;
  598:         my $only_one;
  599:         my %meta_options;
  600:         my @cur_values_inst;
  601:         my $cur_values_stu;
  602:         my $values = $env{$course_key.'.metadata.'.$type.'.values'};
  603:         if ($env{$course_key.'.metadata.'.$type.'.options'} =~ m/stuadd/) {
  604:             $stu_add = 'true';
  605:         }
  606:         if ($env{$course_key.'.metadata.'.$type.'.options'} =~ m/onlyone/) {
  607:             $only_one = 'true';
  608:         }
  609:         # need to take instructor values out of list where instructor and student
  610:         # values may be mixed.
  611:         if ($values) {
  612:             foreach my $item (split(/,/,$values)) {
  613:                 $item =~ s/^\s+//;
  614:                 $meta_options{$item} = $item;
  615:             }
  616:             foreach my $item (split(/,/,$value)) {
  617:                 $item =~ s/^\s+//;
  618:                 if ($meta_options{$item}) {
  619:                     push(@cur_values_inst,$item);
  620:                 } else {
  621:                     if ($item ne '') {
  622:                         $cur_values_stu .= $item.',';
  623:                     }
  624:                 }
  625:             }
  626:              $cur_values_stu =~ s/,$//;
  627:             my @key_order = sort(keys(%meta_options));
  628:             unshift(@key_order,'');
  629:             $meta_options{''} = 'Not specified';
  630:             $meta_options{'select_form_order'} = \@key_order;
  631:         } else {
  632:             $cur_values_stu = $value;
  633:         }
  634:         if ($type eq 'courserestricted') {
  635:             return (&select_course());
  636:             # return ('<input type="hidden" name="new_courserestricted" value="'.$course_key.'" />');
  637:         }
  638:         if (($type eq 'keywords') || ($type eq 'subject')
  639:              || ($type eq 'author')||($type eq  'notes')
  640:              || ($type eq  'abstract')|| ($type eq  'title')|| ($type eq  'standards')
  641:              || (exists($env{$course_key.'.metadata.'.$type.'.added'}))) {
  642:             
  643:             if ($values) {
  644:                 if ($only_one) {
  645:                     $output .= (&Apache::loncommon::select_form($cur_values_inst[0],'new_'.$type,\%meta_options));
  646:                 } else {
  647:                     $output .= (&Apache::loncommon::multiple_select_form('new_'.$type,\@cur_values_inst,undef,\%meta_options));
  648:                 }
  649:             }
  650:             if ($stu_add) {
  651:                 $output .= '<input type="text" name="'.$fieldname.'" size="'.$size.'" '.
  652:                 'value="'.$cur_values_stu.'" />'.
  653:                 &relatedfield(1,$relatedsearchflag,$relatedsep,$fieldname,
  654:                       $relatedvalue); 
  655:             }
  656:             return ($output);
  657:         } 
  658:         if (($type eq 'lowestgradelevel') ||
  659: 	    ($type eq 'highestgradelevel')) {
  660: 	    return &Apache::loncommon::select_level_form($value,$fieldname).
  661:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  662:         }
  663:         return(); 
  664:     }
  665:     # Language
  666:     if ($type eq 'language') {
  667: 	return &selectbox($fieldname,
  668: 			  $value,'',
  669: 			  \&Apache::loncommon::languagedescription,
  670: 			  (&Apache::loncommon::languageids)).
  671:                               &relatedfield(0,$relatedsearchflag,$relatedsep);
  672:     }
  673:     # Copyright
  674:     if ($type eq 'copyright') {
  675: 	return &selectbox($fieldname,
  676: 			  $value,$readonly,
  677: 			  \&Apache::loncommon::copyrightdescription,
  678: 			  (&Apache::loncommon::copyrightids)).
  679:                               &relatedfield(0,$relatedsearchflag,$relatedsep);
  680:     }
  681:     # Source Copyright
  682:     if ($type eq 'sourceavail') {
  683: 	return &selectbox($fieldname,
  684: 			  $value,'',
  685: 			  \&Apache::loncommon::source_copyrightdescription,
  686: 			  (&Apache::loncommon::source_copyrightids)).
  687:                               &relatedfield(0,$relatedsearchflag,$relatedsep);
  688:     }
  689:     # Gradelevels
  690:     if (($type eq 'lowestgradelevel') ||
  691: 	($type eq 'highestgradelevel')) {
  692: 	return &Apache::loncommon::select_level_form($value,$fieldname).
  693:             &relatedfield(0,$relatedsearchflag,$relatedsep);
  694:     }
  695:     # Obsolete
  696:     if ($type eq 'obsolete') {
  697: 	return '<input type="checkbox" name="'.$fieldname.'"'.
  698: 	    ($value?' checked="checked"':'').' />'.
  699:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  700:     }
  701:     # Obsolete replacement file
  702:     if ($type eq 'obsoletereplacement') {
  703: 	return '<input type="text" name="'.$fieldname.
  704: 	    '" size="60" value="'.$value.'" /><a href="javascript:openbrowser'.
  705: 	    "('".$formname."','".$fieldname."'".
  706: 	    ",'')\">".&mt('Select').'</a>'.
  707:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  708:     }
  709:     # Customdistribution file
  710:     if ($type eq 'customdistributionfile') {
  711:         my $disabled;
  712:         if ($readonly) {
  713:             $disabled = ' disabled="disabled"';
  714:         }
  715:         my $output;
  716: 	$output = '<input type="text" name="'.$fieldname.
  717: 	    '" size="60" value="'.$value.'"'.$disabled.' />';
  718:         unless ($readonly) {
  719:             $output .= '<a href="javascript:openbrowser'.
  720: 	               "('".$formname."','".$fieldname."'".
  721: 	               ",'rights')\">".&mt('Select').'</a>';
  722:         }
  723:         $output .= &relatedfield(0,$relatedsearchflag,$relatedsep);
  724:         return $output;
  725:     }
  726:     # Source Customdistribution file
  727:     if ($type eq 'sourcerights') {
  728: 	return '<input type="text" name="'.$fieldname.
  729: 	    '" size="60" value="'.$value.'" /><a href="javascript:openbrowser'.
  730: 	    "('".$formname."','".$fieldname."'".
  731: 	    ",'rights')\">".&mt('Select').'</a>'.
  732:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  733:     }
  734:     if ($type eq 'courserestricted') {
  735:         return (&select_course());
  736:         #return ('<input type="hidden" name="new_courserestricted" value="'.$course_key.'" />');
  737:     }
  738: 
  739:     # Dates
  740:     if (($type eq 'creationdate') ||
  741: 	($type eq 'lastrevisiondate')) {
  742: 	return 
  743:             &Apache::lonhtmlcommon::date_setter($formname,$fieldname,$value).
  744:             &relatedfield(0,$relatedsearchflag,$relatedsep);
  745:     }
  746:     # No pretty input found
  747:     $value=~s/^\s+//gs;
  748:     $value=~s/\s+$//gs;
  749:     $value=~s/\s+/ /gs;
  750:     $value=~s/\"/\&quot\;/gs;
  751:     return 
  752:         '<input type="text" name="'.$fieldname.'" size="'.$size.'" '.
  753:         'value="'.$value.'" />'.
  754:         &relatedfield(1,$relatedsearchflag,$relatedsep,$fieldname,
  755:                       $relatedvalue); 
  756: }
  757: 
  758: # Create pageheader
  759: sub pageheader {
  760:     my $output = '';
  761:     # No CSTR? Include breadcrumbs
  762:     if ($env{'request.state'} ne 'construct') {
  763:         # loncommon::bodytag already includes breadcrumbs for CSTR
  764:         # by calling lonmenu::innerregister
  765:         $output = &Apache::lonhtmlcommon::breadcrumbs();
  766:     }
  767:     # CSTR? Include CSTR header
  768:     if ($env{'request.state'} eq 'construct') {
  769:           $output .= &Apache::loncommon::head_subbox(
  770:                          &Apache::loncommon::CSTR_pageheader());
  771:     }
  772:     return $output;
  773: }
  774: 
  775: # Main Handler
  776: sub handler {
  777:     my $r=shift;
  778:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  779:          ['currentpath','changecourse','modal']);
  780:     my $uri=$r->uri;
  781:     #
  782:     # Set document type
  783:     &Apache::loncommon::content_type($r,'text/html');
  784:     $r->send_http_header;
  785:     return OK if $r->header_only;
  786:     my ($resdomain,$resuser)=
  787:         (&Apache::lonnet::declutter($uri)=~/^($match_domain)\/($match_username)\//);
  788: 
  789:     # Breadcrumbs
  790:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  791: 
  792:     if ($env{'request.state'} eq 'construct') {
  793:         my $text = 'Authoring Space';
  794:         my $href = &Apache::loncommon::authorspace($uri);
  795:         if ($env{'request.course.id'}) {
  796:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  797:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  798:             if ($href eq "/priv/$cdom/$cnum/") {
  799:                 $text = 'Course Authoring Space';
  800:             }
  801:         }
  802:         &Apache::lonhtmlcommon::add_breadcrumb({
  803:             'text'  => $text,
  804:             'href'  => $href,
  805:         });
  806:     }
  807: 
  808:     if ($uri=~m:/adm/bombs/(.*)$:) {
  809:         &Apache::lonhtmlcommon::add_breadcrumb({
  810:             'text'  => 'Error Messages',
  811:             'href'  => '',
  812:         });
  813:         $r->print(&Apache::loncommon::start_page('Error Messages'));
  814:         $r->print(&pageheader());
  815:         # Looking for all bombs?
  816:         &report_bombs($r,$uri);
  817:     } elsif ($uri=~m|^/editupload/[^/]+/[^/]+/portfolio/|) {
  818:         &Apache::lonhtmlcommon::add_breadcrumb({
  819:             'text'  => 'Edit Portfolio File Metadata',
  820:             'href'  => '',
  821:         });
  822: 	    ($resdomain,$resuser)=
  823: 		(&Apache::lonnet::declutter($uri)=~m|^($match_domain)/($match_name)/portfolio|);
  824:         $r->print(&Apache::loncommon::start_page('Edit Portfolio File Metadata',
  825: 						 undef,
  826: 						 {'domain' => $resdomain,}));
  827:         $r->print(&pageheader());
  828:         if ($env{'form.store'}) {
  829:             &present_editable_metadata($r,$uri,'portfolio');
  830:         } else {
  831:             my $fn=&Apache::lonnet::filelocation('',$uri);
  832:             %Apache::lonpublisher::metadatafields=();
  833:             %Apache::lonpublisher::metadatakeys=();
  834:             my $result=&Apache::lonnet::getfile($fn);
  835:             &Apache::lonpublisher::metaeval($result);
  836:             if ((!$Apache::lonpublisher::metadatafields{'courserestricted'}) ||
  837:                 ($env{'form.changecourse'} eq 'true')) {
  838:                 &pre_select_course($r,$uri);
  839:             } else {
  840:                 &present_editable_metadata($r,$uri,'portfolio');
  841:             }
  842:         }
  843:     } elsif ($uri=~m|^/editupload/[^/]+/[^/]+/groups/|) {
  844:         &Apache::lonhtmlcommon::add_breadcrumb({
  845:             'text'  => 'Edit Group Portfolio File Metadata',
  846:             'href'  => '',
  847:         });
  848:         $r->print(&Apache::loncommon::start_page('Edit Group Portfolio File Metadata',
  849: 						 undef,
  850: 						 {'domain' => $resdomain,}));
  851:         $r->print(&pageheader());
  852:         &present_editable_metadata($r,$uri,'groups');    
  853:     } elsif ($uri=~m|^/priv|) { 
  854:         # Authoring space
  855:         &Apache::lonhtmlcommon::add_breadcrumb({
  856:             'text'  => 'Edit Metadata',
  857:             'href'  => '',
  858:         });
  859:         $r->print(&Apache::loncommon::start_page('Edit Metadata',
  860: 						"\n".'<script type="text/javascript">'."\n".
  861:                                                 &Apache::loncommon::browser_and_searcher_javascript().
  862:                                                 "\n".'</script>',
  863: 						 {'domain' => $resdomain,}));
  864:         $r->print(&pageheader());
  865:         &present_editable_metadata($r,$uri);
  866:     } else {
  867:         &Apache::lonhtmlcommon::add_breadcrumb({
  868:             'text'  => 'Metadata',
  869:             'href'  => '',
  870:         });
  871:         $r->print(
  872:             &Apache::loncommon::start_page(
  873:                 'Metadata',
  874:                 undef,
  875:                 {'domain' => $resdomain,
  876:                 'only_body' => 1,})
  877:            .'<h1>'.&mt('Metadata').'</h1>'
  878:         );
  879:         if ($env{'form.modal'}) {
  880:             my $width = 500;
  881:             my $height = 400;
  882:             my $machine = &Apache::lonnet::absolute_url();
  883:             $r->print(&Apache::loncommon::nicescroll_javascript('metadatawrapper',
  884:                                                                 {cursorcolor => '#00F',
  885:                                                                  railalign => 'right',
  886:                                                                  railoffset => '{top:5,left:40}'},
  887:                                                                  undef,1,$machine.$uri));
  888:             $r->print('<div id="metadatawrapper" style="height:'.$height.'px; width:'.$width.'px; overflow: auto;">');
  889:         }
  890:         &present_uneditable_metadata($r,$uri);
  891:         if ($env{'form.modal'}) {
  892:             $r->print('</div>');
  893:         }
  894:     }
  895:     $r->print(&Apache::loncommon::end_page());
  896:     return OK;
  897: }
  898: 
  899: #####################################################
  900: #####################################################
  901: ###                                               ###
  902: ###                Report Bombs                   ###
  903: ###                                               ###
  904: #####################################################
  905: #####################################################
  906: sub report_bombs {
  907:     my ($r,$uri) = @_;
  908:     # Set document type
  909:     $uri =~ s:/adm/bombs/::;
  910:     $uri = &Apache::lonnet::declutter($uri);
  911:     $r->print(
  912:         '<p>'.&mt('Folder: [_1]',
  913:                   '<span class="LC_filename">'.&Apache::lonnet::clutter($uri).'</span>')
  914:        .'</p>'
  915:     );
  916:     my ($domain,$author)=($uri=~/^($match_domain)\/($match_username)\//);
  917:     if (!&Apache::lonnet::constructaccess('/priv/'.$domain.'/'.$author.'/')) {
  918:         $r->print('<p class="LC_error">'.&mt('Not authorized').'</p>');
  919:         return;
  920:     }
  921: 
  922:     my $showbuttons=1;
  923:     my $message='';
  924:     if ($env{'form.clearbombs'}) {
  925:         my $rc=&Apache::lonmsg::clear_author_res_msg($uri);
  926:         if ($rc eq 'ok') {
  927:                 $message=&Apache::lonhtmlcommon::confirm_success(
  928:                     &mt('Messages cleared.'));
  929:                 $showbuttons=0;
  930:         } else {
  931:                 $message=&Apache::lonhtmlcommon::confirm_success(
  932:                              &mt('Error clearing messages'),1)
  933:                         .'<br />'.&mt('Error: [_1]',$rc);
  934:         }
  935:     }
  936: 
  937:     if ($message) {    
  938:         $message=&Apache::loncommon::confirmwrapper($message);
  939:         $r->print($message);
  940:     }
  941: 
  942:     my $cancelurl=$uri;
  943:     $cancelurl=~s/^\Q$domain\E/\/priv\/$domain/;
  944: 
  945:     if ($showbuttons) {
  946:         $r->print(
  947:             '<form method="post" action="">'.
  948:             '<input type="submit" name="clearbombs" value="'.
  949:                 &mt('Clear all Messages in Subdirectory').'" />'.
  950:             ' <a href="'.$cancelurl.'">'.
  951:                 &mt('Back to Source Directory').'</a>'.
  952:             '</form><hr />'
  953:         );
  954:         # Display all bombs of subdirectory
  955:         my %brokenurls = 
  956:             &Apache::lonmsg::all_url_author_res_msg($author,$domain);
  957:         foreach my $key (sort(keys(%brokenurls))) {
  958:             if ($key=~/^\Q$uri\E/) {
  959:                 $r->print
  960:                     ('<a href="'.&Apache::lonnet::clutter($key).'">'.$key.'</a>'.
  961:                      &Apache::lonmsg::retrieve_author_res_msg($key).
  962:                      '<hr />');
  963:             }
  964:         }
  965:     } else {
  966:             my $functions=&Apache::lonhtmlcommon::start_funclist('Actions');
  967:             $functions.=&Apache::lonhtmlcommon::add_item_funclist(
  968:                             '<a href="'.$cancelurl.'">'.
  969:                             &mt('Back to Source Directory').'</a>');
  970:             $functions .= &Apache::lonhtmlcommon::end_funclist();
  971:             $r->print('<p>'.$functions.'</p>');
  972:     }
  973:     return;
  974: }
  975: 
  976: #####################################################
  977: #####################################################
  978: ###                                               ###
  979: ###        Uneditable Metadata Display            ###
  980: ###                                               ###
  981: #####################################################
  982: #####################################################
  983: sub present_uneditable_metadata {
  984:     my ($r,$uri) = @_;
  985:     #
  986:     my $uploaded = ($uri =~ m|/uploaded/|);
  987:     my %content=();
  988:     # Read file
  989:     foreach my $key (split(/\,/,&Apache::lonnet::metadata($uri,'keys'))) {
  990:         $content{$key}=&Apache::lonnet::metadata($uri,$key);
  991:     }
  992:     # Render Output
  993:     # displayed url
  994:     my ($thisversion)=($uri=~/\.(\d+)\.(\w+)\.meta$/);
  995:     $uri=~s/\.meta$//;
  996:     my $disuri=&Apache::lonnet::clutter_with_no_wrapper($uri);
  997:     # version
  998:     my $versiondisplay='';
  999:     if (!$uploaded) {
 1000: 	my $currentversion=&Apache::lonnet::getversion($disuri);
 1001: 	if ($thisversion) {
 1002: 	    $versiondisplay=&mt('Version').': '.$thisversion.
 1003: 		' ('.&mt('most recent version').': '.
 1004: 		($currentversion>0 ? 
 1005: 		 $currentversion   :
 1006: 		 &mt('information not available')).')';
 1007: 	} else {
 1008: 	    $versiondisplay=&mt('Version: [_1]',$currentversion);
 1009: 	}
 1010:     }
 1011:     # crumbify displayed URL               uri     target prefix form 
 1012:     $disuri=&Apache::lonhtmlcommon::crumbs($disuri,undef, undef, undef);
 1013:     # obsolete
 1014:     my $obsolete=$content{'obsolete'};
 1015:     my $obsoletewarning='';
 1016:     if (($obsolete) && ($env{'user.adv'})) {
 1017:         $obsoletewarning='<p><span class="LC_warning">'.
 1018:             &mt('This resource has been marked obsolete by the author(s)').
 1019:             '</span></p>';
 1020:     }
 1021:     #
 1022:     my %lt=&fieldnames();
 1023:     my $table='';
 1024:     my $title = $content{'title'};
 1025:     if (! defined($title)) {
 1026:         $title = &mt('Untitled Resource');
 1027:     }
 1028:     my @fields;
 1029:     if ($uploaded) {
 1030: 	@fields = ('title','author','subject','keywords','notes','abstract',
 1031: 		   'lowestgradelevel','highestgradelevel','standards','mime',
 1032: 		   'owner');
 1033:     } else {
 1034: 	@fields = ('title', 
 1035: 		   'author', 
 1036: 		   'subject', 
 1037: 		   'keywords', 
 1038: 		   'notes', 
 1039: 		   'abstract',
 1040: 		   'lowestgradelevel',
 1041: 		   'highestgradelevel',
 1042: 		   'standards', 
 1043: 		   'mime', 
 1044: 		   'language', 
 1045: 		   'creationdate', 
 1046: 		   'lastrevisiondate', 
 1047: 		   'owner', 
 1048: 		   'copyright', 
 1049: 		   'customdistributionfile',
 1050: 		   'sourceavail',
 1051: 		   'sourcerights', 
 1052: 		   'obsolete', 
 1053: 		   'obsoletereplacement');
 1054:     }
 1055:     my $rownum = 0;
 1056:     foreach my $field (@fields) {
 1057:         my $lastrow = '';
 1058:         $rownum ++;
 1059:         $lastrow = 1 if ($rownum == @fields); 
 1060:         $table.=&Apache::lonhtmlcommon::row_title($lt{$field})
 1061:                .&prettyprint($field,$content{$field})
 1062:                .&Apache::lonhtmlcommon::row_closure($lastrow);
 1063:         delete($content{$field});
 1064:     }
 1065:     #
 1066:     $r->print("<h2>$title</h2>"
 1067:              .'<p>'
 1068:              .$disuri.'<br />'
 1069:              .$obsoletewarning
 1070:              .$versiondisplay
 1071:              .'</p>'
 1072:              .&Apache::lonhtmlcommon::start_pick_box()
 1073:              .$table
 1074:              .&Apache::lonhtmlcommon::end_pick_box()
 1075:     );
 1076:     if (!$uploaded && $env{'user.adv'}) {
 1077:         &print_dynamic_metadata($r,$uri,\%content);
 1078:     }
 1079:     return;
 1080: }
 1081: 
 1082: sub print_dynamic_metadata {
 1083:     my ($r,$uri,$content) = @_;
 1084:     #
 1085:     my %content = %$content;
 1086:     my %lt=&fieldnames();
 1087:     #
 1088:     my $description = 'Dynamic Metadata (updated periodically)';
 1089:     $r->print('<h3>'.&mt($description).'</h3>'.
 1090:               &mt('Processing'));
 1091:     $r->rflush();
 1092:     my %items=&fieldnames();
 1093:     my %dynmeta=&dynamicmeta($uri);
 1094:     #
 1095:     # General Access and Usage Statistics
 1096:     $r->print('<h4>'.&mt('Access and Usage Statistics').'</h4>');
 1097:     if (exists($dynmeta{'count'}) ||
 1098:         exists($dynmeta{'sequsage'}) ||
 1099:         exists($dynmeta{'comefrom'}) ||
 1100:         exists($dynmeta{'goto'}) ||
 1101:         exists($dynmeta{'course'})) {
 1102:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1103:         my @counts = ('count','sequsage','sequsage_list',
 1104:                       'comefrom','comefrom_list','goto',
 1105:                       'goto_list','course','course_list');
 1106:         my $rownum = 0;
 1107:         foreach my $item (@counts) {
 1108:             my $lastrow = '';
 1109:             $rownum ++;
 1110:             $lastrow = 1 if ($rownum == @counts);
 1111:             $r->print(&Apache::lonhtmlcommon::row_title($lt{$item})
 1112:                      .&prettyprint($item,$dynmeta{$item})
 1113:                      .&Apache::lonhtmlcommon::row_closure($lastrow)
 1114:             );
 1115:         }
 1116:         $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1117:     } else {
 1118:         $r->print('<p>'
 1119:                  .&mt('No Access or Usages Statistics are available for this resource.')
 1120:                  .'</p>'
 1121:         );
 1122:     }
 1123:     #
 1124:     # Assessment statistics
 1125:     if ($uri=~/$LONCAPA::assess_re/) {
 1126:         if (exists($dynmeta{'stdno'}) ||
 1127:             exists($dynmeta{'avetries'}) ||
 1128:             exists($dynmeta{'difficulty'}) ||
 1129:             exists($dynmeta{'disc'})) {
 1130:             # This is an assessment, print assessment data
 1131:             $r->print('<h4>'.
 1132:                       &mt('Overall Assessment Statistical Data').
 1133:                       '</h4>'.
 1134:                       &Apache::lonhtmlcommon::start_pick_box());
 1135:             $r->print(&Apache::lonhtmlcommon::row_title($lt{'stdno'})
 1136:                      .&prettyprint('stdno',$dynmeta{'stdno'})
 1137:                      .&Apache::lonhtmlcommon::row_closure()
 1138:             );
 1139:             my @stats = ('avetries','difficulty','disc');
 1140:             my $rownum = 0;
 1141:             foreach my $item (@stats) {
 1142:                 my $lastrow = '';
 1143:                 $rownum ++;
 1144:                 $lastrow = 1 if ($rownum == @stats);
 1145:                 $r->print(&Apache::lonhtmlcommon::row_title($lt{$item})
 1146:                          .&prettyprint($item,sprintf('%5.2f',$dynmeta{$item}))
 1147:                          .&Apache::lonhtmlcommon::row_closure($lastrow)
 1148:                 );
 1149:             }
 1150:             $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1151:         }
 1152:         #
 1153:         # New assessment statistics
 1154:         $r->print('<h4>'
 1155:                  .&mt('Recent Detailed Assessment Statistical Data')
 1156:                  .'</h4>'
 1157:         );
 1158:         if (exists($dynmeta{'stats'})) {
 1159:             my $table=&Apache::loncommon::start_data_table()
 1160:                      .&Apache::loncommon::start_data_table_header_row()
 1161: 		     .'<th>'.&mt('Domain').'</th>'
 1162:                      .'<th>'.&mt('Course').'</th>'
 1163:                      .'<th>'.&mt('Section(s)').'</th>'
 1164:                      .'<th>'.&mt('Num Students').'</th>'
 1165:                      .'<th>'.&mt('Part').'</th>'
 1166:                      .'<th>'.&mt('Mean Tries').'</th>'
 1167:                      .'<th>'.&mt('Degree of Difficulty').'</th>'
 1168:                      .'<th>'.&mt('Degree of Discrimination').'</th>'
 1169:                      .'<th>'.&mt('Time of computation').'</th>'
 1170:                      .&Apache::loncommon::end_data_table_header_row().$/;
 1171:             foreach my $identifier (sort(keys(%{$dynmeta{'stats'}}))) {
 1172:                 my $data = $dynmeta{'stats'}->{$identifier};
 1173:                 my $course = $data->{'course'};
 1174:                 my %courseinfo = 
 1175: 		    &Apache::lonnet::coursedescription($course,
 1176: 						       {'one_time' => 1});
 1177:                 if (! exists($courseinfo{'num'}) || $courseinfo{'num'} eq '') {
 1178:                     &Apache::lonnet::logthis('lookup for '.$course.' failed');
 1179:                     next;
 1180:                 }
 1181:                 $table .= &Apache::loncommon::start_data_table_row();
 1182: 		$table .=
 1183: 		    '<td><span class="LC_nobreak">'.$courseinfo{'domain'}.'</span></td>';
 1184:                 $table .= 
 1185:                     '<td><span class="LC_nobreak">'.$courseinfo{'description'}.'</span></td>';
 1186:                 $table .= 
 1187:                     '<td align="right">'.$data->{'sections'}.'</td>';
 1188:                 $table .=
 1189:                     '<td align="right">'.$data->{'stdno'}.'</td>';
 1190:                 $table .=
 1191:                     '<td align="right">'.$data->{'part'}.'</td>';
 1192:                 foreach my $item ('avetries','difficulty','disc') {
 1193:                     $table .= '<td align="right">';
 1194:                     if (exists($data->{$item})) {
 1195:                         $table .= sprintf('%.2f',$data->{$item}).'&nbsp;';
 1196:                     } else {
 1197:                         $table .= '';
 1198:                     }
 1199:                     $table .= '</td>';
 1200:                 }
 1201:                 $table .=
 1202:                     '<td><span class="LC_nobreak">'.
 1203:                     &Apache::lonlocal::locallocaltime($data->{'timestamp'}).
 1204:                     '</span></td>';
 1205:                 $table .= &Apache::loncommon::end_data_table_row().$/;
 1206:             }
 1207:             $table .= &Apache::loncommon::end_data_table().$/;
 1208:             $r->print($table);
 1209:         } else {
 1210:             $r->print('<p>'
 1211:                      .&mt('No new dynamic data found.')
 1212:                      .'</p>'
 1213:             );
 1214:         }
 1215:     } else {
 1216:         $r->print('<h4>'.
 1217:           &mt('No Assessment Statistical Data is available for this resource').
 1218:                   '</h4>');
 1219:     }
 1220:     #
 1221:     # Evaluation Data
 1222:     $r->print('<h4>'.&mt('Evaluation Data').'</h4>');
 1223:     if (exists($dynmeta{'clear'})   || 
 1224:         exists($dynmeta{'depth'})   || 
 1225:         exists($dynmeta{'helpful'}) || 
 1226:         exists($dynmeta{'correct'}) || 
 1227:         exists($dynmeta{'technical'})){ 
 1228:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1229:         my @criteria = ('clear','depth','helpful','correct','technical');
 1230:         my $rownum = 0;
 1231:         foreach my $item (@criteria) {
 1232:             my $lastrow = '';
 1233:             $rownum ++;
 1234:             $lastrow = 1 if ($rownum == @criteria);
 1235:             $r->print(&Apache::lonhtmlcommon::row_title($lt{$item})
 1236:                      .&prettyprint($item,$dynmeta{$item})
 1237:                      .&Apache::lonhtmlcommon::row_closure($lastrow)
 1238:             );
 1239:         }
 1240:         $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1241:     } else {
 1242:         $r->print('<p>'
 1243:                  .&mt('No Evaluation Data is available for this resource.')
 1244:                  .'</p>'
 1245:         );
 1246:     }
 1247:     # Evaluation Comments
 1248:     $uri=~/^\/res\/($match_domain)\/($match_username)\//; 
 1249:     if ((($env{'user.domain'} eq $1) && ($env{'user.name'} eq $2))
 1250:         || ($env{'user.role.ca./'.$1.'/'.$2})) {
 1251:         $r->print('<h4>'.&mt('Evaluation Comments').'</h4>'
 1252:                  .'<div>('
 1253:                  .&mt('visible to author and co-authors only')
 1254:                  .')</div>'
 1255:         );
 1256:         if (exists($dynmeta{'comments'})) {
 1257:             $r->print('<blockquote>'.$dynmeta{'comments'}.'</blockquote>');
 1258:         } else {
 1259:             $r->print('<p>'
 1260:                      .&mt('There are no Evaluation Comments on this resource.')
 1261:                      .'</p>'
 1262:             );
 1263:         }
 1264:         my $bombs = &Apache::lonmsg::retrieve_author_res_msg($uri);
 1265:         if (defined($bombs) && $bombs ne '') {
 1266:             $r->print('<a name="bombs" />'
 1267:                      .'<h4 class="LC_warning">'.&mt('Error Messages').'</h4>'
 1268:                      .'<div>('
 1269:                      .&mt('visible to author and co-authors only')
 1270:                      .')</div>'
 1271:                      .$bombs
 1272:             );
 1273:         } #else {
 1274:         #    $r->print('<h4>'.&mt('There are currently no Error Messages for this resource.').'</h4>');
 1275:         #}
 1276:     }
 1277:     #
 1278:     # All other stuff
 1279:     $r->print('<h3>'.
 1280:               &mt('Additional Metadata (non-standard, parameters, exports)').
 1281:               '</h3>');
 1282:     $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1283:     my @names;
 1284:     foreach my $key (sort(keys(%content))) {
 1285:         if ($key!~/\.display$/) {
 1286:             push(@names,$key);
 1287:         }
 1288:     }
 1289:     if (@names > 0) {
 1290:         my $rownum = 0;
 1291:         foreach my $name (@names) {
 1292:             my $lastrow = '';
 1293:             $rownum ++;
 1294:             $lastrow = 1 if ($rownum == @names);
 1295: 
 1296:             my $display=&Apache::lonnet::metadata($uri,
 1297:                                                   $name.'.display');
 1298:             if (! $display) { 
 1299:                 $display=$name;
 1300:             };
 1301:             my $otherinfo='';
 1302:             foreach my $item ('name','part','type','default') {
 1303:                 if (defined(&Apache::lonnet::metadata($uri,
 1304:                                                       $name.'.'.$item))) {
 1305:                     $otherinfo.=' '.$item.'='.
 1306:                         &Apache::lonnet::metadata($uri,
 1307:                                                   $name.'.'.$item).'; ';
 1308:                 }
 1309:             }
 1310:             $r->print(&Apache::lonhtmlcommon::row_title($display)
 1311:                      .$content{$name}
 1312:             );
 1313:             if ($otherinfo) {
 1314:                 $r->print(' ('.$otherinfo.')');
 1315:             }
 1316:             $r->print(&Apache::lonhtmlcommon::row_closure($lastrow));
 1317:         }
 1318:     }
 1319:     $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1320:     return;
 1321: }
 1322: 
 1323: 
 1324: 
 1325: #####################################################
 1326: #####################################################
 1327: ###                                               ###
 1328: ###          Editable metadata display            ###
 1329: ###                                               ###
 1330: #####################################################
 1331: #####################################################
 1332: sub present_editable_metadata {
 1333:     my ($r,$uri,$file_type) = @_;
 1334:     # Authoring Space Call
 1335:     # Header
 1336:     my $disuri=$uri;
 1337:     my ($courseauthor,$crsaurights,$readonly);
 1338:     if ($env{'request.course.id'}) {
 1339:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1340:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1341:         if ($uri =~ m{^\Q/priv/$cdom/$cnum/\E}) {
 1342:             $courseauthor = $cnum.':'.$cdom;
 1343:             $crsaurights = "/res/$cdom/$cnum/default.rights";
 1344:             $readonly = 1;
 1345:         }
 1346:     }
 1347:     my $fn=&Apache::lonnet::filelocation('',$uri);
 1348:     $disuri=~s{^/\~}{/priv/};
 1349:     $disuri=~s/\.meta$//;
 1350:     my $meta_uri = $disuri;
 1351:     my $path;
 1352:     if ($disuri =~ m|/portfolio/|) {
 1353: 	($disuri, $meta_uri, $path) =  &portfolio_display_uri($disuri,1);
 1354:     }
 1355:     my $target=$uri;
 1356:     $target=~s{^/\~}{/res/$env{'request.role.domain'}/};
 1357:     $target=~s/\.meta$//;
 1358:     my $bombs=&Apache::lonmsg::retrieve_author_res_msg($target);
 1359:     if ($bombs) {
 1360:         # Display Bombs, not Metadata
 1361:         $r->print(
 1362:             '<h2>'.&mt('Error Messages').'</h2>'
 1363:            .'<p>'.&mt('Folder: [_1]',
 1364:                       '<span class="LC_filename">'.$disuri.'</span>')
 1365:            .'</p>'
 1366:         );
 1367:         my $showbuttons=1;
 1368:         my $message='';
 1369:         my $rc='';
 1370:         if ($env{'form.delmsg'}) {
 1371:             $rc=&Apache::lonmsg::del_url_author_res_msg($target);
 1372:             if ($rc eq 'ok') {
 1373:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1374:                              &mt('Messages deleted.'));
 1375: 		$showbuttons=0;
 1376:             } else {
 1377:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1378:                              &mt('Error deleting messages'), 1)
 1379:                         .'<br />'.&mt('Error: [_1]',$rc);
 1380:             }
 1381:         }
 1382:         if ($env{'form.clearmsg'}) {
 1383: 	    my $cleardir=$target;
 1384: 	    $cleardir=~s/\/[^\/]+$/\//; # Extract dir: keep path, remove filename
 1385:             $rc=&Apache::lonmsg::clear_author_res_msg($cleardir);
 1386:             if ($rc eq 'ok') {
 1387:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1388:                     &mt('Messages cleared.'));
 1389: 		$showbuttons=0;
 1390:             } else {
 1391:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1392:                              &mt('Error clearing messages'),1)
 1393:                         .'<br />'.&mt('Error: [_1]',$rc);
 1394:             }
 1395:         }
 1396:         if ($message) {
 1397:             $message=&Apache::loncommon::confirmwrapper($message);
 1398:             $r->print($message);
 1399:         }
 1400: 
 1401:         $r->print('<form method="post" action="" name="defaultmeta">');
 1402:         if ($showbuttons) {
 1403:             $r->print(
 1404:                 '<input type="submit" name="delmsg" value="'.
 1405:                 &mt('Delete Messages for this Resource').'" />'.
 1406:                 '<input type="submit" name="clearmsg" value="'.
 1407:                 &mt('Clear all Messages in Subdirectory').'" />'
 1408:                .'<br />'.$bombs
 1409:             );
 1410:         } else {
 1411:             my $functions=&Apache::lonhtmlcommon::start_funclist('Actions');
 1412:             $functions.=&Apache::lonhtmlcommon::add_item_funclist(
 1413:                             '<a href="'.$disuri.'">'.
 1414:                             &mt('Back to Source File').'</a>');
 1415:             my ($diruri) = ($disuri =~ m{(.*/)[^/]*});
 1416:             $functions.=&Apache::lonhtmlcommon::add_item_funclist(
 1417:                             '<a href="'.$diruri.'">'.
 1418:                             &mt('Back to Source Directory').'</a>');
 1419:             $functions .= &Apache::lonhtmlcommon::end_funclist();
 1420:             $r->print('<p>'.$functions.'</p>');
 1421:         }
 1422:     } else {
 1423: 
 1424:         # Display Metadata, not Bombs
 1425:         my $displayfile =
 1426:             &mt('Metadata for [_1]'
 1427:                ,'<span class="LC_filename">'.$disuri.'</span>');
 1428:         if ($disuri=~/\/default$/) {
 1429:             my $dir=$disuri;
 1430:             $dir=~s/default$//;
 1431:             $displayfile=&mt('Default Metadata for Directory [_1]'
 1432:                             ,'<span class="LC_filename">'.$dir.'</span>');
 1433:         }
 1434:         %Apache::lonpublisher::metadatafields=();
 1435:         %Apache::lonpublisher::metadatakeys=();
 1436:         my $result=&Apache::lonnet::getfile($fn);
 1437:         if ($result == -1){
 1438:             my $message = &Apache::lonhtmlcommon::confirm_success(
 1439:                 &mt('Creating new file [_1]'
 1440:                    ,'<span class="LC_filename"'.$meta_uri.'</span>'));
 1441:             $message = &Apache::loncommon::confirmwrapper($message);
 1442:             $r->print($message);
 1443:         } else {
 1444:             &Apache::lonpublisher::metaeval($result);
 1445:         }
 1446:         if ($env{'form.new_courserestricted'}) {
 1447:             my $new_assoc_course = $env{'form.new_courserestricted'};
 1448:             my $prev_courserestricted = $Apache::lonpublisher::metadatafields{'courserestricted'};
 1449:             if (($prev_courserestricted) && 
 1450:                 ($prev_courserestricted ne $new_assoc_course)) {
 1451:                 my $transfers = [];
 1452:                 foreach my $key (keys(%env)) {
 1453:                     if ($key =~ /^form\.transfer_(.+)$/) {
 1454:                         push(@{$transfers},$1);
 1455:                     }
 1456:                 }
 1457:                 if (@{$transfers} > 0) {
 1458:                     &store_transferred_addedfields($fn,$uri,$transfers);
 1459:                 }
 1460:             }
 1461:         }
 1462:         $r->print(<<ENDEDIT);
 1463: <h2>$displayfile</h2>
 1464: <form method="post" action="" name="defaultmeta">
 1465: ENDEDIT
 1466:         my %lt=&fieldnames($file_type);
 1467: 	my $output;
 1468: 	my @fields;
 1469: 	my $added_metadata_fields;
 1470: 	my @added_order;
 1471:         if ($file_type eq 'groups') {
 1472:             $Apache::lonpublisher::metadatafields{'courserestricted'}=
 1473:                 'course.'.$env{'request.course.id'};
 1474:         }
 1475:         if ((! $Apache::lonpublisher::metadatafields{'courserestricted'}) &&
 1476:                 (! $env{'form.new_courserestricted'}) && (! $file_type eq 'groups')) {
 1477:             $Apache::lonpublisher::metadatafields{'courserestricted'}=
 1478:                 'none';
 1479:         } elsif ($env{'form.new_courserestricted'}) {
 1480:             $Apache::lonpublisher::metadatafields{'courserestricted'}=
 1481:                 $env{'form.new_courserestricted'};
 1482:         }
 1483: 	if ($file_type eq 'portfolio' || $file_type eq 'groups') {
 1484: 	    if(exists ($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.fieldlist'})) {
 1485: 	        # retrieve fieldnames (in order) from the course restricted list
 1486: 	        @fields = (split(/,/,$env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.fieldlist'}));
 1487: 	    } else {
 1488: 	        # no saved field list, use default list
 1489: 	        @fields =  ('title','author','subject','keywords','abstract',
 1490: 			    'notes','lowestgradelevel',
 1491: 	                    'highestgradelevel','standards');
 1492:                 if ($Apache::lonpublisher::metadatafields{'courserestricted'} =~ /^course\.($match_domain\_$match_courseid)$/) {
 1493:                     my $assoc_crs = $1;
 1494: 	            $added_metadata_fields = &Apache::lonparmset::get_added_meta_fieldnames($assoc_crs);
 1495: 	            if ($env{'course.'.$assoc_crs.'.metadata.addedorder'}) {
 1496: 	                @added_order = split(/,/,$env{'course.'.$assoc_crs.'.metadata.addedorder'});
 1497: 	            }
 1498: 	            $env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.fieldlist'} = join(",",@fields);
 1499:                 }
 1500: 	    }
 1501: 	} else {
 1502: 	    @fields = ('title','author','subject','keywords','abstract','notes',
 1503: 		       'copyright','customdistributionfile','language',
 1504: 		       'standards',
 1505: 		       'lowestgradelevel','highestgradelevel','sourceavail','sourcerights',
 1506: 		       'obsolete','obsoletereplacement');
 1507:         }
 1508:         if ($courseauthor) {
 1509:             $Apache::lonpublisher::metadatafields{'copyright'}='custom';
 1510:             $Apache::lonpublisher::metadatafields{'customdistributionfile'}=$crsaurights;
 1511:         }
 1512:         my (%domdefs,$got_domdefs);
 1513:         if (! $Apache::lonpublisher::metadatafields{'copyright'}) {
 1514:             my $copyright = 'default';
 1515:             if ($env{'environment.copyright'} ne '') {
 1516:                 $copyright = $env{'environment.copyright'};
 1517:             } else {
 1518:                 my $defdom = $env{'request.role.domain'};
 1519:                 if ($disuri =~ m{^/priv/($match_domain)/}) {
 1520:                     $defdom = $1;
 1521:                 }
 1522:                 if ($defdom ne '') {
 1523:                     %domdefs = &Apache::lonnet::get_domain_defaults($defdom);
 1524:                     $got_domdefs = 1;
 1525:                     if ($domdefs{'copyright'} ne '') {
 1526:                         $copyright = $domdefs{'copyright'};
 1527:                     }
 1528:                 }
 1529:             }
 1530:             $Apache::lonpublisher::metadatafields{'copyright'}=
 1531: 		$copyright;
 1532:         }
 1533:         if (! $Apache::lonpublisher::metadatafields{'sourceavail'}) {
 1534:             my $sourceavail = 'closed';
 1535:             if ($env{'environment.sourceavail'} ne '') {
 1536:                 $sourceavail = $env{'environment.sourceavail'};
 1537:             } else {
 1538:                 my $defdom = $env{'request.role.domain'};
 1539:                 if ($disuri =~ m{^/priv/($match_domain)/}) {
 1540:                     $defdom = $1;
 1541:                 }
 1542:                 if ($defdom ne '') {
 1543:                     unless ($got_domdefs) {
 1544:                         %domdefs = &Apache::lonnet::get_domain_defaults($defdom);
 1545:                         $got_domdefs = 1;
 1546:                     }
 1547:                     if ($domdefs{'sourceavail'} ne '') {
 1548:                         $sourceavail = $domdefs{'sourceavail'};
 1549:                     }
 1550:                 }
 1551:             }
 1552:             $Apache::lonpublisher::metadatafields{'sourceavail'}=
 1553:                 $sourceavail;
 1554:         }
 1555: 	if (($file_type eq 'portfolio') || ($file_type eq 'groups'))  {
 1556: 	    if (! $Apache::lonpublisher::metadatafields{'mime'}) {
 1557:                 ($Apache::lonpublisher::metadatafields{'mime'}) =
 1558: 		    ( $target=~/\.(\w+)$/ );
 1559: 	    }
 1560: 	    if (! $Apache::lonpublisher::metadatafields{'owner'}) {
 1561: 		$Apache::lonpublisher::metadatafields{'owner'} =
 1562: 		    $env{'user.name'}.':'.$env{'user.domain'};
 1563: 	    }
 1564: 	    if (! $Apache::lonpublisher::metadatafields{'author'}) {
 1565: 		$Apache::lonpublisher::metadatafields{'author'} =
 1566: 		    &Apache::loncommon::plainname($env{'user.name'},
 1567: 						  $env{'user.domain'});
 1568: 	    }
 1569: 	    if ($Apache::lonpublisher::metadatafields{'courserestricted'} ne 'none') {
 1570: 
 1571:                 if ($file_type eq 'portfolio') {
 1572:                     $r->print(
 1573:                         &mt('Associated with course [_1]'
 1574:                            ,'<strong>'
 1575:                            .$env{$Apache::lonpublisher::metadatafields{'courserestricted'}
 1576:                            .".description"}.'</strong>')
 1577:                        .' <a href="'.$uri.'?changecourse=true">'
 1578:                        .&mt('Change')
 1579:                        .'</a>'.'<br />'
 1580:                     );
 1581: 
 1582:                 } else {
 1583:                     $r->print(&mt('Associated with course [_1]',
 1584:                         '<strong>'.
 1585:   $env{$Apache::lonpublisher::metadatafields{'courserestricted'}.
 1586:                         ".description"}.'</strong>').'<br />');
 1587:                 }
 1588:             } else {
 1589:                 $r->print(
 1590:                     &mt('This resource is not associated with a course.')
 1591:                   .' <a href="'.$uri.'?changecourse=true">'.&mt('Change').'</a><br />'
 1592:                 );
 1593:             }
 1594:         }
 1595: 	if (@added_order) {
 1596: 	    foreach my $field_name (@added_order) {
 1597:                 push(@fields,$field_name);
 1598:                 $lt{$field_name} = $$added_metadata_fields{$field_name};
 1599: 	    }
 1600: 	} else {
 1601:             foreach my $field_name (keys(%$added_metadata_fields)) {
 1602:                 push(@fields,$field_name);
 1603:                 $lt{$field_name} = $$added_metadata_fields{$field_name};
 1604:             }
 1605:         }
 1606:         $output .= &Apache::lonhtmlcommon::start_pick_box();
 1607:         my $last = $#fields + 1;
 1608:         my $rowcount = 0;
 1609:         foreach my $field_name (@fields) {
 1610:             $rowcount++;
 1611:             if (defined($env{'form.new_'.$field_name})) {
 1612:                 my @values = &Apache::loncommon::get_env_multiple('form.new_'.$field_name);
 1613:                 my $newvalue = '';
 1614:                 foreach my $item (@values) {
 1615:                     if ($item ne '') {
 1616:                         $newvalue .= $item.',';
 1617:                     }
 1618:                 }
 1619:                 $newvalue =~ s/,$//; 
 1620:                 $Apache::lonpublisher::metadatafields{$field_name}=$newvalue;
 1621:             }
 1622:             if ($Apache::lonpublisher::metadatafields{'courserestricted'} ne 'none'
 1623: 		&& exists($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'})) {
 1624:                 # handle restrictions here
 1625:                 if ((($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'} =~ m/active/) ||
 1626:                     ($field_name eq 'courserestricted'))&&
 1627:                     (!($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'} =~ m/deleted/))){
 1628:                     
 1629:                     $output .= &Apache::lonhtmlcommon::row_title($lt{$field_name})
 1630:                               .&prettyinput($field_name,
 1631: 				   $Apache::lonpublisher::metadatafields{$field_name},
 1632: 				                    $readonly,'new_'.$field_name,'defaultmeta',
 1633: 				                    undef,undef,undef,undef,
 1634:                                                     $Apache::lonpublisher::metadatafields{'courserestricted'});
 1635:                     $output .= &Apache::lonhtmlcommon::row_closure($rowcount == $last?1:0);
 1636:                  }
 1637:             } else {
 1638:                     $output .= &Apache::lonhtmlcommon::row_title($lt{$field_name})
 1639:                               .&prettyinput($field_name,
 1640: 					   $Apache::lonpublisher::metadatafields{$field_name},
 1641:                                            $readonly,'new_'.$field_name,'defaultmeta')
 1642:                               .&Apache::lonhtmlcommon::row_closure($rowcount == $last?1:0);
 1643:                
 1644:             }
 1645:         }
 1646:         $output .= &Apache::lonhtmlcommon::end_pick_box();
 1647: 	if ($env{'form.store'}) {
 1648:             my ($outcome,$result) = &store_metadata($fn,$uri,'store');
 1649:             $r->print($result);
 1650: 	}
 1651:         my $savebutton = '<p><input type="submit" name="store"'
 1652:                         .' value="'.&mt('Save').'" title="'.&mt('Save Metadata').'" /></p>';
 1653:         $r->print($savebutton.$output.$savebutton);
 1654: 
 1655: 	if ($file_type eq 'portfolio' || $file_type eq 'groups') {
 1656: 	    my ($port_path,$group) = &get_port_path_and_group($uri);
 1657:             if ($group ne '') {
 1658:                 $r->print('<input type="hidden" name="group" value="'.$group.'" />');
 1659:             }
 1660:             $r->print('<input type="hidden" name="currentpath" value="'.$env{'form.currentpath'}.'" />');
 1661: 	    $r->print('</form><br /><br /><form method="post" action="'.$port_path.'">');
 1662: 	    if ($group ne '') {
 1663: 	        $r->print('<input type="hidden" name="group" value="'.$group.'" />');
 1664:             }
 1665: 	    $r->print('<input type="hidden" name="currentpath" value="'.$path.'" />'.
 1666: 		      '<input type="submit" name="cancel" value="'.&mt('Discard Edits and Return to Portfolio').'" />');
 1667: 	}
 1668:     }
 1669:     
 1670:     $r->print('</form>');
 1671: 
 1672:     return;
 1673: }
 1674: 
 1675: sub store_metadata {
 1676:     my ($fn,$uri,$caller) = @_;
 1677:     my $mfh;
 1678:     my $formname='store';
 1679:     my ($file_content,$output,$outcome);
 1680:     if (&Apache::loncommon::get_env_multiple('form.new_keywords')) {
 1681:         $Apache::lonpublisher::metadatafields{'keywords'} =
 1682:             join (',', &Apache::loncommon::get_env_multiple('form.new_keywords'));
 1683:             }
 1684:     if (($caller eq 'store') && ($env{'request.course.id'})) {
 1685:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1686:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1687:         if ($uri =~ m{^\Q/priv/$cdom/$cnum/\E}) {
 1688:             unless ($uri eq "/priv/$cdom/$cnum/default.rights.meta") {
 1689:                 $Apache::lonpublisher::metadatafields{'copyright'} = 'custom';
 1690:                 $Apache::lonpublisher::metadatafields{'customdistributionfile'} =
 1691:                     "/res/$cdom/$cnum/default.rights";
 1692:             }
 1693:         }
 1694:     }
 1695:     foreach my $field (sort(keys(%Apache::lonpublisher::metadatafields))) {
 1696:         next if ($field =~ /\./);
 1697:         my $unikey=$field;
 1698:         $unikey=~/^([A-Za-z_]+)/;
 1699:         my $tag=$1;
 1700:         $tag=~tr/A-Z/a-z/;
 1701:         $file_content.= "\n\<$tag";
 1702:         foreach my $key (split(/\,/,$Apache::lonpublisher::metadatakeys{$unikey})) {
 1703:             my $value = $Apache::lonpublisher::metadatafields{$unikey.'.'.$key};
 1704:             $value=~s/\"/\'\'/g;
 1705:             $file_content.=' '.$key.'="'.$value.'"' ;
 1706:         }
 1707:         $file_content.= '>'.
 1708:             &HTML::Entities::encode
 1709:                 ($Apache::lonpublisher::metadatafields{$unikey},'<>&"').
 1710:                 '</'.$tag.'>';
 1711:     }
 1712:     if ($fn =~ m|^$Apache::lonnet::perlvar{'lonDocRoot'}/userfiles|) {
 1713:         my ($path, $new_fn);
 1714:         if ($fn =~ m|$match_name/groups/\w+/portfolio/|) {
 1715:             ($path, $new_fn) = ($fn =~ m|/(groups/\w+/portfolio.*)/([^/]*)$|);
 1716:         } else {
 1717:             ($path, $new_fn) = ($fn =~ m|/(portfolio.*)/([^/]*)$|);
 1718:         }
 1719:         ($outcome,my $result) = 
 1720:             &store_portfolio_metadata($formname,$file_content,
 1721:                                       $path,$new_fn,$uri,$caller);
 1722:         $output .= $result;
 1723:     } else {
 1724:         if (! ($mfh=Apache::File->new('>'.$fn))) {
 1725:             $output .= '<p class="LC_error">';
 1726:             if ($caller eq 'transfer') {
 1727:                 $output .= &mt('Could not transfer data in added fields to notes');
 1728:             } else { 
 1729:                 $output .= &mt('Could not write metadata');
 1730:             }
 1731:             $output .= ', '.&mt('FAIL').'</p>';
 1732:             $outcome = 'fail';
 1733:         } else {
 1734:             print $mfh ($file_content);
 1735:             close($mfh);
 1736:             &update_metadata_table($uri);
 1737:             my $confirmtext;
 1738:             if ($caller eq 'transfer') {
 1739:                 $confirmtext = &mt('Transferred data in added fields to notes');
 1740:             } else {
 1741:                 $confirmtext = &mt('Wrote Metadata');
 1742:             }
 1743:             $output .= &Apache::loncommon::confirmwrapper(
 1744:                            &Apache::lonhtmlcommon::confirm_success(
 1745:                                $confirmtext.' '.&Apache::lonlocal::locallocaltime(time)));
 1746:             $outcome = 'ok';
 1747:         }
 1748:     }
 1749:     return ($outcome,$output);
 1750: }
 1751: 
 1752: sub store_transferred_addedfields {
 1753:     my ($fn,$uri,$transfers) = @_;
 1754:     foreach my $item (@{$transfers}) {
 1755:         $Apache::lonpublisher::metadatafields{'notes'} .= 
 1756:            ' '.$item.' = '.$Apache::lonpublisher::metadatafields{$item};
 1757:     }
 1758:     my ($outcome,$output) = &store_metadata($fn,$uri,'transfer');
 1759:     if ($outcome eq 'ok') {
 1760:         foreach my $item (@{$transfers}) {
 1761:             delete($Apache::lonpublisher::metadatafields{$item});
 1762:         }
 1763:     }
 1764: }
 1765: 
 1766: sub store_portfolio_metadata {
 1767:     my ($formname,$content,$path,$new_fn,$uri,$caller) = @_;
 1768:     my ($outcome,$output);
 1769:     $env{'form.'.$formname}=$content."\n";
 1770:     $env{'form.'.$formname.'.filename'}=$new_fn;
 1771:     my $result =&Apache::lonnet::userfileupload($formname,'',$path);
 1772:     if ($result =~ /(error|notfound)/) {
 1773:         $output = '<p class="LC_error">';
 1774:         if ($caller eq 'transfer') {
 1775:             $output .= 
 1776:                 &mt('Could not transfer data in added fields to notes'); 
 1777:         } else {
 1778:             $output .= &mt('Could not write metadata');
 1779:         }
 1780:         $output .= ', '.&mt('FAIL').'</p>';
 1781:         $outcome = 'fail';
 1782:     } else {
 1783:         &update_metadata_table($uri);
 1784:         $output = '<p class="LC_success">';
 1785:         if ($caller eq 'transfer') {
 1786:             $output .= &mt('Transferred data in added fields to notes');
 1787:         } else {
 1788:             $output .= &mt('Wrote Metadata');
 1789:         }
 1790:         $output .= ' '.&Apache::lonlocal::locallocaltime(time).
 1791:                    '</p>';
 1792:         $outcome = 'ok';
 1793:     }
 1794:     return ($outcome,$output);
 1795: }
 1796: 
 1797: sub update_metadata_table {
 1798:     my ($uri) = @_;
 1799:     my ($type,$udom,$uname,$file_name,$group) =
 1800: 	&Apache::lonnet::parse_portfolio_url($uri);
 1801:     $file_name =~ s/\.meta$//;
 1802:     my $current_permissions =
 1803:         &Apache::lonnet::get_portfile_permissions($udom,$uname);
 1804:     my %access_controls =
 1805:         &Apache::lonnet::get_access_controls($current_permissions,$group,
 1806:                                              $file_name);
 1807:     my $access_hash = $access_controls{$file_name};
 1808:     my $available = 0;
 1809:     if (ref($access_hash) eq 'HASH') {
 1810:         foreach my $key (keys(%{$access_hash})) {
 1811:             my ($num,$scope,$end,$start) =
 1812:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 1813:             if ($scope eq 'public' || $scope eq 'guest') {
 1814:                 $available = 1;
 1815:                 last;
 1816:             }
 1817:         }
 1818:     }
 1819:     if ($available) {
 1820:         my $result =
 1821:             &Apache::lonnet::update_portfolio_table($uname,$udom,
 1822:             $file_name,'portfolio_metadata',$group,'update');
 1823:     }
 1824: }
 1825: 
 1826: 
 1827: 1;
 1828: __END__
 1829: 
 1830: 
 1831: =head1 NAME
 1832: 
 1833: Apache::lonmeta - display meta data
 1834: 
 1835: =head1 SYNOPSIS
 1836: 
 1837: Handler to display meta data
 1838: 
 1839: This is part of the LearningOnline Network with CAPA project
 1840: described at http://www.lon-capa.org.
 1841: 
 1842: =head1 SUBROUTINES
 1843: 
 1844: =over
 1845: 
 1846: =item &get_dynamic_metadata_from_sql($url) :
 1847: 
 1848: Queries sql database for dynamic metdata
 1849: Returns a hash of hashes, with keys of urls which match $url
 1850: Returned fields are given below.
 1851: 
 1852: Examples:
 1853: 
 1854:     %DynamicMetadata = &Apache::lonmeta::get_dynmaic_metadata_from_sql
 1855:     ('/res/msu/korte/');
 1856: 
 1857:     $DynamicMetadata{'/res/msu/korte/example.problem'}->{$field}
 1858: 
 1859: =item dynamicmeta()
 1860: 
 1861: Fetch and evaluate dynamic metadata
 1862: 
 1863: =item access_count()
 1864: 
 1865: =item alttag()
 1866: 
 1867: Try to make an alt tag if there is none
 1868: 
 1869: =item authordisplay()
 1870: 
 1871: Author display
 1872: 
 1873: =item evalgraph()
 1874: 
 1875: Pretty display
 1876: 
 1877: =item diffgraph()
 1878: 
 1879: =item fieldnames()
 1880: 
 1881: =item portfolio_linked_path()
 1882: 
 1883: =item get_port_path_and_group()
 1884: 
 1885: =item portfolio_display_uri()
 1886: 
 1887: =item pre_select_course()
 1888: 
 1889: =item select_course()
 1890: 
 1891: =item prettyprint()
 1892: 
 1893: Pretty printing of metadata field
 1894: 
 1895: =item direct()
 1896: 
 1897: Pretty input of metadata field
 1898: 
 1899: =item selectbox()
 1900: 
 1901: =item relatedfield()
 1902: 
 1903: =item prettyinput()
 1904: 
 1905: =item report_bombs()
 1906: 
 1907: =item present_uneditable_metadata()
 1908: 
 1909: =item present_editable_metadata()
 1910: 
 1911: =item store_metadata()
 1912: 
 1913: =item store_transferred_addedfields()
 1914: 
 1915: =item store_portfolio_metadata()
 1916: 
 1917: =item update_metadata_table()
 1918: 
 1919: =back
 1920: 
 1921: =cut

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