File:  [LON-CAPA] / loncom / interface / lonmeta.pm
Revision 1.254: download - view: text, annotated - select for diffs
Sun Jun 22 19:46:48 2014 UTC (9 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_X, version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3, version_2_11_2_uiuc, version_2_11_2_msu, version_2_11_2_educog, version_2_11_2, version_2_11_1, version_2_11_0, HEAD
- Bug 6714.
  - "Show Metadata" icon in inline menu launches display of metadata in
  a regular window except for mobile devices which use a modal window.
  - div wrapped around metadata display in modal window and nicescroll
    used so contents are scrollable in mobile Safari on iOS.

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

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