File:  [LON-CAPA] / loncom / interface / lonmeta.pm
Revision 1.258: download - view: text, annotated - select for diffs
Tue Mar 18 18:57:28 2025 UTC (3 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- WCAG 2 compliance.

    1: # The LearningOnline Network with CAPA
    2: # Metadata display handler
    3: #
    4: # $Id: lonmeta.pm,v 1.258 2025/03/18 18:57:28 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,$id,$functionref,@idlist)=@_;
  554:     if (! defined($functionref)) {
  555:         $functionref=\&direct;
  556:     }
  557:     my $disabled;
  558:     if ($readonly) {
  559:         $disabled = ' disabled="disabled"';
  560:     }
  561:     if ($id ne '') {
  562:         $id = ' id="'.$id.'"';
  563:     }
  564:     my $selout='<select name="'.$name.'"'.$id.'>';
  565:     foreach my $id (@idlist) {
  566:         $selout.='<option value="'.$id.'"'.$disabled;
  567:         if ($id eq $value) {
  568: 	    $selout.=' selected="selected">'.&{$functionref}($id).'</option>';
  569:         } else {
  570:             $selout.='>'.&{$functionref}($id).'</option>';
  571:         }
  572:     }
  573:     return $selout.'</select>';
  574: }
  575: 
  576: sub relatedfield {
  577:     my ($show,$relatedsearchflag,$relatedsep,$fieldname,$relatedvalue)=@_;
  578:     if (! $relatedsearchflag) { 
  579:         return '';
  580:     }
  581:     if (! defined($relatedsep)) {
  582:         $relatedsep=' ';
  583:     }
  584:     if (! $show) {
  585:         return $relatedsep.'&nbsp;';
  586:     }
  587:     return $relatedsep.'<input type="checkbox" name="'.$fieldname.'_related"'.
  588: 	($relatedvalue?' checked="checked"':'').' id="'.$fieldname.'_related" />';
  589: }
  590: 
  591: sub prettyinput {
  592:     my ($type,$value,$readonly,$fieldname,$formname,
  593: 	$relatedsearchflag,$relatedsep,$relatedvalue,$size,$course_key)=@_;
  594:     if (! defined($size)) {
  595:         $size = 80;
  596:     }
  597:     my $output;
  598:     if (defined($course_key) 
  599: 	&& exists($env{$course_key.'.metadata.'.$type.'.options'})) {
  600:         my $stu_add;
  601:         my $only_one;
  602:         my %meta_options;
  603:         my @cur_values_inst;
  604:         my $cur_values_stu;
  605:         my $values = $env{$course_key.'.metadata.'.$type.'.values'};
  606:         if ($env{$course_key.'.metadata.'.$type.'.options'} =~ m/stuadd/) {
  607:             $stu_add = 'true';
  608:         }
  609:         if ($env{$course_key.'.metadata.'.$type.'.options'} =~ m/onlyone/) {
  610:             $only_one = 'true';
  611:         }
  612:         # need to take instructor values out of list where instructor and student
  613:         # values may be mixed.
  614:         if ($values) {
  615:             foreach my $item (split(/,/,$values)) {
  616:                 $item =~ s/^\s+//;
  617:                 $meta_options{$item} = $item;
  618:             }
  619:             foreach my $item (split(/,/,$value)) {
  620:                 $item =~ s/^\s+//;
  621:                 if ($meta_options{$item}) {
  622:                     push(@cur_values_inst,$item);
  623:                 } else {
  624:                     if ($item ne '') {
  625:                         $cur_values_stu .= $item.',';
  626:                     }
  627:                 }
  628:             }
  629:              $cur_values_stu =~ s/,$//;
  630:             my @key_order = sort(keys(%meta_options));
  631:             unshift(@key_order,'');
  632:             $meta_options{''} = 'Not specified';
  633:             $meta_options{'select_form_order'} = \@key_order;
  634:         } else {
  635:             $cur_values_stu = $value;
  636:         }
  637:         if ($type eq 'courserestricted') {
  638:             return (&select_course());
  639:             # return ('<input type="hidden" name="new_courserestricted" value="'.$course_key.'" />');
  640:         }
  641:         if (($type eq 'keywords') || ($type eq 'subject')
  642:              || ($type eq 'author')||($type eq  'notes')
  643:              || ($type eq  'abstract')|| ($type eq  'title')|| ($type eq  'standards')
  644:              || (exists($env{$course_key.'.metadata.'.$type.'.added'}))) {
  645:             
  646:             if ($values) {
  647:                 if ($only_one) {
  648:                     $output .= (&Apache::loncommon::select_form($cur_values_inst[0],'new_'.$type,\%meta_options));
  649:                 } else {
  650:                     $output .= (&Apache::loncommon::multiple_select_form('new_'.$type,\@cur_values_inst,undef,\%meta_options));
  651:                 }
  652:             }
  653:             if ($stu_add) {
  654:                 $output .= '<input type="text" name="'.$fieldname.'" size="'.$size.'" '.
  655:                 'value="'.$cur_values_stu.'" />'.
  656:                 &relatedfield(1,$relatedsearchflag,$relatedsep,$fieldname,
  657:                       $relatedvalue); 
  658:             }
  659:             return ($output);
  660:         } 
  661:         if (($type eq 'lowestgradelevel') ||
  662: 	    ($type eq 'highestgradelevel')) {
  663: 	    return &Apache::loncommon::select_level_form($value,$fieldname,$fieldname).
  664:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  665:         }
  666:         return(); 
  667:     }
  668:     # Language
  669:     if ($type eq 'language') {
  670: 	return &selectbox($fieldname,
  671: 			  $value,'',$fieldname,
  672: 			  \&Apache::loncommon::languagedescription,
  673: 			  (&Apache::loncommon::languageids)).
  674:                               &relatedfield(0,$relatedsearchflag,$relatedsep);
  675:     }
  676:     # Copyright
  677:     if ($type eq 'copyright') {
  678: 	return &selectbox($fieldname,
  679: 			  $value,$readonly,$fieldname,
  680: 			  \&Apache::loncommon::copyrightdescription,
  681: 			  (&Apache::loncommon::copyrightids)).
  682:                               &relatedfield(0,$relatedsearchflag,$relatedsep);
  683:     }
  684:     # Source Copyright
  685:     if ($type eq 'sourceavail') {
  686: 	return &selectbox($fieldname,
  687: 			  $value,'',$fieldname,
  688: 			  \&Apache::loncommon::source_copyrightdescription,
  689: 			  (&Apache::loncommon::source_copyrightids)).
  690:                               &relatedfield(0,$relatedsearchflag,$relatedsep);
  691:     }
  692:     # Gradelevels
  693:     if (($type eq 'lowestgradelevel') ||
  694: 	($type eq 'highestgradelevel')) {
  695: 	return &Apache::loncommon::select_level_form($value,$fieldname,$fieldname).
  696:             &relatedfield(0,$relatedsearchflag,$relatedsep);
  697:     }
  698:     # Obsolete
  699:     if ($type eq 'obsolete') {
  700: 	return '<input type="checkbox" name="'.$fieldname.'"'.
  701: 	    ($value?' checked="checked"':'').' id="'.$fieldname.'" />'.
  702:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  703:     }
  704:     # Obsolete replacement file
  705:     if ($type eq 'obsoletereplacement') {
  706: 	return '<input type="text" name="'.$fieldname.
  707: 	    '" size="60" value="'.$value.'" id="'.$fieldname.'" /><a href="javascript:openbrowser'.
  708: 	    "('".$formname."','".$fieldname."'".
  709: 	    ",'')\">".&mt('Select').'</a>'.
  710:             &relatedfield(0,$relatedsearchflag,$relatedsep);
  711:     }
  712:     # Customdistribution file
  713:     if ($type eq 'customdistributionfile') {
  714:         my $disabled;
  715:         if ($readonly) {
  716:             $disabled = ' disabled="disabled"';
  717:         }
  718:         my $output;
  719: 	$output = '<input type="text" name="'.$fieldname.
  720: 	    '" size="60" value="'.$value.'"'.$disabled.' id="'.$fieldname.'" />';
  721:         unless ($readonly) {
  722:             $output .= '<a href="javascript:openbrowser'.
  723: 	               "('".$formname."','".$fieldname."'".
  724: 	               ",'rights')\">".&mt('Select').'</a>';
  725:         }
  726:         $output .= &relatedfield(0,$relatedsearchflag,$relatedsep);
  727:         return $output;
  728:     }
  729:     # Source Customdistribution file
  730:     if ($type eq 'sourcerights') {
  731: 	return '<input type="text" name="'.$fieldname.
  732: 	    '" size="60" value="'.$value.'" id="'.$fieldname.'" /><a href="javascript:openbrowser'.
  733: 	    "('".$formname."','".$fieldname."'".
  734: 	    ",'rights')\">".&mt('Select').'</a>'.
  735:             &relatedfield(0,$relatedsearchflag,$relatedsep); 
  736:     }
  737:     if ($type eq 'courserestricted') {
  738:         return (&select_course());
  739:         #return ('<input type="hidden" name="new_courserestricted" value="'.$course_key.'" />');
  740:     }
  741: 
  742:     # Dates
  743:     if (($type eq 'creationdate') ||
  744: 	($type eq 'lastrevisiondate')) {
  745: 	return 
  746:             &Apache::lonhtmlcommon::date_setter($formname,$fieldname,$value).
  747:             &relatedfield(0,$relatedsearchflag,$relatedsep);
  748:     }
  749:     # No pretty input found
  750:     $value=~s/^\s+//gs;
  751:     $value=~s/\s+$//gs;
  752:     $value=~s/\s+/ /gs;
  753:     $value=~s/\"/\&quot\;/gs;
  754:     return 
  755:         '<input type="text" name="'.$fieldname.'" size="'.$size.'" '.
  756:         'value="'.$value.'" id="'.$fieldname.'" />'.
  757:         &relatedfield(1,$relatedsearchflag,$relatedsep,$fieldname,
  758:                       $relatedvalue);
  759: }
  760: 
  761: # Create pageheader
  762: sub pageheader {
  763:     my $output = '';
  764:     # No CSTR? Include breadcrumbs
  765:     if ($env{'request.state'} ne 'construct') {
  766:         # loncommon::bodytag already includes breadcrumbs for CSTR
  767:         # by calling lonmenu::innerregister
  768:         $output = &Apache::lonhtmlcommon::breadcrumbs();
  769:     }
  770:     # CSTR? Include CSTR header
  771:     if ($env{'request.state'} eq 'construct') {
  772:           $output .= &Apache::loncommon::head_subbox(
  773:                          &Apache::loncommon::CSTR_pageheader());
  774:     }
  775:     return $output;
  776: }
  777: 
  778: # Main Handler
  779: sub handler {
  780:     my $r=shift;
  781:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  782:          ['currentpath','changecourse','modal']);
  783:     my $uri=$r->uri;
  784:     #
  785:     # Set document type
  786:     &Apache::loncommon::content_type($r,'text/html');
  787:     $r->send_http_header;
  788:     return OK if $r->header_only;
  789:     my ($resdomain,$resuser)=
  790:         (&Apache::lonnet::declutter($uri)=~/^($match_domain)\/($match_username)\//);
  791: 
  792:     # Breadcrumbs
  793:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  794: 
  795:     if ($env{'request.state'} eq 'construct') {
  796:         my $text = 'Authoring Space';
  797:         my $href = &Apache::loncommon::authorspace($uri);
  798:         if ($env{'request.course.id'}) {
  799:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  800:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  801:             if ($href eq "/priv/$cdom/$cnum/") {
  802:                 $text = 'Course Authoring Space';
  803:             }
  804:         }
  805:         &Apache::lonhtmlcommon::add_breadcrumb({
  806:             'text'  => $text,
  807:             'href'  => $href,
  808:         });
  809:     }
  810: 
  811:     if ($uri=~m:/adm/bombs/(.*)$:) {
  812:         &Apache::lonhtmlcommon::add_breadcrumb({
  813:             'text'  => 'Error Messages',
  814:             'href'  => '',
  815:         });
  816:         $r->print(&Apache::loncommon::start_page('Error Messages'));
  817:         $r->print(&pageheader());
  818:         # Looking for all bombs?
  819:         &report_bombs($r,$uri);
  820:     } elsif ($uri=~m|^/editupload/[^/]+/[^/]+/portfolio/|) {
  821:         &Apache::lonhtmlcommon::add_breadcrumb({
  822:             'text'  => 'Edit Portfolio File Metadata',
  823:             'href'  => '',
  824:         });
  825: 	    ($resdomain,$resuser)=
  826: 		(&Apache::lonnet::declutter($uri)=~m|^($match_domain)/($match_name)/portfolio|);
  827:         $r->print(&Apache::loncommon::start_page('Edit Portfolio File Metadata',
  828: 						 undef,
  829: 						 {'domain' => $resdomain,}));
  830:         $r->print(&pageheader());
  831:         if ($env{'form.store'}) {
  832:             &present_editable_metadata($r,$uri,'portfolio');
  833:         } else {
  834:             my $fn=&Apache::lonnet::filelocation('',$uri);
  835:             %Apache::lonpublisher::metadatafields=();
  836:             %Apache::lonpublisher::metadatakeys=();
  837:             my $result=&Apache::lonnet::getfile($fn);
  838:             &Apache::lonpublisher::metaeval($result);
  839:             if ((!$Apache::lonpublisher::metadatafields{'courserestricted'}) ||
  840:                 ($env{'form.changecourse'} eq 'true')) {
  841:                 &pre_select_course($r,$uri);
  842:             } else {
  843:                 &present_editable_metadata($r,$uri,'portfolio');
  844:             }
  845:         }
  846:     } elsif ($uri=~m|^/editupload/[^/]+/[^/]+/groups/|) {
  847:         &Apache::lonhtmlcommon::add_breadcrumb({
  848:             'text'  => 'Edit Group Portfolio File Metadata',
  849:             'href'  => '',
  850:         });
  851:         $r->print(&Apache::loncommon::start_page('Edit Group Portfolio File Metadata',
  852: 						 undef,
  853: 						 {'domain' => $resdomain,}));
  854:         $r->print(&pageheader());
  855:         &present_editable_metadata($r,$uri,'groups');    
  856:     } elsif ($uri=~m|^/priv|) { 
  857:         # Authoring space
  858:         &Apache::lonhtmlcommon::add_breadcrumb({
  859:             'text'  => 'Edit Metadata',
  860:             'href'  => '',
  861:         });
  862:         $r->print(&Apache::loncommon::start_page('Edit Metadata',
  863: 						"\n".'<script type="text/javascript">'."\n".
  864:                                                 &Apache::loncommon::browser_and_searcher_javascript().
  865:                                                 "\n".'</script>',
  866: 						 {'domain' => $resdomain,}));
  867:         $r->print(&pageheader());
  868:         &present_editable_metadata($r,$uri);
  869:     } else {
  870:         &Apache::lonhtmlcommon::add_breadcrumb({
  871:             'text'  => 'Metadata',
  872:             'href'  => '',
  873:         });
  874:         $r->print(
  875:             &Apache::loncommon::start_page(
  876:                 'Metadata',
  877:                 undef,
  878:                 {'domain' => $resdomain,
  879:                 'only_body' => 1,})
  880:            .'<h1>'.&mt('Metadata').'</h1>'
  881:         );
  882:         if ($env{'form.modal'}) {
  883:             my $width = 500;
  884:             my $height = 400;
  885:             my $machine = &Apache::lonnet::absolute_url();
  886:             $r->print(&Apache::loncommon::nicescroll_javascript('metadatawrapper',
  887:                                                                 {cursorcolor => '#00F',
  888:                                                                  railalign => 'right',
  889:                                                                  railoffset => '{top:5,left:40}'},
  890:                                                                  undef,1,$machine.$uri));
  891:             $r->print('<div id="metadatawrapper" style="height:'.$height.'px; width:'.$width.'px; overflow: auto;">');
  892:         }
  893:         &present_uneditable_metadata($r,$uri);
  894:         if ($env{'form.modal'}) {
  895:             $r->print('</div>');
  896:         }
  897:     }
  898:     $r->print(&Apache::loncommon::end_page());
  899:     return OK;
  900: }
  901: 
  902: #####################################################
  903: #####################################################
  904: ###                                               ###
  905: ###                Report Bombs                   ###
  906: ###                                               ###
  907: #####################################################
  908: #####################################################
  909: sub report_bombs {
  910:     my ($r,$uri) = @_;
  911:     # Set document type
  912:     $uri =~ s:/adm/bombs/::;
  913:     $uri = &Apache::lonnet::declutter($uri);
  914:     $r->print(
  915:         '<p>'.&mt('Folder: [_1]',
  916:                   '<span class="LC_filename">'.&Apache::lonnet::clutter($uri).'</span>')
  917:        .'</p>'
  918:     );
  919:     my ($domain,$author)=($uri=~/^($match_domain)\/($match_username)\//);
  920:     if (!&Apache::lonnet::constructaccess('/priv/'.$domain.'/'.$author.'/')) {
  921:         $r->print('<p class="LC_error">'.&mt('Not authorized').'</p>');
  922:         return;
  923:     }
  924: 
  925:     my $showbuttons=1;
  926:     my $message='';
  927:     if ($env{'form.clearbombs'}) {
  928:         my $rc=&Apache::lonmsg::clear_author_res_msg($uri);
  929:         if ($rc eq 'ok') {
  930:                 $message=&Apache::lonhtmlcommon::confirm_success(
  931:                     &mt('Messages cleared.'));
  932:                 $showbuttons=0;
  933:         } else {
  934:                 $message=&Apache::lonhtmlcommon::confirm_success(
  935:                              &mt('Error clearing messages'),1)
  936:                         .'<br />'.&mt('Error: [_1]',$rc);
  937:         }
  938:     }
  939: 
  940:     if ($message) {    
  941:         $message=&Apache::loncommon::confirmwrapper($message);
  942:         $r->print($message);
  943:     }
  944: 
  945:     my $cancelurl=$uri;
  946:     $cancelurl=~s/^\Q$domain\E/\/priv\/$domain/;
  947: 
  948:     if ($showbuttons) {
  949:         $r->print(
  950:             '<form method="post" action="">'.
  951:             '<input type="submit" name="clearbombs" value="'.
  952:                 &mt('Clear all Messages in Subdirectory').'" />'.
  953:             ' <a href="'.$cancelurl.'">'.
  954:                 &mt('Back to Source Directory').'</a>'.
  955:             '</form><hr />'
  956:         );
  957:         # Display all bombs of subdirectory
  958:         my %brokenurls = 
  959:             &Apache::lonmsg::all_url_author_res_msg($author,$domain);
  960:         foreach my $key (sort(keys(%brokenurls))) {
  961:             if ($key=~/^\Q$uri\E/) {
  962:                 $r->print
  963:                     ('<a href="'.&Apache::lonnet::clutter($key).'">'.$key.'</a>'.
  964:                      &Apache::lonmsg::retrieve_author_res_msg($key).
  965:                      '<hr />');
  966:             }
  967:         }
  968:     } else {
  969:             my $functions=&Apache::lonhtmlcommon::start_funclist('Actions');
  970:             $functions.=&Apache::lonhtmlcommon::add_item_funclist(
  971:                             '<a href="'.$cancelurl.'">'.
  972:                             &mt('Back to Source Directory').'</a>');
  973:             $functions .= &Apache::lonhtmlcommon::end_funclist();
  974:             $r->print('<p>'.$functions.'</p>');
  975:     }
  976:     return;
  977: }
  978: 
  979: #####################################################
  980: #####################################################
  981: ###                                               ###
  982: ###        Uneditable Metadata Display            ###
  983: ###                                               ###
  984: #####################################################
  985: #####################################################
  986: sub present_uneditable_metadata {
  987:     my ($r,$uri) = @_;
  988:     #
  989:     my $uploaded = ($uri =~ m|/uploaded/|);
  990:     my %content=();
  991:     # Read file
  992:     foreach my $key (split(/\,/,&Apache::lonnet::metadata($uri,'keys'))) {
  993:         $content{$key}=&Apache::lonnet::metadata($uri,$key);
  994:     }
  995:     # Render Output
  996:     # displayed url
  997:     my ($thisversion)=($uri=~/\.(\d+)\.(\w+)\.meta$/);
  998:     $uri=~s/\.meta$//;
  999:     my $disuri=&Apache::lonnet::clutter_with_no_wrapper($uri);
 1000:     # version
 1001:     my $versiondisplay='';
 1002:     if (!$uploaded) {
 1003: 	my $currentversion=&Apache::lonnet::getversion($disuri);
 1004: 	if ($thisversion) {
 1005: 	    $versiondisplay=&mt('Version').': '.$thisversion.
 1006: 		' ('.&mt('most recent version').': '.
 1007: 		($currentversion>0 ? 
 1008: 		 $currentversion   :
 1009: 		 &mt('information not available')).')';
 1010: 	} else {
 1011: 	    $versiondisplay=&mt('Version: [_1]',$currentversion);
 1012: 	}
 1013:     }
 1014:     # crumbify displayed URL               uri     target prefix form 
 1015:     $disuri=&Apache::lonhtmlcommon::crumbs($disuri,undef, undef, undef);
 1016:     # obsolete
 1017:     my $obsolete=$content{'obsolete'};
 1018:     my $obsoletewarning='';
 1019:     if (($obsolete) && ($env{'user.adv'})) {
 1020:         $obsoletewarning='<p><span class="LC_warning">'.
 1021:             &mt('This resource has been marked obsolete by the author(s)').
 1022:             '</span></p>';
 1023:     }
 1024:     #
 1025:     my %lt=&fieldnames();
 1026:     my $table='';
 1027:     my $title = $content{'title'};
 1028:     if (! defined($title)) {
 1029:         $title = &mt('Untitled Resource');
 1030:     }
 1031:     my @fields;
 1032:     if ($uploaded) {
 1033: 	@fields = ('title','author','subject','keywords','notes','abstract',
 1034: 		   'lowestgradelevel','highestgradelevel','standards','mime',
 1035: 		   'owner');
 1036:     } else {
 1037: 	@fields = ('title', 
 1038: 		   'author', 
 1039: 		   'subject', 
 1040: 		   'keywords', 
 1041: 		   'notes', 
 1042: 		   'abstract',
 1043: 		   'lowestgradelevel',
 1044: 		   'highestgradelevel',
 1045: 		   'standards', 
 1046: 		   'mime', 
 1047: 		   'language', 
 1048: 		   'creationdate', 
 1049: 		   'lastrevisiondate', 
 1050: 		   'owner', 
 1051: 		   'copyright', 
 1052: 		   'customdistributionfile',
 1053: 		   'sourceavail',
 1054: 		   'sourcerights', 
 1055: 		   'obsolete', 
 1056: 		   'obsoletereplacement');
 1057:     }
 1058:     my $rownum = 0;
 1059:     foreach my $field (@fields) {
 1060:         my $lastrow = '';
 1061:         $rownum ++;
 1062:         $lastrow = 1 if ($rownum == @fields); 
 1063:         $table.=&Apache::lonhtmlcommon::row_title($lt{$field})
 1064:                .&prettyprint($field,$content{$field})
 1065:                .&Apache::lonhtmlcommon::row_closure($lastrow);
 1066:         delete($content{$field});
 1067:     }
 1068:     #
 1069:     $r->print("<h2>$title</h2>"
 1070:              .'<p>'
 1071:              .$disuri.'<br />'
 1072:              .$obsoletewarning
 1073:              .$versiondisplay
 1074:              .'</p>'
 1075:              .&Apache::lonhtmlcommon::start_pick_box()
 1076:              .$table
 1077:              .&Apache::lonhtmlcommon::end_pick_box()
 1078:     );
 1079:     if (!$uploaded && $env{'user.adv'}) {
 1080:         &print_dynamic_metadata($r,$uri,\%content);
 1081:     }
 1082:     return;
 1083: }
 1084: 
 1085: sub print_dynamic_metadata {
 1086:     my ($r,$uri,$content) = @_;
 1087:     #
 1088:     my %content = %$content;
 1089:     my %lt=&fieldnames();
 1090:     #
 1091:     my $description = 'Dynamic Metadata (updated periodically)';
 1092:     $r->print('<h3>'.&mt($description).'</h3>'.
 1093:               &mt('Processing'));
 1094:     $r->rflush();
 1095:     my %items=&fieldnames();
 1096:     my %dynmeta=&dynamicmeta($uri);
 1097:     #
 1098:     # General Access and Usage Statistics
 1099:     $r->print('<h4>'.&mt('Access and Usage Statistics').'</h4>');
 1100:     if (exists($dynmeta{'count'}) ||
 1101:         exists($dynmeta{'sequsage'}) ||
 1102:         exists($dynmeta{'comefrom'}) ||
 1103:         exists($dynmeta{'goto'}) ||
 1104:         exists($dynmeta{'course'})) {
 1105:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1106:         my @counts = ('count','sequsage','sequsage_list',
 1107:                       'comefrom','comefrom_list','goto',
 1108:                       'goto_list','course','course_list');
 1109:         my $rownum = 0;
 1110:         foreach my $item (@counts) {
 1111:             my $lastrow = '';
 1112:             $rownum ++;
 1113:             $lastrow = 1 if ($rownum == @counts);
 1114:             $r->print(&Apache::lonhtmlcommon::row_title($lt{$item})
 1115:                      .&prettyprint($item,$dynmeta{$item})
 1116:                      .&Apache::lonhtmlcommon::row_closure($lastrow)
 1117:             );
 1118:         }
 1119:         $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1120:     } else {
 1121:         $r->print('<p>'
 1122:                  .&mt('No Access or Usages Statistics are available for this resource.')
 1123:                  .'</p>'
 1124:         );
 1125:     }
 1126:     #
 1127:     # Assessment statistics
 1128:     if ($uri=~/$LONCAPA::assess_re/) {
 1129:         if (exists($dynmeta{'stdno'}) ||
 1130:             exists($dynmeta{'avetries'}) ||
 1131:             exists($dynmeta{'difficulty'}) ||
 1132:             exists($dynmeta{'disc'})) {
 1133:             # This is an assessment, print assessment data
 1134:             $r->print('<h4>'.
 1135:                       &mt('Overall Assessment Statistical Data').
 1136:                       '</h4>'.
 1137:                       &Apache::lonhtmlcommon::start_pick_box());
 1138:             $r->print(&Apache::lonhtmlcommon::row_title($lt{'stdno'})
 1139:                      .&prettyprint('stdno',$dynmeta{'stdno'})
 1140:                      .&Apache::lonhtmlcommon::row_closure()
 1141:             );
 1142:             my @stats = ('avetries','difficulty','disc');
 1143:             my $rownum = 0;
 1144:             foreach my $item (@stats) {
 1145:                 my $lastrow = '';
 1146:                 $rownum ++;
 1147:                 $lastrow = 1 if ($rownum == @stats);
 1148:                 $r->print(&Apache::lonhtmlcommon::row_title($lt{$item})
 1149:                          .&prettyprint($item,sprintf('%5.2f',$dynmeta{$item}))
 1150:                          .&Apache::lonhtmlcommon::row_closure($lastrow)
 1151:                 );
 1152:             }
 1153:             $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1154:         }
 1155:         #
 1156:         # New assessment statistics
 1157:         $r->print('<h4>'
 1158:                  .&mt('Recent Detailed Assessment Statistical Data')
 1159:                  .'</h4>'
 1160:         );
 1161:         if (exists($dynmeta{'stats'})) {
 1162:             my $table=&Apache::loncommon::start_data_table()
 1163:                      .&Apache::loncommon::start_data_table_header_row()
 1164: 		     .'<th>'.&mt('Domain').'</th>'
 1165:                      .'<th>'.&mt('Course').'</th>'
 1166:                      .'<th>'.&mt('Section(s)').'</th>'
 1167:                      .'<th>'.&mt('Num Students').'</th>'
 1168:                      .'<th>'.&mt('Part').'</th>'
 1169:                      .'<th>'.&mt('Mean Tries').'</th>'
 1170:                      .'<th>'.&mt('Degree of Difficulty').'</th>'
 1171:                      .'<th>'.&mt('Degree of Discrimination').'</th>'
 1172:                      .'<th>'.&mt('Time of computation').'</th>'
 1173:                      .&Apache::loncommon::end_data_table_header_row().$/;
 1174:             foreach my $identifier (sort(keys(%{$dynmeta{'stats'}}))) {
 1175:                 my $data = $dynmeta{'stats'}->{$identifier};
 1176:                 my $course = $data->{'course'};
 1177:                 my %courseinfo = 
 1178: 		    &Apache::lonnet::coursedescription($course,
 1179: 						       {'one_time' => 1});
 1180:                 if (! exists($courseinfo{'num'}) || $courseinfo{'num'} eq '') {
 1181:                     &Apache::lonnet::logthis('lookup for '.$course.' failed');
 1182:                     next;
 1183:                 }
 1184:                 $table .= &Apache::loncommon::start_data_table_row();
 1185: 		$table .=
 1186: 		    '<td><span class="LC_nobreak">'.$courseinfo{'domain'}.'</span></td>';
 1187:                 $table .= 
 1188:                     '<td><span class="LC_nobreak">'.$courseinfo{'description'}.'</span></td>';
 1189:                 $table .= 
 1190:                     '<td align="right">'.$data->{'sections'}.'</td>';
 1191:                 $table .=
 1192:                     '<td align="right">'.$data->{'stdno'}.'</td>';
 1193:                 $table .=
 1194:                     '<td align="right">'.$data->{'part'}.'</td>';
 1195:                 foreach my $item ('avetries','difficulty','disc') {
 1196:                     $table .= '<td align="right">';
 1197:                     if (exists($data->{$item})) {
 1198:                         $table .= sprintf('%.2f',$data->{$item}).'&nbsp;';
 1199:                     } else {
 1200:                         $table .= '';
 1201:                     }
 1202:                     $table .= '</td>';
 1203:                 }
 1204:                 $table .=
 1205:                     '<td><span class="LC_nobreak">'.
 1206:                     &Apache::lonlocal::locallocaltime($data->{'timestamp'}).
 1207:                     '</span></td>';
 1208:                 $table .= &Apache::loncommon::end_data_table_row().$/;
 1209:             }
 1210:             $table .= &Apache::loncommon::end_data_table().$/;
 1211:             $r->print($table);
 1212:         } else {
 1213:             $r->print('<p>'
 1214:                      .&mt('No new dynamic data found.')
 1215:                      .'</p>'
 1216:             );
 1217:         }
 1218:     } else {
 1219:         $r->print('<h4>'.
 1220:           &mt('No Assessment Statistical Data is available for this resource').
 1221:                   '</h4>');
 1222:     }
 1223:     #
 1224:     # Evaluation Data
 1225:     $r->print('<h4>'.&mt('Evaluation Data').'</h4>');
 1226:     if (exists($dynmeta{'clear'})   || 
 1227:         exists($dynmeta{'depth'})   || 
 1228:         exists($dynmeta{'helpful'}) || 
 1229:         exists($dynmeta{'correct'}) || 
 1230:         exists($dynmeta{'technical'})){ 
 1231:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1232:         my @criteria = ('clear','depth','helpful','correct','technical');
 1233:         my $rownum = 0;
 1234:         foreach my $item (@criteria) {
 1235:             my $lastrow = '';
 1236:             $rownum ++;
 1237:             $lastrow = 1 if ($rownum == @criteria);
 1238:             $r->print(&Apache::lonhtmlcommon::row_title($lt{$item})
 1239:                      .&prettyprint($item,$dynmeta{$item})
 1240:                      .&Apache::lonhtmlcommon::row_closure($lastrow)
 1241:             );
 1242:         }
 1243:         $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1244:     } else {
 1245:         $r->print('<p>'
 1246:                  .&mt('No Evaluation Data is available for this resource.')
 1247:                  .'</p>'
 1248:         );
 1249:     }
 1250:     # Evaluation Comments
 1251:     $uri=~/^\/res\/($match_domain)\/($match_username)\//; 
 1252:     if ((($env{'user.domain'} eq $1) && ($env{'user.name'} eq $2))
 1253:         || ($env{'user.role.ca./'.$1.'/'.$2})) {
 1254:         $r->print('<h4>'.&mt('Evaluation Comments').'</h4>'
 1255:                  .'<div>('
 1256:                  .&mt('visible to author and co-authors only')
 1257:                  .')</div>'
 1258:         );
 1259:         if (exists($dynmeta{'comments'})) {
 1260:             $r->print('<blockquote>'.$dynmeta{'comments'}.'</blockquote>');
 1261:         } else {
 1262:             $r->print('<p>'
 1263:                      .&mt('There are no Evaluation Comments on this resource.')
 1264:                      .'</p>'
 1265:             );
 1266:         }
 1267:         my $bombs = &Apache::lonmsg::retrieve_author_res_msg($uri);
 1268:         if (defined($bombs) && $bombs ne '') {
 1269:             $r->print('<a name="bombs" />'
 1270:                      .'<h4 class="LC_warning">'.&mt('Error Messages').'</h4>'
 1271:                      .'<div>('
 1272:                      .&mt('visible to author and co-authors only')
 1273:                      .')</div>'
 1274:                      .$bombs
 1275:             );
 1276:         } #else {
 1277:         #    $r->print('<h4>'.&mt('There are currently no Error Messages for this resource.').'</h4>');
 1278:         #}
 1279:     }
 1280:     #
 1281:     # All other stuff
 1282:     $r->print('<h3>'.
 1283:               &mt('Additional Metadata (non-standard, parameters, exports)').
 1284:               '</h3>');
 1285:     $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1286:     my @names;
 1287:     foreach my $key (sort(keys(%content))) {
 1288:         if ($key!~/\.display$/) {
 1289:             push(@names,$key);
 1290:         }
 1291:     }
 1292:     if (@names > 0) {
 1293:         my $rownum = 0;
 1294:         foreach my $name (@names) {
 1295:             my $lastrow = '';
 1296:             $rownum ++;
 1297:             $lastrow = 1 if ($rownum == @names);
 1298: 
 1299:             my $display=&Apache::lonnet::metadata($uri,
 1300:                                                   $name.'.display');
 1301:             if (! $display) { 
 1302:                 $display=$name;
 1303:             };
 1304:             my $otherinfo='';
 1305:             foreach my $item ('name','part','type','default') {
 1306:                 if (defined(&Apache::lonnet::metadata($uri,
 1307:                                                       $name.'.'.$item))) {
 1308:                     $otherinfo.=' '.$item.'='.
 1309:                         &Apache::lonnet::metadata($uri,
 1310:                                                   $name.'.'.$item).'; ';
 1311:                 }
 1312:             }
 1313:             $r->print(&Apache::lonhtmlcommon::row_title($display)
 1314:                      .$content{$name}
 1315:             );
 1316:             if ($otherinfo) {
 1317:                 $r->print(' ('.$otherinfo.')');
 1318:             }
 1319:             $r->print(&Apache::lonhtmlcommon::row_closure($lastrow));
 1320:         }
 1321:     }
 1322:     $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1323:     return;
 1324: }
 1325: 
 1326: 
 1327: 
 1328: #####################################################
 1329: #####################################################
 1330: ###                                               ###
 1331: ###          Editable metadata display            ###
 1332: ###                                               ###
 1333: #####################################################
 1334: #####################################################
 1335: sub present_editable_metadata {
 1336:     my ($r,$uri,$file_type) = @_;
 1337:     # Authoring Space Call
 1338:     # Header
 1339:     my $disuri=$uri;
 1340:     my ($courseauthor,$crsaurights,$readonly);
 1341:     if ($env{'request.course.id'}) {
 1342:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1343:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1344:         if ($uri =~ m{^\Q/priv/$cdom/$cnum/\E}) {
 1345:             $courseauthor = $cnum.':'.$cdom;
 1346:             $crsaurights = "/res/$cdom/$cnum/default.rights";
 1347:             $readonly = 1;
 1348:         }
 1349:     }
 1350:     my $fn=&Apache::lonnet::filelocation('',$uri);
 1351:     $disuri=~s{^/\~}{/priv/};
 1352:     $disuri=~s/\.meta$//;
 1353:     my $meta_uri = $disuri;
 1354:     my $path;
 1355:     if ($disuri =~ m|/portfolio/|) {
 1356: 	($disuri, $meta_uri, $path) =  &portfolio_display_uri($disuri,1);
 1357:     }
 1358:     my $target=$uri;
 1359:     $target=~s{^/\~}{/res/$env{'request.role.domain'}/};
 1360:     $target=~s/\.meta$//;
 1361:     my $bombs=&Apache::lonmsg::retrieve_author_res_msg($target);
 1362:     if ($bombs) {
 1363:         # Display Bombs, not Metadata
 1364:         $r->print(
 1365:             '<h2>'.&mt('Error Messages').'</h2>'
 1366:            .'<p>'.&mt('Folder: [_1]',
 1367:                       '<span class="LC_filename">'.$disuri.'</span>')
 1368:            .'</p>'
 1369:         );
 1370:         my $showbuttons=1;
 1371:         my $message='';
 1372:         my $rc='';
 1373:         if ($env{'form.delmsg'}) {
 1374:             $rc=&Apache::lonmsg::del_url_author_res_msg($target);
 1375:             if ($rc eq 'ok') {
 1376:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1377:                              &mt('Messages deleted.'));
 1378: 		$showbuttons=0;
 1379:             } else {
 1380:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1381:                              &mt('Error deleting messages'), 1)
 1382:                         .'<br />'.&mt('Error: [_1]',$rc);
 1383:             }
 1384:         }
 1385:         if ($env{'form.clearmsg'}) {
 1386: 	    my $cleardir=$target;
 1387: 	    $cleardir=~s/\/[^\/]+$/\//; # Extract dir: keep path, remove filename
 1388:             $rc=&Apache::lonmsg::clear_author_res_msg($cleardir);
 1389:             if ($rc eq 'ok') {
 1390:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1391:                     &mt('Messages cleared.'));
 1392: 		$showbuttons=0;
 1393:             } else {
 1394:                 $message=&Apache::lonhtmlcommon::confirm_success(
 1395:                              &mt('Error clearing messages'),1)
 1396:                         .'<br />'.&mt('Error: [_1]',$rc);
 1397:             }
 1398:         }
 1399:         if ($message) {
 1400:             $message=&Apache::loncommon::confirmwrapper($message);
 1401:             $r->print($message);
 1402:         }
 1403: 
 1404:         $r->print('<form method="post" action="" name="defaultmeta">');
 1405:         if ($showbuttons) {
 1406:             $r->print(
 1407:                 '<input type="submit" name="delmsg" value="'.
 1408:                 &mt('Delete Messages for this Resource').'" />'.
 1409:                 '<input type="submit" name="clearmsg" value="'.
 1410:                 &mt('Clear all Messages in Subdirectory').'" />'
 1411:                .'<br />'.$bombs
 1412:             );
 1413:         } else {
 1414:             my $functions=&Apache::lonhtmlcommon::start_funclist('Actions');
 1415:             $functions.=&Apache::lonhtmlcommon::add_item_funclist(
 1416:                             '<a href="'.$disuri.'">'.
 1417:                             &mt('Back to Source File').'</a>');
 1418:             my ($diruri) = ($disuri =~ m{(.*/)[^/]*});
 1419:             $functions.=&Apache::lonhtmlcommon::add_item_funclist(
 1420:                             '<a href="'.$diruri.'">'.
 1421:                             &mt('Back to Source Directory').'</a>');
 1422:             $functions .= &Apache::lonhtmlcommon::end_funclist();
 1423:             $r->print('<p>'.$functions.'</p>');
 1424:         }
 1425:     } else {
 1426: 
 1427:         # Display Metadata, not Bombs
 1428:         my $displayfile =
 1429:             &mt('Metadata for [_1]'
 1430:                ,'<span class="LC_filename">'.$disuri.'</span>');
 1431:         if ($disuri=~/\/default$/) {
 1432:             my $dir=$disuri;
 1433:             $dir=~s/default$//;
 1434:             $displayfile=&mt('Default Metadata for Directory [_1]'
 1435:                             ,'<span class="LC_filename">'.$dir.'</span>');
 1436:         }
 1437:         %Apache::lonpublisher::metadatafields=();
 1438:         %Apache::lonpublisher::metadatakeys=();
 1439:         my $result=&Apache::lonnet::getfile($fn);
 1440:         if ($result == -1){
 1441:             my $message = &Apache::lonhtmlcommon::confirm_success(
 1442:                 &mt('Creating new file [_1]'
 1443:                    ,'<span class="LC_filename"'.$meta_uri.'</span>'));
 1444:             $message = &Apache::loncommon::confirmwrapper($message);
 1445:             $r->print($message);
 1446:         } else {
 1447:             &Apache::lonpublisher::metaeval($result);
 1448:         }
 1449:         if ($env{'form.new_courserestricted'}) {
 1450:             my $new_assoc_course = $env{'form.new_courserestricted'};
 1451:             my $prev_courserestricted = $Apache::lonpublisher::metadatafields{'courserestricted'};
 1452:             if (($prev_courserestricted) && 
 1453:                 ($prev_courserestricted ne $new_assoc_course)) {
 1454:                 my $transfers = [];
 1455:                 foreach my $key (keys(%env)) {
 1456:                     if ($key =~ /^form\.transfer_(.+)$/) {
 1457:                         push(@{$transfers},$1);
 1458:                     }
 1459:                 }
 1460:                 if (@{$transfers} > 0) {
 1461:                     &store_transferred_addedfields($fn,$uri,$transfers);
 1462:                 }
 1463:             }
 1464:         }
 1465:         $r->print(<<ENDEDIT);
 1466: <h2>$displayfile</h2>
 1467: <form method="post" action="" name="defaultmeta">
 1468: ENDEDIT
 1469:         my %lt=&fieldnames($file_type);
 1470: 	my $output;
 1471: 	my @fields;
 1472: 	my $added_metadata_fields;
 1473: 	my @added_order;
 1474:         if ($file_type eq 'groups') {
 1475:             $Apache::lonpublisher::metadatafields{'courserestricted'}=
 1476:                 'course.'.$env{'request.course.id'};
 1477:         }
 1478:         if ((! $Apache::lonpublisher::metadatafields{'courserestricted'}) &&
 1479:                 (! $env{'form.new_courserestricted'}) && (! $file_type eq 'groups')) {
 1480:             $Apache::lonpublisher::metadatafields{'courserestricted'}=
 1481:                 'none';
 1482:         } elsif ($env{'form.new_courserestricted'}) {
 1483:             $Apache::lonpublisher::metadatafields{'courserestricted'}=
 1484:                 $env{'form.new_courserestricted'};
 1485:         }
 1486: 	if ($file_type eq 'portfolio' || $file_type eq 'groups') {
 1487: 	    if(exists ($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.fieldlist'})) {
 1488: 	        # retrieve fieldnames (in order) from the course restricted list
 1489: 	        @fields = (split(/,/,$env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.fieldlist'}));
 1490: 	    } else {
 1491: 	        # no saved field list, use default list
 1492: 	        @fields =  ('title','author','subject','keywords','abstract',
 1493: 			    'notes','lowestgradelevel',
 1494: 	                    'highestgradelevel','standards');
 1495:                 if ($Apache::lonpublisher::metadatafields{'courserestricted'} =~ /^course\.($match_domain\_$match_courseid)$/) {
 1496:                     my $assoc_crs = $1;
 1497: 	            $added_metadata_fields = &Apache::lonparmset::get_added_meta_fieldnames($assoc_crs);
 1498: 	            if ($env{'course.'.$assoc_crs.'.metadata.addedorder'}) {
 1499: 	                @added_order = split(/,/,$env{'course.'.$assoc_crs.'.metadata.addedorder'});
 1500: 	            }
 1501: 	            $env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.fieldlist'} = join(",",@fields);
 1502:                 }
 1503: 	    }
 1504: 	} else {
 1505: 	    @fields = ('title','author','subject','keywords','abstract','notes',
 1506: 		       'copyright','customdistributionfile','language',
 1507: 		       'standards',
 1508: 		       'lowestgradelevel','highestgradelevel','sourceavail','sourcerights',
 1509: 		       'obsolete','obsoletereplacement');
 1510:         }
 1511:         if ($courseauthor) {
 1512:             $Apache::lonpublisher::metadatafields{'copyright'}='custom';
 1513:             $Apache::lonpublisher::metadatafields{'customdistributionfile'}=$crsaurights;
 1514:         }
 1515:         my (%domdefs,$got_domdefs);
 1516:         if (! $Apache::lonpublisher::metadatafields{'copyright'}) {
 1517:             my $copyright = 'default';
 1518:             if ($env{'environment.copyright'} ne '') {
 1519:                 $copyright = $env{'environment.copyright'};
 1520:             } else {
 1521:                 my $defdom = $env{'request.role.domain'};
 1522:                 if ($disuri =~ m{^/priv/($match_domain)/}) {
 1523:                     $defdom = $1;
 1524:                 }
 1525:                 if ($defdom ne '') {
 1526:                     %domdefs = &Apache::lonnet::get_domain_defaults($defdom);
 1527:                     $got_domdefs = 1;
 1528:                     if ($domdefs{'copyright'} ne '') {
 1529:                         $copyright = $domdefs{'copyright'};
 1530:                     }
 1531:                 }
 1532:             }
 1533:             $Apache::lonpublisher::metadatafields{'copyright'}=
 1534: 		$copyright;
 1535:         }
 1536:         if (! $Apache::lonpublisher::metadatafields{'sourceavail'}) {
 1537:             my $sourceavail = 'closed';
 1538:             if ($env{'environment.sourceavail'} ne '') {
 1539:                 $sourceavail = $env{'environment.sourceavail'};
 1540:             } else {
 1541:                 my $defdom = $env{'request.role.domain'};
 1542:                 if ($disuri =~ m{^/priv/($match_domain)/}) {
 1543:                     $defdom = $1;
 1544:                 }
 1545:                 if ($defdom ne '') {
 1546:                     unless ($got_domdefs) {
 1547:                         %domdefs = &Apache::lonnet::get_domain_defaults($defdom);
 1548:                         $got_domdefs = 1;
 1549:                     }
 1550:                     if ($domdefs{'sourceavail'} ne '') {
 1551:                         $sourceavail = $domdefs{'sourceavail'};
 1552:                     }
 1553:                 }
 1554:             }
 1555:             $Apache::lonpublisher::metadatafields{'sourceavail'}=
 1556:                 $sourceavail;
 1557:         }
 1558: 	if (($file_type eq 'portfolio') || ($file_type eq 'groups'))  {
 1559: 	    if (! $Apache::lonpublisher::metadatafields{'mime'}) {
 1560:                 ($Apache::lonpublisher::metadatafields{'mime'}) =
 1561: 		    ( $target=~/\.(\w+)$/ );
 1562: 	    }
 1563: 	    if (! $Apache::lonpublisher::metadatafields{'owner'}) {
 1564: 		$Apache::lonpublisher::metadatafields{'owner'} =
 1565: 		    $env{'user.name'}.':'.$env{'user.domain'};
 1566: 	    }
 1567: 	    if (! $Apache::lonpublisher::metadatafields{'author'}) {
 1568: 		$Apache::lonpublisher::metadatafields{'author'} =
 1569: 		    &Apache::loncommon::plainname($env{'user.name'},
 1570: 						  $env{'user.domain'});
 1571: 	    }
 1572: 	    if ($Apache::lonpublisher::metadatafields{'courserestricted'} ne 'none') {
 1573: 
 1574:                 if ($file_type eq 'portfolio') {
 1575:                     $r->print(
 1576:                         &mt('Associated with course [_1]'
 1577:                            ,'<strong>'
 1578:                            .$env{$Apache::lonpublisher::metadatafields{'courserestricted'}
 1579:                            .".description"}.'</strong>')
 1580:                        .' <a href="'.$uri.'?changecourse=true">'
 1581:                        .&mt('Change')
 1582:                        .'</a>'.'<br />'
 1583:                     );
 1584: 
 1585:                 } else {
 1586:                     $r->print(&mt('Associated with course [_1]',
 1587:                         '<strong>'.
 1588:   $env{$Apache::lonpublisher::metadatafields{'courserestricted'}.
 1589:                         ".description"}.'</strong>').'<br />');
 1590:                 }
 1591:             } else {
 1592:                 $r->print(
 1593:                     &mt('This resource is not associated with a course.')
 1594:                   .' <a href="'.$uri.'?changecourse=true">'.&mt('Change').'</a><br />'
 1595:                 );
 1596:             }
 1597:         }
 1598: 	if (@added_order) {
 1599: 	    foreach my $field_name (@added_order) {
 1600:                 push(@fields,$field_name);
 1601:                 $lt{$field_name} = $$added_metadata_fields{$field_name};
 1602: 	    }
 1603: 	} else {
 1604:             foreach my $field_name (keys(%$added_metadata_fields)) {
 1605:                 push(@fields,$field_name);
 1606:                 $lt{$field_name} = $$added_metadata_fields{$field_name};
 1607:             }
 1608:         }
 1609:         $output .= &Apache::lonhtmlcommon::start_pick_box();
 1610:         my $last = $#fields + 1;
 1611:         my $rowcount = 0;
 1612:         foreach my $field_name (@fields) {
 1613:             $rowcount++;
 1614:             if (defined($env{'form.new_'.$field_name})) {
 1615:                 my @values = &Apache::loncommon::get_env_multiple('form.new_'.$field_name);
 1616:                 my $newvalue = '';
 1617:                 foreach my $item (@values) {
 1618:                     if ($item ne '') {
 1619:                         $newvalue .= $item.',';
 1620:                     }
 1621:                 }
 1622:                 $newvalue =~ s/,$//; 
 1623:                 $Apache::lonpublisher::metadatafields{$field_name}=$newvalue;
 1624:             }
 1625:             if ($Apache::lonpublisher::metadatafields{'courserestricted'} ne 'none'
 1626: 		&& exists($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'})) {
 1627:                 # handle restrictions here
 1628:                 if ((($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'} =~ m/active/) ||
 1629:                     ($field_name eq 'courserestricted'))&&
 1630:                     (!($env{$Apache::lonpublisher::metadatafields{'courserestricted'}.'.metadata.'.$field_name.'.options'} =~ m/deleted/))){
 1631:                     
 1632:                     $output .= &Apache::lonhtmlcommon::row_title($lt{$field_name})
 1633:                               .&prettyinput($field_name,
 1634: 				   $Apache::lonpublisher::metadatafields{$field_name},
 1635: 				                    $readonly,'new_'.$field_name,'defaultmeta',
 1636: 				                    undef,undef,undef,undef,
 1637:                                                     $Apache::lonpublisher::metadatafields{'courserestricted'});
 1638:                     $output .= &Apache::lonhtmlcommon::row_closure($rowcount == $last?1:0);
 1639:                  }
 1640:             } else {
 1641:                     $output .= &Apache::lonhtmlcommon::row_title($lt{$field_name})
 1642:                               .&prettyinput($field_name,
 1643: 					   $Apache::lonpublisher::metadatafields{$field_name},
 1644:                                            $readonly,'new_'.$field_name,'defaultmeta')
 1645:                               .&Apache::lonhtmlcommon::row_closure($rowcount == $last?1:0);
 1646:                
 1647:             }
 1648:         }
 1649:         $output .= &Apache::lonhtmlcommon::end_pick_box();
 1650: 	if ($env{'form.store'}) {
 1651:             my ($outcome,$result) = &store_metadata($fn,$uri,'store');
 1652:             $r->print($result);
 1653: 	}
 1654:         my $savebutton = '<p><input type="submit" name="store"'
 1655:                         .' value="'.&mt('Save').'" title="'.&mt('Save Metadata').'" /></p>';
 1656:         $r->print($savebutton.$output.$savebutton);
 1657: 
 1658: 	if ($file_type eq 'portfolio' || $file_type eq 'groups') {
 1659: 	    my ($port_path,$group) = &get_port_path_and_group($uri);
 1660:             if ($group ne '') {
 1661:                 $r->print('<input type="hidden" name="group" value="'.$group.'" />');
 1662:             }
 1663:             $r->print('<input type="hidden" name="currentpath" value="'.$env{'form.currentpath'}.'" />');
 1664: 	    $r->print('</form><br /><br /><form method="post" action="'.$port_path.'">');
 1665: 	    if ($group ne '') {
 1666: 	        $r->print('<input type="hidden" name="group" value="'.$group.'" />');
 1667:             }
 1668: 	    $r->print('<input type="hidden" name="currentpath" value="'.$path.'" />'.
 1669: 		      '<input type="submit" name="cancel" value="'.&mt('Discard Edits and Return to Portfolio').'" />');
 1670: 	}
 1671:     }
 1672:     
 1673:     $r->print('</form>');
 1674: 
 1675:     return;
 1676: }
 1677: 
 1678: sub store_metadata {
 1679:     my ($fn,$uri,$caller) = @_;
 1680:     my $mfh;
 1681:     my $formname='store';
 1682:     my ($file_content,$output,$outcome);
 1683:     if (&Apache::loncommon::get_env_multiple('form.new_keywords')) {
 1684:         $Apache::lonpublisher::metadatafields{'keywords'} =
 1685:             join (',', &Apache::loncommon::get_env_multiple('form.new_keywords'));
 1686:             }
 1687:     if (($caller eq 'store') && ($env{'request.course.id'})) {
 1688:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1689:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1690:         if ($uri =~ m{^\Q/priv/$cdom/$cnum/\E}) {
 1691:             unless ($uri eq "/priv/$cdom/$cnum/default.rights.meta") {
 1692:                 $Apache::lonpublisher::metadatafields{'copyright'} = 'custom';
 1693:                 $Apache::lonpublisher::metadatafields{'customdistributionfile'} =
 1694:                     "/res/$cdom/$cnum/default.rights";
 1695:             }
 1696:         }
 1697:     }
 1698:     foreach my $field (sort(keys(%Apache::lonpublisher::metadatafields))) {
 1699:         next if ($field =~ /\./);
 1700:         my $unikey=$field;
 1701:         $unikey=~/^([A-Za-z_]+)/;
 1702:         my $tag=$1;
 1703:         $tag=~tr/A-Z/a-z/;
 1704:         $file_content.= "\n\<$tag";
 1705:         foreach my $key (split(/\,/,$Apache::lonpublisher::metadatakeys{$unikey})) {
 1706:             my $value = $Apache::lonpublisher::metadatafields{$unikey.'.'.$key};
 1707:             $value=~s/\"/\'\'/g;
 1708:             $file_content.=' '.$key.'="'.$value.'"' ;
 1709:         }
 1710:         $file_content.= '>'.
 1711:             &HTML::Entities::encode
 1712:                 ($Apache::lonpublisher::metadatafields{$unikey},'<>&"').
 1713:                 '</'.$tag.'>';
 1714:     }
 1715:     if ($fn =~ m|^$Apache::lonnet::perlvar{'lonDocRoot'}/userfiles|) {
 1716:         my ($path, $new_fn);
 1717:         if ($fn =~ m|$match_name/groups/\w+/portfolio/|) {
 1718:             ($path, $new_fn) = ($fn =~ m|/(groups/\w+/portfolio.*)/([^/]*)$|);
 1719:         } else {
 1720:             ($path, $new_fn) = ($fn =~ m|/(portfolio.*)/([^/]*)$|);
 1721:         }
 1722:         ($outcome,my $result) = 
 1723:             &store_portfolio_metadata($formname,$file_content,
 1724:                                       $path,$new_fn,$uri,$caller);
 1725:         $output .= $result;
 1726:     } else {
 1727:         if (! ($mfh=Apache::File->new('>'.$fn))) {
 1728:             $output .= '<p class="LC_error">';
 1729:             if ($caller eq 'transfer') {
 1730:                 $output .= &mt('Could not transfer data in added fields to notes');
 1731:             } else { 
 1732:                 $output .= &mt('Could not write metadata');
 1733:             }
 1734:             $output .= ', '.&mt('FAIL').'</p>';
 1735:             $outcome = 'fail';
 1736:         } else {
 1737:             print $mfh ($file_content);
 1738:             close($mfh);
 1739:             &update_metadata_table($uri);
 1740:             my $confirmtext;
 1741:             if ($caller eq 'transfer') {
 1742:                 $confirmtext = &mt('Transferred data in added fields to notes');
 1743:             } else {
 1744:                 $confirmtext = &mt('Wrote Metadata');
 1745:             }
 1746:             $output .= &Apache::loncommon::confirmwrapper(
 1747:                            &Apache::lonhtmlcommon::confirm_success(
 1748:                                $confirmtext.' '.&Apache::lonlocal::locallocaltime(time)));
 1749:             $outcome = 'ok';
 1750:         }
 1751:     }
 1752:     return ($outcome,$output);
 1753: }
 1754: 
 1755: sub store_transferred_addedfields {
 1756:     my ($fn,$uri,$transfers) = @_;
 1757:     foreach my $item (@{$transfers}) {
 1758:         $Apache::lonpublisher::metadatafields{'notes'} .= 
 1759:            ' '.$item.' = '.$Apache::lonpublisher::metadatafields{$item};
 1760:     }
 1761:     my ($outcome,$output) = &store_metadata($fn,$uri,'transfer');
 1762:     if ($outcome eq 'ok') {
 1763:         foreach my $item (@{$transfers}) {
 1764:             delete($Apache::lonpublisher::metadatafields{$item});
 1765:         }
 1766:     }
 1767: }
 1768: 
 1769: sub store_portfolio_metadata {
 1770:     my ($formname,$content,$path,$new_fn,$uri,$caller) = @_;
 1771:     my ($outcome,$output);
 1772:     $env{'form.'.$formname}=$content."\n";
 1773:     $env{'form.'.$formname.'.filename'}=$new_fn;
 1774:     my $result =&Apache::lonnet::userfileupload($formname,'',$path);
 1775:     if ($result =~ /(error|notfound)/) {
 1776:         $output = '<p class="LC_error">';
 1777:         if ($caller eq 'transfer') {
 1778:             $output .= 
 1779:                 &mt('Could not transfer data in added fields to notes'); 
 1780:         } else {
 1781:             $output .= &mt('Could not write metadata');
 1782:         }
 1783:         $output .= ', '.&mt('FAIL').'</p>';
 1784:         $outcome = 'fail';
 1785:     } else {
 1786:         &update_metadata_table($uri);
 1787:         $output = '<p class="LC_success">';
 1788:         if ($caller eq 'transfer') {
 1789:             $output .= &mt('Transferred data in added fields to notes');
 1790:         } else {
 1791:             $output .= &mt('Wrote Metadata');
 1792:         }
 1793:         $output .= ' '.&Apache::lonlocal::locallocaltime(time).
 1794:                    '</p>';
 1795:         $outcome = 'ok';
 1796:     }
 1797:     return ($outcome,$output);
 1798: }
 1799: 
 1800: sub update_metadata_table {
 1801:     my ($uri) = @_;
 1802:     my ($type,$udom,$uname,$file_name,$group) =
 1803: 	&Apache::lonnet::parse_portfolio_url($uri);
 1804:     $file_name =~ s/\.meta$//;
 1805:     my $current_permissions =
 1806:         &Apache::lonnet::get_portfile_permissions($udom,$uname);
 1807:     my %access_controls =
 1808:         &Apache::lonnet::get_access_controls($current_permissions,$group,
 1809:                                              $file_name);
 1810:     my $access_hash = $access_controls{$file_name};
 1811:     my $available = 0;
 1812:     if (ref($access_hash) eq 'HASH') {
 1813:         foreach my $key (keys(%{$access_hash})) {
 1814:             my ($num,$scope,$end,$start) =
 1815:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 1816:             if ($scope eq 'public' || $scope eq 'guest') {
 1817:                 $available = 1;
 1818:                 last;
 1819:             }
 1820:         }
 1821:     }
 1822:     if ($available) {
 1823:         my $result =
 1824:             &Apache::lonnet::update_portfolio_table($uname,$udom,
 1825:             $file_name,'portfolio_metadata',$group,'update');
 1826:     }
 1827: }
 1828: 
 1829: 
 1830: 1;
 1831: __END__
 1832: 
 1833: 
 1834: =head1 NAME
 1835: 
 1836: Apache::lonmeta - display meta data
 1837: 
 1838: =head1 SYNOPSIS
 1839: 
 1840: Handler to display meta data
 1841: 
 1842: This is part of the LearningOnline Network with CAPA project
 1843: described at http://www.lon-capa.org.
 1844: 
 1845: =head1 SUBROUTINES
 1846: 
 1847: =over
 1848: 
 1849: =item &get_dynamic_metadata_from_sql($url) :
 1850: 
 1851: Queries sql database for dynamic metdata
 1852: Returns a hash of hashes, with keys of urls which match $url
 1853: Returned fields are given below.
 1854: 
 1855: Examples:
 1856: 
 1857:     %DynamicMetadata = &Apache::lonmeta::get_dynmaic_metadata_from_sql
 1858:     ('/res/msu/korte/');
 1859: 
 1860:     $DynamicMetadata{'/res/msu/korte/example.problem'}->{$field}
 1861: 
 1862: =item dynamicmeta()
 1863: 
 1864: Fetch and evaluate dynamic metadata
 1865: 
 1866: =item access_count()
 1867: 
 1868: =item alttag()
 1869: 
 1870: Try to make an alt tag if there is none
 1871: 
 1872: =item authordisplay()
 1873: 
 1874: Author display
 1875: 
 1876: =item evalgraph()
 1877: 
 1878: Pretty display
 1879: 
 1880: =item diffgraph()
 1881: 
 1882: =item fieldnames()
 1883: 
 1884: =item portfolio_linked_path()
 1885: 
 1886: =item get_port_path_and_group()
 1887: 
 1888: =item portfolio_display_uri()
 1889: 
 1890: =item pre_select_course()
 1891: 
 1892: =item select_course()
 1893: 
 1894: =item prettyprint()
 1895: 
 1896: Pretty printing of metadata field
 1897: 
 1898: =item direct()
 1899: 
 1900: Pretty input of metadata field
 1901: 
 1902: =item selectbox()
 1903: 
 1904: =item relatedfield()
 1905: 
 1906: =item prettyinput()
 1907: 
 1908: =item report_bombs()
 1909: 
 1910: =item present_uneditable_metadata()
 1911: 
 1912: =item present_editable_metadata()
 1913: 
 1914: =item store_metadata()
 1915: 
 1916: =item store_transferred_addedfields()
 1917: 
 1918: =item store_portfolio_metadata()
 1919: 
 1920: =item update_metadata_table()
 1921: 
 1922: =back
 1923: 
 1924: =cut

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