File:  [LON-CAPA] / loncom / publisher / lonpublisher.pm
Revision 1.295.2.1: download - view: text, annotated - select for diffs
Fri Jun 4 15:09:36 2021 UTC (3 years ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4
- For 2.11
  Backport 1.298, 1.299

    1: # The LearningOnline Network with CAPA
    2: # Publication Handler
    3: #
    4: # $Id: lonpublisher.pm,v 1.295.2.1 2021/06/04 15:09:36 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: 
   30: ###############################################################################
   31: ##                                                                           ##
   32: ## ORGANIZATION OF THIS PERL MODULE                                          ##
   33: ##                                                                           ##
   34: ## 1. Modules used by this module                                            ##
   35: ## 2. Various subroutines                                                    ##
   36: ## 3. Publication Step One                                                   ##
   37: ## 4. Phase Two                                                              ##
   38: ## 5. Main Handler                                                           ##
   39: ##                                                                           ##
   40: ###############################################################################
   41: 
   42: 
   43: ######################################################################
   44: ######################################################################
   45: 
   46: =pod 
   47: 
   48: =head1 NAME
   49: 
   50: lonpublisher - LON-CAPA publishing handler
   51: 
   52: =head1 SYNOPSIS
   53: 
   54: B<lonpublisher> is used by B<mod_perl> inside B<Apache>.  This is the
   55: invocation by F<loncapa_apache.conf>:
   56: 
   57:   <Location /adm/publish>
   58:   PerlAccessHandler       Apache::lonacc
   59:   SetHandler perl-script
   60:   PerlHandler Apache::lonpublisher
   61:   ErrorDocument     403 /adm/login
   62:   ErrorDocument     404 /adm/notfound.html
   63:   ErrorDocument     406 /adm/unauthorized.html
   64:   ErrorDocument     500 /adm/errorhandler
   65:   </Location>
   66: 
   67: =head1 OVERVIEW
   68: 
   69: Authors can only write-access the C</priv/domain/authorname/> space. 
   70: They can copy resources into the resource area through the 
   71: publication step, and move them back through a recover step. 
   72: Authors do not have direct write-access to their resource space.
   73: 
   74: During the publication step, several events will be
   75: triggered. Metadata is gathered, where a wizard manages default
   76: entries on a hierarchical per-directory base: The wizard imports the
   77: metadata (including access privileges and royalty information) from
   78: the most recent published resource in the current directory, and if
   79: that is not available, from the next directory above, etc. The Network
   80: keeps all previous versions of a resource and makes them available by
   81: an explicit version number, which is inserted between the file name
   82: and extension, for example C<foo.2.html>, while the most recent
   83: version does not carry a version number (C<foo.html>). Servers
   84: subscribing to a changed resource are notified that a new version is
   85: available.
   86: 
   87: =head1 DESCRIPTION
   88: 
   89: B<lonpublisher> takes the proper steps to add resources to the LON-CAPA
   90: digital library.  This includes updating the metadata table in the
   91: LON-CAPA database.
   92: 
   93: B<lonpublisher> is many things to many people.  
   94: 
   95: This module publishes a file.  This involves gathering metadata,
   96: versioning the file, copying file from construction space to
   97: publication space, and copying metadata from construction space
   98: to publication space.
   99: 
  100: =head2 SUBROUTINES
  101: 
  102: Many of the undocumented subroutines implement various magical
  103: parsing shortcuts.
  104: 
  105: =cut
  106: 
  107: ######################################################################
  108: ######################################################################
  109: 
  110: 
  111: package Apache::lonpublisher;
  112: 
  113: # ------------------------------------------------- modules used by this module
  114: use strict;
  115: use Apache::File;
  116: use File::Copy;
  117: use Apache::Constants qw(:common :http :methods);
  118: use HTML::LCParser;
  119: use HTML::Entities;
  120: use Encode::Encoder;
  121: use Apache::lonxml;
  122: use DBI;
  123: use Apache::lonnet;
  124: use Apache::loncommon();
  125: use Apache::lonhtmlcommon;
  126: use Apache::lonmysql;
  127: use Apache::lonlocal;
  128: use Apache::loncfile;
  129: use LONCAPA::lonmetadata;
  130: use Apache::lonmsg;
  131: use vars qw(%metadatafields %metadatakeys);
  132: use LONCAPA qw(:DEFAULT :match);
  133:  
  134: 
  135: my %addid;
  136: my %nokey;
  137: 
  138: my $docroot;
  139: 
  140: my $cuname;
  141: my $cudom;
  142: 
  143: my $registered_cleanup;
  144: my $modified_urls;
  145: 
  146: my $lock;
  147: 
  148: =pod
  149: 
  150: =over 4
  151: 
  152: =item B<metaeval>
  153: 
  154: Evaluates a string that contains metadata.  This subroutine
  155: stores values inside I<%metadatafields> and I<%metadatakeys>.
  156: The hash key is a I<$unikey> corresponding to a unique id
  157: that is descriptive of the parser location inside the XML tree.
  158: 
  159: Parameters:
  160: 
  161: =over 4
  162: 
  163: =item I<$metastring>
  164: 
  165: A string that contains metadata.
  166: 
  167: =back
  168: 
  169: Returns:
  170: 
  171: nothing
  172: 
  173: =cut
  174: 
  175: #########################################
  176: #########################################
  177: #
  178: # Modifies global %metadatafields %metadatakeys 
  179: #
  180: 
  181: sub metaeval {
  182:     my ($metastring,$prefix)=@_;
  183:    
  184:     my $parser=HTML::LCParser->new(\$metastring);
  185:     my $token;
  186:     while ($token=$parser->get_token) {
  187: 	if ($token->[0] eq 'S') {
  188: 	    my $entry=$token->[1];
  189: 	    my $unikey=$entry;
  190: 	    next if ($entry =~ m/^(?:parameter|stores)_/);
  191: 	    if (defined($token->[2]->{'package'})) { 
  192: 		$unikey.="\0package\0".$token->[2]->{'package'};
  193: 	    } 
  194: 	    if (defined($token->[2]->{'part'})) { 
  195: 		$unikey.="\0".$token->[2]->{'part'}; 
  196: 	    }
  197: 	    if (defined($token->[2]->{'id'})) { 
  198: 		$unikey.="\0".$token->[2]->{'id'};
  199: 	    } 
  200: 	    if (defined($token->[2]->{'name'})) { 
  201: 		$unikey.="\0".$token->[2]->{'name'}; 
  202: 	    }
  203: 	    foreach my $item (@{$token->[3]}) {
  204: 		$metadatafields{$unikey.'.'.$item}=$token->[2]->{$item};
  205: 		if ($metadatakeys{$unikey}) {
  206: 		    $metadatakeys{$unikey}.=','.$item;
  207: 		} else {
  208: 		    $metadatakeys{$unikey}=$item;
  209: 		}
  210: 	    }
  211: 	    my $newentry=$parser->get_text('/'.$entry);
  212: 	    if (($entry eq 'customdistributionfile') ||
  213: 		($entry eq 'sourcerights')) {
  214: 		$newentry=~s/^\s*//;
  215: 		if ($newentry !~m|^/res|) { $newentry=$prefix.$newentry; }
  216: 	    }
  217: # actually store
  218: 	    if ( $entry eq 'rule' && exists($metadatafields{$unikey})) {
  219: 		$metadatafields{$unikey}.=','.$newentry;
  220: 	    } else {
  221: 		$metadatafields{$unikey}=$newentry;
  222: 	    }
  223: 	}
  224:     }
  225: }
  226: 
  227: #########################################
  228: #########################################
  229: 
  230: =pod
  231: 
  232: =item B<metaread>
  233: 
  234: Read a metadata file
  235: 
  236: Parameters:
  237: 
  238: =over
  239: 
  240: =item I<$logfile>
  241: 
  242: File output stream to output errors and warnings to.
  243: 
  244: =item I<$fn>
  245: 
  246: File name (including path).
  247: 
  248: =back
  249: 
  250: Returns:
  251: 
  252: =over 4
  253: 
  254: =item Scalar string (if successful)
  255: 
  256: XHTML text that indicates successful reading of the metadata.
  257: 
  258: =back
  259: 
  260: =cut
  261: 
  262: #########################################
  263: #########################################
  264: sub metaread {
  265:     my ($logfile,$fn,$prefix)=@_;
  266:     unless (-e $fn) {
  267: 	print($logfile 'No file '.$fn."\n");
  268:         return '<p class="LC_warning">'
  269:               .&mt('No file: [_1]',&Apache::loncfile::display($fn))
  270:               .'</p>';
  271:     }
  272:     print($logfile 'Processing '.$fn."\n");
  273:     my $metastring;
  274:     {
  275: 	my $metafh=Apache::File->new($fn);
  276: 	$metastring=join('',<$metafh>);
  277:     }
  278:     &metaeval($metastring,$prefix);
  279:     return '<p class="LC_info">'
  280:           .&mt('Processed file: [_1]',&Apache::loncfile::display($fn))
  281:           .'</p>';
  282: }
  283: 
  284: #########################################
  285: #########################################
  286: 
  287: sub coursedependencies {
  288:     my $url=&Apache::lonnet::declutter(shift);
  289:     $url=~s/\.meta$//;
  290:     my ($adomain,$aauthor)=($url=~ m{^($match_domain)/($match_username)/});
  291:     my $regexp=quotemeta($url);
  292:     $regexp='___'.$regexp.'___course';
  293:     my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
  294: 				       $aauthor,$regexp);
  295:     my %courses=();
  296:     foreach my $item (keys(%evaldata)) {
  297: 	if ($item=~/^([a-zA-Z0-9]+_[a-zA-Z0-9]+)___.+___course$/) {
  298: 	    $courses{$1}=1;
  299:         }
  300:     }
  301:     return %courses;
  302: }
  303: #########################################
  304: #########################################
  305: 
  306: 
  307: =pod
  308: 
  309: =item Form-field-generating subroutines.
  310: 
  311: For input parameters, these subroutines take in values
  312: such as I<$name>, I<$value> and other form field metadata.
  313: The output (scalar string that is returned) is an XHTML
  314: string which presents the form field (foreseeably inside
  315: <form></form> tags).
  316: 
  317: =over 4
  318: 
  319: =item B<textfield>
  320: 
  321: =item B<text_with_browse_field>
  322: 
  323: =item B<hiddenfield>
  324: 
  325: =item B<checkbox>
  326: 
  327: =item B<selectbox>
  328: 
  329: =back
  330: 
  331: =cut
  332: 
  333: #########################################
  334: #########################################
  335: sub textfield {
  336:     my ($title,$name,$value,$noline)=@_;
  337:     $value=~s/^\s+//gs;
  338:     $value=~s/\s+$//gs;
  339:     $value=~s/\s+/ /gs;
  340:     $title=&mt($title);
  341:     $env{'form.'.$name}=$value;
  342:     return "\n".&Apache::lonhtmlcommon::row_title($title)
  343:            .'<input type="text" name="'.$name.'" size="80" value="'.$value.'" />'
  344:            .&Apache::lonhtmlcommon::row_closure($noline);
  345: }
  346: 
  347: sub text_with_browse_field {
  348:     my ($title,$name,$value,$restriction,$noline)=@_;
  349:     $value=~s/^\s+//gs;
  350:     $value=~s/\s+$//gs;
  351:     $value=~s/\s+/ /gs;
  352:     $title=&mt($title);
  353:     $env{'form.'.$name}=$value;
  354:     return "\n".&Apache::lonhtmlcommon::row_title($title)
  355:           .'<input type="text" name="'.$name.'" size="80" value="'.$value.'" />'
  356:           .'<br />'
  357: 	  .'<a href="javascript:openbrowser(\'pubform\',\''.$name.'\',\''.$restriction.'\');">'
  358:           .&mt('Select')
  359:           .'</a>&nbsp;'
  360: 	  .'<a href="javascript:opensearcher(\'pubform\',\''.$name.'\');">'
  361:           .&mt('Search')
  362:           .'</a>'
  363:           .&Apache::lonhtmlcommon::row_closure($noline);
  364: }
  365: 
  366: sub hiddenfield {
  367:     my ($name,$value)=@_;
  368:     $env{'form.'.$name}=$value;
  369:     return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
  370: }
  371: 
  372: sub checkbox {
  373:     my ($name,$text)=@_;
  374:     return "\n<label><input type='checkbox' name='$name' /> ".
  375: 	&mt($text)."</label>";
  376: }
  377: 
  378: sub selectbox {
  379:     my ($title,$name,$value,$functionref,@idlist)=@_;
  380:     $title=&mt($title);
  381:     $value=(split(/\s*,\s*/,$value))[-1];
  382:     if (defined($value)) {
  383: 	$env{'form.'.$name}=$value;
  384:     } else {
  385: 	$env{'form.'.$name}=$idlist[0];
  386:     }
  387:     my $selout="\n".&Apache::lonhtmlcommon::row_title($title)
  388:               .'<select name="'.$name.'">';
  389:     foreach my $id (@idlist) {
  390:         $selout.='<option value="'.$id.'"';
  391:         if ($id eq $value) {
  392: 	    $selout.=' selected="selected"';
  393:         }
  394:         $selout.='>'.&{$functionref}($id).'</option>';
  395:     }
  396:     $selout.='</select>'.&Apache::lonhtmlcommon::row_closure();
  397:     return $selout;
  398: }
  399: 
  400: sub select_level_form {
  401:     my ($value,$name)=@_;
  402:     $env{'form.'.$name}=$value;
  403:     if (!defined($value)) { $env{'form.'.$name}=0; }
  404:     return  &Apache::loncommon::select_level_form($value,$name);
  405: }
  406: 
  407: sub common_access {
  408:     my ($name,$text,$options)=@_;
  409:     return unless (ref($options) eq 'ARRAY');
  410:     my $formname = 'pubdirpref';
  411:     my $chkname = 'common'.$name;
  412:     my $chkid = 'LC_'.$chkname;
  413:     my $divid = $chkid.'div';
  414:     my $customdivid = 'LC_customfile'; 
  415:     my $selname = $chkname.'select';
  416:     my $selid = $chkid.'select';
  417:     my $selonchange;
  418:     if ($name eq 'dist') {
  419:         $selonchange = ' onchange="showHideCustom(this,'."'$customdivid'".');"';
  420:     }
  421:     my %lt = &Apache::lonlocal::texthash(
  422:                                             'default' => 'System wide - can be used for any courses system wide',
  423:                                             'domain'  => 'Domain only - use limited to courses in the domai',
  424:                                             'custom'  => 'Customized right of use ...',
  425:                                             'public'  => 'Public - no authentication or authorization required for use',
  426:                                             'closed'  => 'Closed - XML source is closed to everyone',
  427:                                             'open'    => 'Open - XML source is open to people who want to use it',
  428:                                             'sel'     => 'Select',
  429:                                         );
  430:     my $output = <<"END";
  431: <span class="LC_nobreak">
  432: <label>
  433: <input type="checkbox" name="commonaccess" value="$name" id="$chkid"  
  434: onclick="showHideAccess(this,'$divid');" />
  435: $text</label></span>
  436: <div id="$divid" style="padding:0;clear:both;margin:0;border:0;display:none">
  437: <select name="$selname" id="$selid" $selonchange>
  438: <option value="" selected="selected">$lt{'sel'}</option>
  439: END
  440:     foreach my $val (@{$options}) {
  441:         $output .= '<option value="'.$val.'">'.$lt{$val}.'</option>'."\n";
  442:     }
  443:     $output .= '
  444: </select>';
  445:     if ($name eq 'dist') {
  446:         $output .= <<"END";
  447: <div id="$customdivid" style="padding:0;clear:both;margin:0;border:0;display:none">
  448: <input type="text" name="commoncustomrights" size="60" value="" />
  449: <a href="javascript:openbrowser('$formname','commoncustomrights','rights');">
  450: $lt{'sel'}</a></div>
  451: END
  452:     }
  453:     $output .= '
  454: </div>
  455: ';
  456: }
  457: 
  458: #########################################
  459: #########################################
  460: 
  461: =pod
  462: 
  463: =item B<urlfixup>
  464: 
  465: Fix up a url?  First step of publication
  466: 
  467: =cut
  468: 
  469: #########################################
  470: #########################################
  471: sub urlfixup {
  472:     my ($url,$target)=@_;
  473:     unless ($url) { return ''; }
  474:     #javascript code needs no fixing
  475:     if ($url =~ /^javascript:/i) { return $url; }
  476:     if ($url =~ /^mailto:/i) { return $url; }
  477:     #internal document links need no fixing
  478:     if ($url =~ /^\#/) { return $url; } 
  479:     my ($host)=($url=~m{(?:(?:http|https|ftp)://)*([^/]+)});
  480:     my @lonids = &Apache::lonnet::machine_ids($host);
  481:     if (@lonids) {
  482: 	$url=~s{^(?:http|https|ftp)://}{};
  483: 	$url=~s/^\Q$host\E//;
  484:     }
  485:     if ($url=~m{^(?:http|https|ftp)://}) { return $url; }
  486:     $url=~s{\Q~$cuname\E}{res/$cudom/$cuname};
  487:     return $url;
  488: }
  489: 
  490: #########################################
  491: #########################################
  492: 
  493: =pod
  494: 
  495: =item B<absoluteurl>
  496: 
  497: Currently undocumented.
  498: 
  499: =cut
  500: 
  501: #########################################
  502: #########################################
  503: sub absoluteurl {
  504:     my ($url,$target)=@_;
  505:     unless ($url) { return ''; }
  506:     if ($target) {
  507: 	$target=~s/\/[^\/]+$//;
  508:        $url=&Apache::lonnet::hreflocation($target,$url);
  509:     }
  510:     return $url;
  511: }
  512: 
  513: #########################################
  514: #########################################
  515: 
  516: =pod
  517: 
  518: =item B<set_allow>
  519: 
  520: Currently undocumented    
  521: 
  522: =cut
  523: 
  524: #########################################
  525: #########################################
  526: sub set_allow {
  527:     my ($allow,$logfile,$target,$tag,$oldurl,$type)=@_;
  528:     my $newurl=&urlfixup($oldurl,$target);
  529:     my $return_url=$oldurl;
  530:     print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
  531:     if ($newurl ne $oldurl) {
  532: 	$return_url=$newurl;
  533: 	print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
  534:     }
  535:     if (($newurl !~ /^javascript:/i) &&
  536: 	($newurl !~ /^mailto:/i) &&
  537: 	($newurl !~ /^(?:http|https|ftp):/i) &&
  538: 	($newurl !~ /^\#/)) {
  539:         if (($type eq 'src') || ($type eq 'href')) {
  540:             if ($newurl =~ /^([^?]+)\?[^?]*$/) {
  541:                 $newurl = $1;
  542:             }
  543:         }
  544: 	$$allow{&absoluteurl($newurl,$target)}=1;
  545:     }
  546:     return $return_url;
  547: }
  548: 
  549: #########################################
  550: #########################################
  551: 
  552: =pod
  553: 
  554: =item B<get_subscribed_hosts>
  555: 
  556: Currently undocumented    
  557: 
  558: =cut
  559: 
  560: #########################################
  561: #########################################
  562: sub get_subscribed_hosts {
  563:     my ($target)=@_;
  564:     my @subscribed;
  565:     my $filename;
  566:     $target=~/(.*)\/([^\/]+)$/;
  567:     my $srcf=$2;
  568:     opendir(DIR,$1);
  569:     # cycle through listed files, subscriptions used to exist
  570:     # as "filename.lonid"
  571:     while ($filename=readdir(DIR)) {
  572: 	if ($filename=~/\Q$srcf\E\.($match_lonid)$/) {
  573: 	    my $subhost=$1;
  574: 	    if (($subhost ne 'meta' 
  575: 		 && $subhost ne 'subscription' 
  576: 		 && $subhost ne 'meta.subscription'
  577: 		 && $subhost ne 'tmp') &&
  578:                 ($subhost ne $Apache::lonnet::perlvar{'lonHostID'})) {
  579: 		push(@subscribed,$subhost);
  580: 	    }
  581: 	}
  582:     }
  583:     closedir(DIR);
  584:     my $sh;
  585:     if ( $sh=Apache::File->new("$target.subscription") ) {
  586: 	while (my $subline=<$sh>) {
  587: 	    if ($subline =~ /^($match_lonid):/) { 
  588:                 if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) { 
  589:                    push(@subscribed,$1);
  590: 	        }
  591: 	    }
  592: 	}
  593:     }
  594:     return @subscribed;
  595: }
  596: 
  597: 
  598: #########################################
  599: #########################################
  600: 
  601: =pod
  602: 
  603: =item B<get_max_ids_indices>
  604: 
  605: Currently undocumented    
  606: 
  607: =cut
  608: 
  609: #########################################
  610: #########################################
  611: sub get_max_ids_indices {
  612:     my ($content)=@_;
  613:     my $maxindex=10;
  614:     my $maxid=10;
  615:     my $needsfixup=0;
  616:     my $duplicateids=0;
  617: 
  618:     my %allids;
  619:     my %duplicatedids;
  620: 
  621:     my $parser=HTML::LCParser->new($content);
  622:     $parser->xml_mode(1);
  623:     my $token;
  624:     while ($token=$parser->get_token) {
  625: 	if ($token->[0] eq 'S') {
  626: 	    my $counter;
  627: 	    if ($counter=$addid{$token->[1]}) {
  628: 		if ($counter eq 'id') {
  629: 		    if (defined($token->[2]->{'id'}) &&
  630: 			$token->[2]->{'id'} !~ /^\s*$/) {
  631: 			$maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
  632: 			if (exists($allids{$token->[2]->{'id'}})) {
  633: 			    $duplicateids=1;
  634: 			    $duplicatedids{$token->[2]->{'id'}}=1;
  635: 			} else {
  636: 			    $allids{$token->[2]->{'id'}}=1;
  637: 			}
  638: 		    } else {
  639: 			$needsfixup=1;
  640: 		    }
  641: 		} else {
  642: 		    if (defined($token->[2]->{'index'}) &&
  643: 			$token->[2]->{'index'} !~ /^\s*$/) {
  644: 			$maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
  645: 		    } else {
  646: 			$needsfixup=1;
  647: 		    }
  648: 		}
  649: 	    }
  650: 	}
  651:     }
  652:     return ($needsfixup,$maxid,$maxindex,$duplicateids,
  653: 	    (keys(%duplicatedids)));
  654: }
  655: 
  656: #########################################
  657: #########################################
  658: 
  659: =pod
  660: 
  661: =item B<get_all_text_unbalanced>
  662: 
  663: Currently undocumented    
  664: 
  665: =cut
  666: 
  667: #########################################
  668: #########################################
  669: sub get_all_text_unbalanced {
  670:     #there is a copy of this in lonxml.pm
  671:     my($tag,$pars)= @_;
  672:     my $token;
  673:     my $result='';
  674:     $tag='<'.$tag.'>';
  675:     while ($token = $$pars[-1]->get_token) {
  676: 	if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
  677: 	    $result.=$token->[1];
  678: 	} elsif ($token->[0] eq 'PI') {
  679: 	    $result.=$token->[2];
  680: 	} elsif ($token->[0] eq 'S') {
  681: 	    $result.=$token->[4];
  682: 	} elsif ($token->[0] eq 'E')  {
  683: 	    $result.=$token->[2];
  684: 	}
  685: 	if ($result =~ /\Q$tag\E/s) {
  686: 	    ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
  687: 	    #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
  688: 	    #&Apache::lonnet::logthis('Result is :'.$1);
  689: 	    $redo=$tag.$redo;
  690: 	    push (@$pars,HTML::LCParser->new(\$redo));
  691: 	    $$pars[-1]->xml_mode('1');
  692: 	    last;
  693: 	}
  694:     }
  695:     return $result
  696: }
  697: 
  698: #########################################
  699: #########################################
  700: 
  701: =pod
  702: 
  703: =item B<fix_ids_and_indices>
  704: 
  705: Currently undocumented    
  706: 
  707: =cut
  708: 
  709: #########################################
  710: #########################################
  711: #Arguably this should all be done as a lonnet::ssi instead
  712: sub fix_ids_and_indices {
  713:     my ($logfile,$source,$target)=@_;
  714: 
  715:     my %allow;
  716:     my $content;
  717:     {
  718: 	my $org=Apache::File->new($source);
  719: 	$content=join('',<$org>);
  720:     }
  721: 
  722:     my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
  723: 	&get_max_ids_indices(\$content);
  724: 
  725:     print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
  726: 			   join(', ',@duplicatedids));
  727:     if ($duplicateids) {
  728: 	print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
  729: 	my $outstring='<span class="LC_error">'.&mt('Unable to publish file, it contains duplicated ID(s), ID(s) need to be unique. The duplicated ID(s) are').': '.join(', ',@duplicatedids).'</span>';
  730: 	return ($outstring,1);
  731:     }
  732:     if ($needsfixup) {
  733: 	print $logfile "Needs ID and/or index fixup\n".
  734: 	    "Max ID   : $maxid (min 10)\n".
  735:                 "Max Index: $maxindex (min 10)\n";
  736:     }
  737:     my $outstring='';
  738:     my $responsecounter=1;
  739:     my @parser;
  740:     $parser[0]=HTML::LCParser->new(\$content);
  741:     $parser[-1]->xml_mode(1);
  742:     my $token;
  743:     while (@parser) {
  744: 	while ($token=$parser[-1]->get_token) {
  745: 	    if ($token->[0] eq 'S') {
  746: 		my $counter;
  747: 		my $tag=$token->[1];
  748: 		my $lctag=lc($tag);
  749: 		if ($lctag eq 'allow') {
  750: 		    $allow{$token->[2]->{'src'}}=1;
  751: 		    next;
  752: 		}
  753: 		if ($lctag eq 'base') { next; }
  754:                 if (($lctag eq 'part') || ($lctag eq 'problem')) {
  755:                     $responsecounter=0;
  756:                 }
  757:                 if ($lctag=~/response$/) { $responsecounter++; }
  758:                 if ($lctag eq 'import') { $responsecounter++; }
  759: 		my %parms=%{$token->[2]};
  760: 		$counter=$addid{$tag};
  761: 		if (!$counter) { $counter=$addid{$lctag}; }
  762: 		if ($counter) {
  763: 		    if ($counter eq 'id') {
  764: 			unless (defined($parms{'id'}) &&
  765: 				$parms{'id'}!~/^\s*$/) {
  766: 			    $maxid++;
  767: 			    $parms{'id'}=$maxid;
  768: 			    print $logfile 'ID(new) : '.$tag.':'.$maxid."\n";
  769: 			} else {
  770: 			    print $logfile 'ID(kept): '.$tag.':'.$parms{'id'}."\n";
  771: 			}
  772: 		    } elsif ($counter eq 'index') {
  773: 			unless (defined($parms{'index'}) &&
  774: 				$parms{'index'}!~/^\s*$/) {
  775: 			    $maxindex++;
  776: 			    $parms{'index'}=$maxindex;
  777: 			    print $logfile 'Index: '.$tag.':'.$maxindex."\n";
  778: 			}
  779: 		    }
  780: 		}
  781:                 unless ($parms{'type'} eq 'zombie') {
  782: 		    foreach my $type ('src','href','background','bgimg') {
  783: 			foreach my $key (keys(%parms)) {
  784: 			    if ($key =~ /^$type$/i) {
  785:                                 next if (($lctag eq 'img') && ($type eq 'src') && 
  786:                                          ($parms{$key} =~ m{^data\:image/gif;base64,}));
  787: 				$parms{$key}=&set_allow(\%allow,$logfile,
  788: 							$target,$tag,
  789: 							$parms{$key},$type);
  790: 			    }
  791: 			}
  792: 		    }
  793: 		}
  794: 		# probably a <randomlabel> image type <label>
  795: 		# or a <image> tag inside <imageresponse>
  796: 		if (($lctag eq 'label' && defined($parms{'description'}))
  797: 		    ||
  798: 		    ($lctag eq 'image')) {
  799: 		    my $next_token=$parser[-1]->get_token();
  800: 		    if ($next_token->[0] eq 'T') {
  801:                         $next_token->[1] =~ s/[\n\r\f]+//g;
  802: 			$next_token->[1]=&set_allow(\%allow,$logfile,
  803: 						    $target,$tag,
  804: 						    $next_token->[1]);
  805: 		    }
  806: 		    $parser[-1]->unget_token($next_token);
  807: 		}
  808: 		if ($lctag eq 'applet') {
  809: 		    my $codebase='';
  810: 		    my $havecodebase=0;
  811: 		    foreach my $key (keys(%parms)) {
  812: 			if (lc($key) eq 'codebase') { 
  813: 			    $codebase=$parms{$key};
  814: 			    $havecodebase=1; 
  815: 			}
  816: 		    }
  817: 		    if ($havecodebase) {
  818: 			my $oldcodebase=$codebase;
  819: 			unless ($oldcodebase=~/\/$/) {
  820: 			    $oldcodebase.='/';
  821: 			}
  822: 			$codebase=&urlfixup($oldcodebase,$target);
  823: 			$codebase=~s/\/$//;    
  824: 			if ($codebase ne $oldcodebase) {
  825: 			    $parms{'codebase'}=$codebase;
  826: 			    print $logfile 'URL codebase: '.$tag.':'.
  827: 				$oldcodebase.' - '.
  828: 				    $codebase."\n";
  829: 			}
  830: 			$allow{&absoluteurl($codebase,$target).'/*'}=1;
  831: 		    } else {
  832: 			foreach my $key (keys(%parms)) {
  833: 			    if ($key =~ /(archive|code|object)/i) {
  834: 				my $oldurl=$parms{$key};
  835: 				my $newurl=&urlfixup($oldurl,$target);
  836: 				$newurl=~s/\/[^\/]+$/\/\*/;
  837: 				print $logfile 'Allow: applet '.lc($key).':'.
  838: 				    $oldurl.' allows '.$newurl."\n";
  839: 				$allow{&absoluteurl($newurl,$target)}=1;
  840: 			    }
  841: 			}
  842: 		    }
  843: 		}
  844: 		my $newparmstring='';
  845: 		my $endtag='';
  846: 		foreach my $parkey (keys(%parms)) {
  847: 		    if ($parkey eq '/') {
  848: 			$endtag=' /';
  849: 		    } else { 
  850: 			my $quote=($parms{$parkey}=~/\"/?"'":'"');
  851: 			$newparmstring.=' '.$parkey.'='.$quote.$parms{$parkey}.$quote;
  852: 		    }
  853: 		}
  854: 		if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
  855: 		$outstring.='<'.$tag.$newparmstring.$endtag.'>';
  856: 		if ($lctag eq 'm' || $lctag eq 'answer' || $lctag eq 'display' ||
  857:                     $lctag eq 'tex') {
  858: 		    $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
  859:                 } elsif ($lctag eq 'script') {
  860:                     if ($parms{'type'} eq 'loncapa/perl') {
  861:                         $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
  862:                     } else {
  863:                         my $script = &get_all_text_unbalanced('/'.$lctag,\@parser);
  864:                         if ($script =~ m{\.set\w+(Src|Swf)\(["']}i) {
  865:                             my @srcs = split(/\.set/i,$script);
  866:                             if (scalar(@srcs) > 1) {
  867:                                 foreach my $item (@srcs) {
  868:                                     if ($item =~ m{^(FlashPlayerSwf|MediaSrc|XMPSrc|ConfigurationSrc|PosterImageSrc)\((['"])(?:(?!\2).)+\2\)}is) {
  869:                                         my $srctype = $1;
  870:                                         my $quote = $2;
  871:                                         my ($url) = ($item =~ m{^\Q$srctype($quote\E([^$quote]+)\Q$quote)\E});
  872:                                         $url = &urlfixup($url);
  873:                                         unless ($url=~m{^(?:http|https|ftp)://}) {
  874:                                             $allow{&absoluteurl($url,$target)}=1;
  875:                                             if ($srctype eq 'ConfigurationSrc') {
  876:                                                 if ($url =~ m{^(.+/)configuration_express\.xml$}) {
  877: #
  878: # Camtasia 8.1: express_show/spritesheet.png needed, and included in zip archive.
  879: # Not referenced directly in <main>.html or <main>_player.html files,
  880: # so add this file to %allow (where <main> is name user gave to file/archive).
  881: #
  882:                                                     my $spritesheet = $1.'express_show/spritesheet.png';
  883:                                                     $allow{&absoluteurl($spritesheet,$target)}=1;
  884: 
  885: #
  886: # Camtasia 8.4: skins/express_show/spritesheet.min.css needed, and included in zip archive.
  887: # Not referenced directly in <main>.html or <main>_player.html files,
  888: # so add this file to %allow (where <main> is name user gave to file/archive).
  889: #
  890:                                                     my $spritecss = $1.'express_show/spritesheet.min.css';
  891:                                                     $allow{&absoluteurl($spritecss,$target)}=1;
  892:                                                 }
  893:                                             } elsif ($srctype eq 'PosterImageSrc') {
  894:                                                 if ($url =~ m{^(.+)_First_Frame\.png$}) {
  895:                                                     my $prefix = $1;
  896: #
  897: # Camtasia 8.1: <main>_Thumbnails.png needed, and included in zip archive.
  898: # Not referenced directly in <main>.html or <main>_player.html files,
  899: # so add this file to %allow (where <main> is name user gave to file/archive).
  900: #
  901:                                                     my $thumbnail = $prefix.'_Thumbnails.png';
  902:                                                     $allow{&absoluteurl($thumbnail,$target)}=1;
  903:                                                 }
  904:                                             }
  905:                                         }
  906:                                     }
  907:                                 }
  908:                             }
  909:                         }
  910:                         if ($script =~ m{\.addMediaSrc\((["'])((?!\1).+)\1\);}) {
  911:                             my $src = $2;
  912:                             if ($src) {
  913:                                 my $url = &urlfixup($src);
  914:                                 unless ($url=~m{^(?:http|https|ftp)://}) {
  915:                                     $allow{&absoluteurl($url,$target)}=1;
  916:                                 }
  917:                             }
  918:                         }
  919:                         if ($script =~ /\(document,\s*(['"])script\1,\s*\[([^\]]+)\]\);/s) {
  920:                             my $scriptslist = $2;
  921:                             my @srcs = split(/\s*,\s*/,$scriptslist);
  922:                             foreach my $src (@srcs) {
  923:                                 if ($src =~ /(["'])(?:(?!\1).)+\.js\1/) {
  924:                                     my $quote = $1;
  925:                                     my ($url) = ($src =~ m/\Q$quote\E([^$quote]+)\Q$quote\E/);
  926:                                     $url = &urlfixup($url);
  927:                                     unless ($url=~m{^(?:http|https|ftp)://}) {
  928:                                         $allow{&absoluteurl($url,$target)}=1;
  929:                                     }
  930:                                 }
  931:                             }
  932:                         }
  933:                         if ($script =~ m{loadScript\(\s*(['"])((?:(?!\1).)+\.js)\1,\s*function}is) {
  934:                             my $src = $2;
  935:                             if ($src) {
  936:                                 my $url = &urlfixup($src);
  937:                                 unless ($url=~m{^(?:http|https|ftp)://}) {
  938:                                     $allow{&absoluteurl($url,$target)}=1;
  939:                                 }
  940:                             }
  941:                         }
  942:                         $outstring .= $script;
  943:                     }
  944:                 }
  945: 	    } elsif ($token->[0] eq 'E') {
  946: 		if ($token->[2]) {
  947: 		    unless ($token->[1] eq 'allow') {
  948: 			$outstring.='</'.$token->[1].'>';
  949: 		    }
  950:                 }
  951:                 if ((($token->[1] eq 'part') || ($token->[1] eq 'problem'))
  952:                     && (!$responsecounter)) {
  953:                     my $outstring='<span class="LC_error">'.&mt('Found [_1] without responses. This resource cannot be published.',$token->[1]).'</span>';
  954:                     return ($outstring,1);
  955:                 }
  956: 	    } else {
  957: 		$outstring.=$token->[1];
  958: 	    }
  959: 	}
  960: 	pop(@parser);
  961:     }
  962: 
  963:     if ($needsfixup) {
  964: 	print $logfile "End of ID and/or index fixup\n".
  965: 	    "Max ID   : $maxid (min 10)\n".
  966: 		"Max Index: $maxindex (min 10)\n";
  967:     } else {
  968: 	print $logfile "Does not need ID and/or index fixup\n";
  969:     }
  970: 
  971:     return ($outstring,0,%allow);
  972: }
  973: 
  974: #########################################
  975: #########################################
  976: 
  977: =pod
  978: 
  979: =item B<store_metadata>
  980: 
  981: Store the metadata in the metadata table in the loncapa database.
  982: Uses lonmysql to access the database.
  983: 
  984: Inputs: \%metadata
  985: 
  986: Returns: (error,status).  error is undef on success, status is undef on error.
  987: 
  988: =cut
  989: 
  990: #########################################
  991: #########################################
  992: sub store_metadata {
  993:     my %metadata = @_;
  994:     my $error;
  995:     # Determine if the table exists
  996:     my $status = &Apache::lonmysql::check_table('metadata');
  997:     if (! defined($status)) {
  998:         $error='<span class="LC_error">'
  999:               .&mt('WARNING: Cannot connect to database!')
 1000:               .'</span>';
 1001:         &Apache::lonnet::logthis($error);
 1002:         return ($error,undef);
 1003:     }
 1004:     if ($status == 0) {
 1005:         # It would be nice to actually create the table....
 1006:         $error ='<span class="LC_error">'
 1007:                .&mt('WARNING: The metadata table does not exist in the LON-CAPA database!')
 1008:                .'</span>';
 1009:         &Apache::lonnet::logthis($error);
 1010:         return ($error,undef);
 1011:     }
 1012:     my $dbh = &Apache::lonmysql::get_dbh();
 1013:     if (($metadata{'obsolete'}) || ($metadata{'copyright'} eq 'priv')) {
 1014:         # remove this entry
 1015: 	my $delitem = 'url = '.$dbh->quote($metadata{'url'});
 1016: 	$status = &LONCAPA::lonmetadata::delete_metadata($dbh,undef,$delitem);
 1017:                                                        
 1018:     } else {
 1019:         $status = &LONCAPA::lonmetadata::update_metadata($dbh,undef,undef,
 1020:                                                          \%metadata);
 1021:     }
 1022:     if (defined($status) && $status ne '') {
 1023:         $error='<span class="LC_error">'
 1024:               .&mt('Error occurred saving new values in metadata table in LON-CAPA database!')
 1025:               .'</span>';
 1026:         &Apache::lonnet::logthis($error);
 1027:         &Apache::lonnet::logthis($status);
 1028:         return ($error,undef);
 1029:     }
 1030:     return (undef,'success');
 1031: }
 1032: 
 1033: 
 1034: # ========================================== Parse file for errors and warnings
 1035: 
 1036: sub checkonthis {
 1037:     my ($r,$source)=@_;
 1038:     my $uri=&Apache::lonnet::hreflocation($source);
 1039:     $uri=~s/\/$//;
 1040:     my $result=&Apache::lonnet::ssi_body($uri,
 1041: 					 ('grade_target'=>'web',
 1042: 					  'return_only_error_and_warning_counts' => 1));
 1043:     my ($errorcount,$warningcount)=split(':',$result);
 1044:     if (($errorcount) || ($warningcount)) {
 1045:         $r->print('<h3>'.&mt('Warnings and Errors').'</h3>');
 1046:         $r->print('<tt>'.$uri.'</tt>:');
 1047:         $r->print('<ul>');
 1048:         if ($warningcount) {
 1049:             $r->print('<li><div class="LC_warning">'
 1050:                      .&mt('[quant,_1,warning]',$warningcount)
 1051:                      .'</div></li>');
 1052:         }
 1053:         if ($errorcount) {
 1054:             $r->print('<li><div class="LC_error">'
 1055:                      .&mt('[quant,_1,error]',$errorcount)
 1056:                      .' <img src="/adm/lonMisc/bomb.gif" />'
 1057:                      .'</div></li>');
 1058:         }
 1059:         $r->print('</ul>');
 1060:     } else {
 1061: 	#$r->print('<font color="green">'.&mt('ok').'</font>');
 1062:     }
 1063:     $r->rflush();
 1064:     return ($warningcount,$errorcount);
 1065: }
 1066: 
 1067: # ============================================== Parse file itself for metadata
 1068: #
 1069: # parses a file with target meta, sets global %metadatafields %metadatakeys 
 1070: 
 1071: sub parseformeta {
 1072:     my ($source,$style)=@_;
 1073:     my $allmeta='';
 1074:     if (($style eq 'ssi') || ($style eq 'prv')) {
 1075: 	my $dir=$source;
 1076: 	$dir=~s-/[^/]*$--;
 1077: 	my $file=$source;
 1078: 	$file=(split('/',$file))[-1];
 1079:         $source=&Apache::lonnet::hreflocation($dir,$file);
 1080: 	$allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
 1081:         &metaeval($allmeta);
 1082:     }
 1083:     return $allmeta;
 1084: }
 1085: 
 1086: #########################################
 1087: #########################################
 1088: 
 1089: =pod
 1090: 
 1091: =item B<publish>
 1092: 
 1093: This is the workhorse function of this module.  This subroutine generates
 1094: backup copies, performs any automatic processing (prior to publication,
 1095: especially for rat and ssi files),
 1096: 
 1097: Returns a 2 element array, the first is the string to be shown to the
 1098: user, the second is an error code, either 1 (an error occurred) or 0
 1099: (no error occurred)
 1100: 
 1101: I<Additional documentation needed.>
 1102: 
 1103: =cut
 1104: 
 1105: #########################################
 1106: #########################################
 1107: sub publish {
 1108: 
 1109:     my ($source,$target,$style,$batch)=@_;
 1110:     my $logfile;
 1111:     my $scrout='';
 1112:     my $allmeta='';
 1113:     my $content='';
 1114:     my %allow=();
 1115: 
 1116:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
 1117: 	return ('<span class="LC_error">'.&mt('No write permission to user directory, FAIL').'</span>',1);
 1118:     }
 1119:     print $logfile 
 1120: "\n\n================= Publish ".localtime()." Phase One  ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
 1121: 
 1122:     if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
 1123: # ------------------------------------------------------- This needs processing
 1124: 
 1125: # ----------------------------------------------------------------- Backup Copy
 1126: 	my $copyfile=$source.'.save';
 1127:         if (copy($source,$copyfile)) {
 1128: 	    print $logfile "Copied original file to ".$copyfile."\n";
 1129:         } else {
 1130: 	    print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
 1131: 	    return ("<span class=\"LC_error\">".&mt("Failed to write backup copy, [_1], FAIL",$1)."</span>",1);
 1132:         }
 1133: # ------------------------------------------------------------- IDs and indices
 1134: 	
 1135: 	my ($outstring,$error);
 1136: 	($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
 1137: 							$target);
 1138: 	if ($error) { return ($outstring,$error); }
 1139: # ------------------------------------------------------------ Construct Allows
 1140:     
 1141:         my $outdep=''; # Collect dependencies output data
 1142:         my $allowstr='';
 1143:         foreach my $thisdep (sort(keys(%allow))) {
 1144: 	   if ($thisdep !~ /[^\s]/) { next; }
 1145:            if ($thisdep =~/\$/) {
 1146:               $outdep.='<div class="LC_warning">'
 1147:                        .&mt('The resource depends on another resource with variable filename, i.e., [_1].','<tt>'.$thisdep.'</tt>').'<br />'
 1148:                        .&mt('You likely need to explicitly allow access to all possible dependencies using the [_1]-tag.','<tt>&lt;allow&gt;</tt>')
 1149:                        ."</div>\n";
 1150:            }
 1151:            unless ($style eq 'rat') { 
 1152:               $allowstr.="\n".'<allow src="'.$thisdep.'" />';
 1153: 	   }
 1154:           $outdep.='<div>';
 1155:            if ($thisdep!~/[\*\$]/ && $thisdep!~m|^/adm/|) {
 1156: 	       $outdep.='<a href="'.$thisdep.'">';
 1157:            }
 1158:            $outdep.='<tt>'.$thisdep.'</tt>';
 1159:            if ($thisdep!~/[\*\$]/ && $thisdep!~m|^/adm/|) {
 1160: 	       $outdep.='</a>';
 1161:                if (
 1162:        &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 1163:                                             $thisdep.'.meta') eq '-1') {
 1164: 		   $outdep.= ' - <span class="LC_error">'.&mt('Currently not available').
 1165: 		       '</span>';
 1166:                } else {
 1167: #
 1168: # Store the fact that the dependency has been used by the target file
 1169: # Unfortunately, usage is erroneously named sequsage in lonmeta.pm
 1170: # The translation happens in lonmetadata.pm
 1171: #
 1172:                    my %temphash=(&Apache::lonnet::declutter($target).'___'.
 1173:                              &Apache::lonnet::declutter($thisdep).'___usage'
 1174:                                  => time);
 1175:                    $thisdep=~m{^/res/($match_domain)/($match_username)/};
 1176:                    if ((defined($1)) && (defined($2))) {
 1177:                       &Apache::lonnet::put('nohist_resevaldata',\%temphash,
 1178: 					   $1,$2);
 1179: 		   }
 1180: 	       }
 1181:            }
 1182:            $outdep.='</div><br />';
 1183:         }
 1184: 
 1185:         if ($outdep) {
 1186:             $scrout.='<h3>'.&mt('Dependencies').'</h3>'
 1187:                     .$outdep
 1188:         }
 1189:         $outstring=~s/\n*(\<\/[^\>]+\>[^<]*)$/$allowstr\n$1\n/s;
 1190: 
 1191: # ------------------------------------------------------------- Write modified.
 1192: 
 1193:         {
 1194:           my $org;
 1195:           unless ($org=Apache::File->new('>'.$source)) {
 1196:              print $logfile "No write permit to $source\n";
 1197:              return ('<span class="LC_error">'.&mt('No write permission to').
 1198: 		     ' '.$source.
 1199: 		     ', '.&mt('FAIL').'</span>',1);
 1200: 	  }
 1201:           print($org $outstring);
 1202:         }
 1203: 	  $content=$outstring;
 1204: 
 1205:     }
 1206: # -------------------------------------------- Initial step done, now metadata.
 1207: 
 1208: # --------------------------------------- Storage for metadata keys and fields.
 1209: # these are globals
 1210: #
 1211:      %metadatafields=();
 1212:      %metadatakeys=();
 1213:      
 1214:      my %oldparmstores=();
 1215:      
 1216:     unless ($batch) {
 1217:      $scrout.='<h3>'.&mt('Metadata').' ' .
 1218:        &Apache::loncommon::help_open_topic("Metadata_Description")
 1219:        . '</h3>';
 1220:     }
 1221: 
 1222: # ------------------------------------------------ First, check out environment
 1223:      if ((!(-e $source.'.meta')) || ($env{'form.forceoverride'})) {
 1224:         $metadatafields{'author'}=$env{'environment.firstname'}.' '.
 1225: 	                          $env{'environment.middlename'}.' '.
 1226: 		                  $env{'environment.lastname'}.' '.
 1227: 		                  $env{'environment.generation'};
 1228:         $metadatafields{'author'}=~s/\s+/ /g;
 1229:         $metadatafields{'author'}=~s/\s+$//;
 1230:         $metadatafields{'owner'}=$cuname.':'.$cudom;
 1231: 
 1232: # ------------------------------------------------ Check out directory hierachy
 1233: 
 1234:         my $thisdisfn=$source;
 1235: 
 1236:         $thisdisfn=~s/^\Q$docroot\E\/priv\/\Q$cudom\E\/\Q$cuname\E\///;
 1237:         my @urlparts=('.',split(/\//,$thisdisfn));
 1238:         $#urlparts--;
 1239: 
 1240:         my $currentpath=$docroot.'/priv/'.$cudom.'/'.$cuname.'/';
 1241: 
 1242: 	my $prefix='../'x($#urlparts);
 1243:         foreach my $subdir (@urlparts) {
 1244: 	    $currentpath.=$subdir.'/';
 1245:             $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
 1246: 	    $prefix=~s|^\.\./||;
 1247:         }
 1248: 
 1249: # ----------------------------------------------------------- Parse file itself
 1250: # read %metadatafields from file itself
 1251:  
 1252: 	$allmeta=&parseformeta($source,$style);
 1253: 
 1254: # ------------------- Clear out parameters and stores (there should not be any)
 1255: 
 1256:         foreach my $field (keys(%metadatafields)) {
 1257: 	    if (($field=~/^parameter/) || ($field=~/^stores/)) {
 1258: 		delete $metadatafields{$field};
 1259:             }
 1260:         }
 1261: 
 1262:     } else {
 1263: # ---------------------- Read previous metafile, remember parameters and stores
 1264: 
 1265:         $scrout.=&metaread($logfile,$source.'.meta');
 1266: 
 1267:         foreach my $field (keys(%metadatafields)) {
 1268: 	    if (($field=~/^parameter/) || ($field=~/^stores/)) {
 1269:                 $oldparmstores{$field}=1;
 1270: 		delete $metadatafields{$field};
 1271:             }
 1272:         }
 1273: # ------------------------------------------------------------- Save some stuff
 1274:         my %savemeta=();
 1275:         if ($metadatafields{'title'}) { $savemeta{'title'}=$metadatafields{'title'}; }
 1276: # ------------------------------------------ See if anything new in file itself
 1277:  
 1278: 	$allmeta=&parseformeta($source,$style);
 1279: # ----------------------------------------------------------- Restore the stuff
 1280:         foreach my $item (keys(%savemeta)) {
 1281: 	    $metadatafields{$item}=$savemeta{$item};
 1282: 	}
 1283:    }
 1284: 
 1285:        
 1286: # ---------------- Find and document discrepancies in the parameters and stores
 1287: 
 1288:     my $chparms='';
 1289:     foreach my $field (sort(keys(%metadatafields))) {
 1290: 	if (($field=~/^parameter/) || ($field=~/^stores/)) {
 1291: 	    unless ($field=~/\.\w+$/) {
 1292: 		unless ($oldparmstores{$field}) {
 1293: 		    my $disp_key = $field;
 1294: 		    $disp_key =~ tr/\0/_/;
 1295: 		    print $logfile ('New: '.$disp_key."\n");
 1296: 		    $chparms .= $disp_key.' ';
 1297: 		}
 1298: 	    }
 1299: 	}
 1300:     }
 1301:     if ($chparms) {
 1302: 	$scrout.='<p><b>'.&mt('New parameters or saved values').
 1303: 	    ':</b> '.$chparms.'</p>';
 1304:     }
 1305: 
 1306:     $chparms='';
 1307:     foreach my $olditem (sort(keys(%oldparmstores))) {
 1308: 	if (($olditem=~/^parameter/) || ($olditem=~/^stores/)) {
 1309: 	    unless (($metadatafields{$olditem.'.name'}) ||
 1310: 		    ($metadatafields{$olditem.'.package'}) || ($olditem=~/\.\w+$/)) {
 1311: 		my $disp_key = $olditem;
 1312: 		$disp_key =~ tr/\0/_/;
 1313: 		print $logfile ('Obsolete: '.$disp_key."\n");
 1314: 		$chparms.=$disp_key.' ';
 1315: 	    }
 1316: 	}
 1317:     }
 1318:     if ($chparms) {
 1319:         $scrout.='<p><b>'.&mt('Obsolete parameters or saved values').':</b> '
 1320: 	        .$chparms.'</p>'
 1321:                 .'<p class="LC_warning"><b>'.&mt('Warning!').'</b><br />'
 1322:                 .&mt('If this resource is in active use, student performance data from the previous version may become inaccessible.')
 1323:                 .'</p><hr />';
 1324:     }
 1325:     if ($metadatafields{'copyright'} eq 'priv') {
 1326:         $scrout.='<p class="LC_warning"><b>'.&mt('Warning!').'</b><br />'
 1327:                 .&mt('Copyright/distribution option "Private" is no longer supported. Select another option from below. Consider "Custom Rights" for maximum control over the usage of your resource.')
 1328:                 .'</p><hr />';
 1329:     }
 1330: 
 1331: # ------------------------------------------------------- Now have all metadata
 1332: 
 1333:     my %keywords=();
 1334:         
 1335:     if (length($content)<500000) {
 1336: 	my $textonly=$content;
 1337: 	$textonly=~s/\<script[^\<]+\<\/script\>//g;
 1338: 	$textonly=~s/\<m\>[^\<]+\<\/m\>//g;
 1339: 	$textonly=~s/\<[^\>]*\>//g;
 1340: 
 1341:         #this is a work simplification for german authors for present
 1342:         $textonly=HTML::Entities::decode($textonly);           #decode HTML-character
 1343:         $textonly=Encode::Encoder::encode('utf8', $textonly);  #encode to perl internal unicode
 1344:         $textonly=~tr/A-ZÜÄÖ/a-züäö/;      #add lowercase rule for german "Umlaute"
 1345:         $textonly=~s/[\$\&][a-z]\w*//g;
 1346:         $textonly=~s/[^a-z^ü^ä^ö^ß\s]//g;  #dont delete german "Umlaute"
 1347: 
 1348:         foreach ($textonly=~m/[^\s]+/g) {  #match all but whitespaces
 1349:             unless ($nokey{$_}) {
 1350:                 $keywords{$_}=1;
 1351:             }
 1352:         }
 1353: 
 1354: 
 1355:     }
 1356:             
 1357:     foreach my $addkey (split(/[\"\'\,\;]/,$metadatafields{'keywords'})) {
 1358: 	$addkey=~s/\s+/ /g;
 1359: 	$addkey=~s/^\s//;
 1360: 	$addkey=~s/\s$//;
 1361: 	if ($addkey=~/\w/) {
 1362: 	    $keywords{$addkey}=1;
 1363: 	}
 1364:     }
 1365: # --------------------------------------------------- Now we also have keywords
 1366: # =============================================================================
 1367: # interactive mode html goes into $intr_scrout
 1368: # batch mode throws away this HTML
 1369: # additionally all of the field functions have a by product of setting
 1370: #   $env{'from.'..} so that it can be used by the phase two handler in
 1371: #    batch mode
 1372: 
 1373:     my $intr_scrout.='<br />'
 1374:                     .'<form name="pubform" action="/adm/publish" method="post">';
 1375:     unless ($env{'form.makeobsolete'}) {
 1376:        $intr_scrout.='<p class="LC_warning">'
 1377:                     .&mt('Searching for your resource will be based on the following metadata. Please provide as much data as possible.')
 1378:                     .'</p>'
 1379:                     .'<p><input type="submit" value="'
 1380:                     .&mt('Finalize Publication')
 1381:                     .'" /> <a href="'.&Apache::loncfile::url($source).'">'.&mt('Cancel').'</a></p>';
 1382:     }
 1383:     $intr_scrout.=&Apache::lonhtmlcommon::start_pick_box();
 1384:     $intr_scrout.=
 1385: 	&hiddenfield('phase','two').
 1386: 	&hiddenfield('filename',$env{'form.filename'}).
 1387: 	&hiddenfield('allmeta',&escape($allmeta)).
 1388: 	&hiddenfield('dependencies',join(',',keys(%allow)));
 1389:     unless ($env{'form.makeobsolete'}) {
 1390:        $intr_scrout.=
 1391: 	&textfield('Title','title',$metadatafields{'title'}).
 1392: 	&textfield('Author(s)','author',$metadatafields{'author'}).
 1393: 	&textfield('Subject','subject',$metadatafields{'subject'});
 1394:  # --------------------------------------------------- Scan content for keywords
 1395: 
 1396:     my $keywords_help = &Apache::loncommon::help_open_topic("Publishing_Keywords");
 1397:     my $keywordout=<<"END";
 1398: <script>
 1399: function checkAll(field) {
 1400:     for (i = 0; i < field.length; i++)
 1401:         field[i].checked = true ;
 1402: }
 1403: 
 1404: function uncheckAll(field) {
 1405:     for (i = 0; i < field.length; i++)
 1406:         field[i].checked = false ;
 1407: }
 1408: </script>
 1409: END
 1410:     $keywordout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Keywords'))
 1411:                 .$keywords_help
 1412:                 .'<input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.pubform.keywords)" />'
 1413:                 .'<input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.pubform.keywords)" />'
 1414:                 .'</p><br />'
 1415:                 .&Apache::loncommon::start_data_table();
 1416:     my $cols_per_row = 10;
 1417:     my $colcount=0;
 1418:     my $wordcount=0;
 1419:     my $numkeywords = scalar(keys(%keywords));
 1420: 
 1421:     foreach my $word (sort(keys(%keywords))) {
 1422:         if ($colcount == 0) {
 1423:             $keywordout .= &Apache::loncommon::start_data_table_row();
 1424:         }
 1425:         $colcount++;
 1426:         $wordcount++;
 1427:         if (($wordcount == $numkeywords) && ($colcount < $cols_per_row)) {
 1428:             my $colspan = 1+$cols_per_row-$colcount;
 1429:             $keywordout .= '<td colspan="'.$colspan.'">';
 1430:         } else {
 1431:             $keywordout .= '<td>';
 1432:         }
 1433:         $keywordout.='<label><input type="checkbox" name="keywords" value="'.$word.'"';
 1434:         if ($metadatafields{'keywords'}) {
 1435:             if ($metadatafields{'keywords'}=~/\Q$word\E/) {
 1436:                 $keywordout.=' checked="checked"';
 1437:                 $env{'form.keywords'}.=$word.',';
 1438:             }
 1439:         } elsif (&Apache::loncommon::keyword($word)) {
 1440:             $keywordout.=' checked="checked"';
 1441:             $env{'form.keywords'}.=$word.',';
 1442:         }
 1443:         $keywordout.=' />'.$word.'</label></td>';
 1444:         if ($colcount == $cols_per_row) {
 1445:             $keywordout.=&Apache::loncommon::end_data_table_row();
 1446:             $colcount=0;
 1447:         }
 1448:     }
 1449:     if ($colcount > 0) {
 1450:         $keywordout .= &Apache::loncommon::end_data_table_row();
 1451:     }
 1452: 
 1453:     $env{'form.keywords'}=~s/\,$//;
 1454: 
 1455:     $keywordout.=&Apache::loncommon::end_data_table_row()
 1456:                  .&Apache::loncommon::end_data_table()
 1457:                  .&Apache::lonhtmlcommon::row_closure();
 1458: 
 1459:     $intr_scrout.=$keywordout;
 1460: 
 1461:     $intr_scrout.=&textfield('Additional Keywords','addkey','');
 1462: 
 1463:     $intr_scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
 1464: 
 1465:     $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Abstract'))
 1466:                  .'<textarea cols="80" rows="5" name="abstract">'
 1467:                  .$metadatafields{'abstract'}
 1468:                  .'</textarea>'
 1469:                  .&Apache::lonhtmlcommon::row_closure();
 1470: 
 1471:     $source=~/\.(\w+)$/;
 1472: 
 1473:     $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Grade Levels'))
 1474:                  .&mt('Lowest Grade Level:').'&nbsp;'
 1475:                  .&select_level_form($metadatafields{'lowestgradelevel'},'lowestgradelevel')
 1476: #                .&Apache::lonhtmlcommon::row_closure();
 1477: #   $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Highest Grade Level'))
 1478:                  .' '.&mt('Highest Grade Level:').'&nbsp;'
 1479:                  .&select_level_form($metadatafields{'highestgradelevel'},'highestgradelevel')
 1480:                  .&Apache::lonhtmlcommon::row_closure();
 1481: 
 1482:     $intr_scrout.=&textfield('Standards','standards',$metadatafields{'standards'});
 1483: 
 1484:     $intr_scrout.=&hiddenfield('mime',$1);
 1485: 
 1486:     my $defaultlanguage=$metadatafields{'language'};
 1487:     $defaultlanguage =~ s/\s*notset\s*//g;
 1488:     $defaultlanguage =~ s/^,\s*//g;
 1489:     $defaultlanguage =~ s/,\s*$//g;
 1490: 
 1491:     $intr_scrout.=&selectbox('Language','language',
 1492: 			     $defaultlanguage,
 1493: 			     \&Apache::loncommon::languagedescription,
 1494: 			     (&Apache::loncommon::languageids),
 1495: 			     );
 1496: 
 1497:     unless ($metadatafields{'creationdate'}) {
 1498: 	$metadatafields{'creationdate'}=time;
 1499:     }
 1500:     $intr_scrout.=&hiddenfield('creationdate',
 1501: 			       &Apache::lonmysql::unsqltime($metadatafields{'creationdate'}));
 1502: 
 1503:     $intr_scrout.=&hiddenfield('lastrevisiondate',time);
 1504: 
 1505:     my $pubowner_last;
 1506:     if ($style eq 'prv') {
 1507:         $pubowner_last = 1;
 1508:     }
 1509:     $intr_scrout.=&textfield('Publisher/Owner','owner',
 1510: 			     $metadatafields{'owner'},$pubowner_last);
 1511: 
 1512: # ---------------------------------------------- Retrofix for unused copyright
 1513:     if ($metadatafields{'copyright'} eq 'free') {
 1514: 	$metadatafields{'copyright'}='default';
 1515: 	$metadatafields{'sourceavail'}='open';
 1516:     }
 1517:     if ($metadatafields{'copyright'} eq 'priv') {
 1518:         $metadatafields{'copyright'}='domain';
 1519:     }
 1520: # ------------------------------------------------ Dial in reasonable defaults
 1521:     my $defaultoption=$metadatafields{'copyright'};
 1522:     unless ($defaultoption) { $defaultoption='default'; }
 1523:     my $defaultsourceoption=$metadatafields{'sourceavail'};
 1524:     unless ($defaultsourceoption) { $defaultsourceoption='closed'; }
 1525:     unless ($style eq 'prv') {
 1526: # -------------------------------------------------- Correct copyright for rat.
 1527: 	if ($style eq 'rat') {
 1528: # -------------------------------------- Retrofix for non-applicable copyright
 1529: 	    if ($metadatafields{'copyright'} eq 'public') { 
 1530: 		delete $metadatafields{'copyright'};
 1531: 		$defaultoption='default';
 1532: 	    }
 1533: 	    $intr_scrout.=&selectbox('Copyright/Distribution','copyright',
 1534: 				     $defaultoption,
 1535: 				     \&Apache::loncommon::copyrightdescription,
 1536: 				    (grep !/^(public|priv)$/,(&Apache::loncommon::copyrightids)));
 1537: 	} else {
 1538: 	    $intr_scrout.=&selectbox('Copyright/Distribution','copyright',
 1539: 				     $defaultoption,
 1540: 				     \&Apache::loncommon::copyrightdescription,
 1541: 				     (grep !/^priv$/,(&Apache::loncommon::copyrightids)));
 1542: 	}
 1543: 	my $copyright_help =
 1544: 	    &Apache::loncommon::help_open_topic('Publishing_Copyright');
 1545:         my $replace=&mt('Copyright/Distribution:');
 1546: 	$intr_scrout =~ s/$replace/$replace.' '.$copyright_help/ge;
 1547: 
 1548: 	$intr_scrout.=&text_with_browse_field('Custom Distribution File','customdistributionfile',$metadatafields{'customdistributionfile'},'rights');
 1549: 	$intr_scrout.=&selectbox('Source Distribution','sourceavail',
 1550: 				 $defaultsourceoption,
 1551: 				 \&Apache::loncommon::source_copyrightdescription,
 1552: 				 (&Apache::loncommon::source_copyrightids));
 1553: #	$intr_scrout.=&text_with_browse_field('Source Custom Distribution File','sourcerights',$metadatafields{'sourcerights'},'rights');
 1554: 	my $uctitle=&mt('Obsolete');
 1555:         my $obsolete_checked=($metadatafields{'obsolete'})?' checked="checked"':'';
 1556:         $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title($uctitle)
 1557:                      .'<input type="checkbox" name="obsolete"'.$obsolete_checked.' />'
 1558:                      .&Apache::lonhtmlcommon::row_closure(1);
 1559:         $intr_scrout.=&text_with_browse_field('Suggested Replacement for Obsolete File',
 1560: 				    'obsoletereplacement',
 1561: 				    $metadatafields{'obsoletereplacement'},'',1);
 1562:     } else {
 1563: 	$intr_scrout.=&hiddenfield('copyright','private');
 1564:     }
 1565:    } else {
 1566:        $intr_scrout.=
 1567: 	&hiddenfield('title',$metadatafields{'title'}).
 1568: 	&hiddenfield('author',$metadatafields{'author'}).
 1569: 	&hiddenfield('subject',$metadatafields{'subject'}).
 1570: 	&hiddenfield('keywords',$metadatafields{'keywords'}).
 1571: 	&hiddenfield('abstract',$metadatafields{'abstract'}).
 1572: 	&hiddenfield('notes',$metadatafields{'notes'}).
 1573: 	&hiddenfield('mime',$metadatafields{'mime'}).
 1574: 	&hiddenfield('creationdate',$metadatafields{'creationdate'}).
 1575: 	&hiddenfield('lastrevisiondate',time).
 1576: 	&hiddenfield('owner',$metadatafields{'owner'}).
 1577: 	&hiddenfield('lowestgradelevel',$metadatafields{'lowestgradelevel'}).
 1578: 	&hiddenfield('standards',$metadatafields{'standards'}).
 1579: 	&hiddenfield('highestgradelevel',$metadatafields{'highestgradelevel'}).
 1580: 	&hiddenfield('language',$metadatafields{'language'}).
 1581: 	&hiddenfield('copyright',$metadatafields{'copyright'}).
 1582: 	&hiddenfield('sourceavail',$metadatafields{'sourceavail'}).
 1583: 	&hiddenfield('customdistributionfile',$metadatafields{'customdistributionfile'}).
 1584: 	&hiddenfield('obsolete',1).
 1585: 	&text_with_browse_field('Suggested Replacement for Obsolete File',
 1586: 				    'obsoletereplacement',
 1587: 				    $metadatafields{'obsoletereplacement'},'',1);
 1588:    }
 1589:     if (!$batch) {
 1590: 	$scrout.=$intr_scrout
 1591:             .&Apache::lonhtmlcommon::end_pick_box()
 1592:             .'<p><input type="submit" value="'
 1593: 	    .&mt($env{'form.makeobsolete'}?'Make Obsolete':'Finalize Publication')
 1594:             .'" /></p>'
 1595:             .'</form>';
 1596:     }
 1597:     return($scrout,0);
 1598: }
 1599: 
 1600: #########################################
 1601: #########################################
 1602: 
 1603: =pod 
 1604: 
 1605: =item B<phasetwo>
 1606: 
 1607: Render second interface showing status of publication steps.
 1608: This is publication step two.
 1609: 
 1610: Parameters:
 1611: 
 1612: =over 4
 1613: 
 1614: =item I<$source>
 1615: 
 1616: =item I<$target>
 1617: 
 1618: =item I<$style>
 1619: 
 1620: =item I<$distarget>
 1621: 
 1622: =back
 1623: 
 1624: Returns:
 1625: 
 1626: =over 4
 1627: 
 1628: =item integer
 1629: 
 1630: 0: fail
 1631: 1: success
 1632: 
 1633: =back
 1634: 
 1635: =cut
 1636: 
 1637: #'stupid emacs
 1638: #########################################
 1639: #########################################
 1640: sub phasetwo {
 1641: 
 1642:     my ($r,$source,$target,$style,$distarget,$batch)=@_;
 1643:     $source=~s/\/+/\//g;
 1644:     $target=~s/\/+/\//g;
 1645: #
 1646: # Unless trying to get rid of something, check name validity
 1647: #
 1648:     unless ($env{'form.obsolete'}) {
 1649: 	if ($target=~/(\_\_\_|\&\&\&|\:\:\:)/) {
 1650: 	    $r->print('<span class="LC_error">'.
 1651: 		      &mt('Unsupported character combination [_1] in filename, FAIL.',"<tt>'.$1.'</tt>").
 1652: 		      '</span>');
 1653: 	    return 0;
 1654: 	}
 1655: 	unless ($target=~/\.(\w+)$/) {
 1656: 	    $r->print('<span class="LC_error">'.&mt('No valid extension found in filename, FAIL').'</span>');
 1657: 	    return 0;
 1658: 	}
 1659: 	if ($target=~/\.(\d+)\.(\w+)$/) {
 1660: 	    $r->print('<span class="LC_error">'.&mt('Filename of resource contains internal version number. Cannot publish such resources, FAIL').'</span>');
 1661: 	    return 0;
 1662: 	}
 1663:     }
 1664: 
 1665: #
 1666: # End name check
 1667: #
 1668:     $distarget=~s/\/+/\//g;
 1669:     my $logfile;
 1670:     unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
 1671: 	$r->print(
 1672:         '<span class="LC_error">'.
 1673: 		&mt('No write permission to user directory, FAIL').'</span>');
 1674:         return 0;
 1675:     }
 1676:     
 1677:     if ($source =~ /\.rights$/) {
 1678: 	$r->print('<p><span class="LC_warning">'.&mt('Warning: It can take up to 1 hour for rights changes to fully propagate.').'</span></p>');
 1679:     }
 1680: 
 1681:     print $logfile 
 1682:         "\n================= Publish ".localtime()." Phase Two  ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
 1683:     
 1684:     %metadatafields=();
 1685:     %metadatakeys=();
 1686: 
 1687:     &metaeval(&unescape($env{'form.allmeta'}));
 1688: 
 1689:     if ($batch) {
 1690:         my %commonaccess;
 1691:         map { $commonaccess{$_} = 1; } &Apache::loncommon::get_env_multiple('form.commonaccess');
 1692:         if ($commonaccess{'dist'}) {
 1693:             unless ($style eq 'prv') { 
 1694:                 if ($env{'form.commondistselect'} eq 'custom') {
 1695:                     unless ($source =~ /\.rights$/) {
 1696:                         if ($env{'form.commoncustomrights'} =~ m{^/res/.+\.rights$}) { 
 1697:                             $env{'form.customdistributionfile'} = $env{'form.commoncustomrights'}; 
 1698:                             $env{'form.copyright'} = $env{'form.commondistselect'};
 1699:                         }
 1700:                     }
 1701:                 } elsif ($env{'form.commondistselect'} =~ /^default|domain|public$/) {
 1702:                     $env{'form.copyright'} = $env{'form.commondistselect'};
 1703:                 }
 1704:             }
 1705:         }
 1706:         unless ($style eq 'prv') {
 1707:             if ($commonaccess{'source'}) {
 1708:                 if (($env{'form.commonsourceselect'} eq 'open') || ($env{'form.commonsourceselect'} eq 'closed')) {
 1709:                     $env{'form.sourceavail'} = $env{'form.commonsourceselect'};
 1710:                 }
 1711:             }
 1712:         }
 1713:     }
 1714: 
 1715:     $metadatafields{'title'}=$env{'form.title'};
 1716:     $metadatafields{'author'}=$env{'form.author'};
 1717:     $metadatafields{'subject'}=$env{'form.subject'};
 1718:     $metadatafields{'notes'}=$env{'form.notes'};
 1719:     $metadatafields{'abstract'}=$env{'form.abstract'};
 1720:     $metadatafields{'mime'}=$env{'form.mime'};
 1721:     $metadatafields{'language'}=$env{'form.language'};
 1722:     $metadatafields{'creationdate'}=$env{'form.creationdate'};
 1723:     $metadatafields{'lastrevisiondate'}=$env{'form.lastrevisiondate'};
 1724:     $metadatafields{'owner'}=$env{'form.owner'};
 1725:     $metadatafields{'copyright'}=$env{'form.copyright'};
 1726:     $metadatafields{'standards'}=$env{'form.standards'};
 1727:     $metadatafields{'lowestgradelevel'}=$env{'form.lowestgradelevel'};
 1728:     $metadatafields{'highestgradelevel'}=$env{'form.highestgradelevel'};
 1729:     $metadatafields{'customdistributionfile'}=
 1730:                                  $env{'form.customdistributionfile'};
 1731:     $metadatafields{'sourceavail'}=$env{'form.sourceavail'};
 1732:     $metadatafields{'obsolete'}=$env{'form.obsolete'};
 1733:     $metadatafields{'obsoletereplacement'}=
 1734: 	                        $env{'form.obsoletereplacement'};
 1735:     $metadatafields{'dependencies'}=$env{'form.dependencies'};
 1736:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
 1737: 	                                 $env{'user.domain'};
 1738:     $metadatafields{'authorspace'}=$cuname.':'.$cudom;
 1739:     $metadatafields{'domain'}=$cudom;
 1740:     
 1741:     my $allkeywords=$env{'form.addkey'};
 1742:     if (exists($env{'form.keywords'})) {
 1743:         if (ref($env{'form.keywords'})) {
 1744:             $allkeywords .= ','.join(',',@{$env{'form.keywords'}});
 1745:         } else {
 1746:             $allkeywords .= ','.$env{'form.keywords'};
 1747:         }
 1748:     }
 1749:     $allkeywords=~s/[\"\']//g;
 1750:     $allkeywords=~s/\s*[\;\,]\s*/\,/g;
 1751:     $allkeywords=~s/\s+/ /g;
 1752:     $allkeywords=~s/^[ \,]//;
 1753:     $allkeywords=~s/[ \,]$//;
 1754:     $metadatafields{'keywords'}=$allkeywords;
 1755:     
 1756: # check if custom distribution file is specified
 1757:     if ($metadatafields{'copyright'} eq 'custom') {
 1758: 	my $file=$metadatafields{'customdistributionfile'};
 1759: 	unless ($file=~/\.rights$/) {
 1760:             $r->print(
 1761:                 '<span class="LC_error">'.&mt('No valid custom distribution rights file specified, FAIL').
 1762: 		'</span>');
 1763: 	    return 0;
 1764:         }
 1765:     }
 1766:     {
 1767:         print $logfile "\nWrite metadata file for ".$source;
 1768:         my $mfh;
 1769:         unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
 1770:             $r->print( 
 1771:                 '<span class="LC_error">'.&mt('Could not write metadata, FAIL').
 1772: 		'</span>');
 1773: 	    return 0;
 1774:         }
 1775:         foreach my $field (sort(keys(%metadatafields))) {
 1776:             unless ($field=~/\./) {
 1777:                 my $unikey=$field;
 1778:                 $unikey=~/^([A-Za-z]+)/;
 1779:                 my $tag=$1;
 1780:                 $tag=~tr/A-Z/a-z/;
 1781:                 print $mfh "\n\<$tag";
 1782:                 foreach my $item (split(/\,/,$metadatakeys{$unikey})) {
 1783:                     my $value=$metadatafields{$unikey.'.'.$item};
 1784:                     $value=~s/\"/\'\'/g;
 1785:                     print $mfh ' '.$item.'="'.$value.'"';
 1786:                 }
 1787:                 print $mfh '>'.
 1788:                     &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
 1789:                         .'</'.$tag.'>';
 1790:             }
 1791:         }
 1792:         $r->print('<p>'.&mt('Wrote Metadata').'</p>');
 1793:         print $logfile "\nWrote metadata";
 1794:     }
 1795:     
 1796: # -------------------------------- Synchronize entry with SQL metadata database
 1797: 
 1798:     $metadatafields{'url'} = $distarget;
 1799:     $metadatafields{'version'} = 'current';
 1800: 
 1801:     my ($error,$success) = &store_metadata(%metadatafields);
 1802:     if ($success) {
 1803: 	$r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
 1804: 	print $logfile "\nSynchronized SQL metadata database";
 1805:     } else {
 1806: 	$r->print($error);
 1807: 	print $logfile "\n".$error;
 1808:     }
 1809: # --------------------------------------------- Delete author resource messages
 1810:     my $delresult=&Apache::lonmsg::del_url_author_res_msg($target); 
 1811:     $r->print('<p>'.&mt('Removing error messages:').' '.$delresult.'</p>');
 1812:     print $logfile "\nRemoving error messages: $delresult";
 1813: # ----------------------------------------------------------- Copy old versions
 1814:    
 1815:     if (-e $target) {
 1816:         my $filename;
 1817:         my $maxversion=0;
 1818:         $target=~/(.*)\/([^\/]+)\.(\w+)$/;
 1819:         my $srcf=$2;
 1820:         my $srct=$3;
 1821:         my $srcd=$1;
 1822:         my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1823:         unless ($srcd=~/^\Q$docroot\E\/res/) {
 1824:             print $logfile "\nPANIC: Target dir is ".$srcd;
 1825:             $r->print(
 1826: 	 "<span class=\"LC_error\">".&mt('Invalid target directory, FAIL')."</span>");
 1827: 	    return 0;
 1828:         }
 1829:         opendir(DIR,$srcd);
 1830:         while ($filename=readdir(DIR)) {
 1831:             if (-l $srcd.'/'.$filename) {
 1832:                 unlink($srcd.'/'.$filename);
 1833:                 unlink($srcd.'/'.$filename.'.meta');
 1834:             } else {
 1835:                 if ($filename=~/^\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
 1836:                     $maxversion=($1>$maxversion)?$1:$maxversion;
 1837:                 }
 1838:             }
 1839:         }
 1840:         closedir(DIR);
 1841:         $maxversion++;
 1842:         $r->print('<p>'.&mt('Creating old version [_1]',$maxversion).'</p>');
 1843:         print $logfile "\nCreating old version ".$maxversion."\n";
 1844:         
 1845:         my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
 1846:         
 1847:         if (copy($target,$copyfile)) {
 1848: 	    print $logfile "Copied old target to ".$copyfile."\n";
 1849:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied old target file')));
 1850:         } else {
 1851: 	    print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 1852:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Failed to copy old target').", $!",1));
 1853: 	    return 0;
 1854:         }
 1855:         
 1856: # --------------------------------------------------------------- Copy Metadata
 1857: 
 1858: 	$copyfile=$copyfile.'.meta';
 1859:         
 1860:         if (copy($target.'.meta',$copyfile)) {
 1861: 	    print $logfile "Copied old target metadata to ".$copyfile."\n";
 1862:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied old metadata')));
 1863:         } else {
 1864: 	    print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 1865:             if (-e $target.'.meta') {
 1866:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 1867:                            &mt('Failed to write old metadata copy').", $!",1));
 1868: 		return 0;
 1869: 	    }
 1870:         }
 1871:         
 1872:         
 1873:     } else {
 1874:         $r->print('<p>'.&mt('Initial version').'</p>');
 1875:         print $logfile "\nInitial version";
 1876:     }
 1877: 
 1878: # ---------------------------------------------------------------- Write Source
 1879:     my $copyfile=$target;
 1880:     
 1881:     my @parts=split(/\//,$copyfile);
 1882:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1883:     
 1884:     my $count;
 1885:     for ($count=5;$count<$#parts;$count++) {
 1886:         $path.="/$parts[$count]";
 1887:         if ((-e $path)!=1) {
 1888:             print $logfile "\nCreating directory ".$path;
 1889:             mkdir($path,0777);
 1890:             $r->print('<p>'
 1891:                      .&mt('Created directory [_1]'
 1892:                          ,'<span class="LC_filename">'.$parts[$count].'</span>')
 1893:                      .'</p>'
 1894:             );
 1895:         }
 1896:     }
 1897:     
 1898:     if (copy($source,$copyfile)) {
 1899:         print $logfile "\nCopied original source to ".$copyfile."\n";
 1900:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied source file')));
 1901:     } else {
 1902:         print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 1903:         $r->print(&Apache::lonhtmlcommon::confirm_success(
 1904: 	    &mt('Failed to copy source').", $!",1));
 1905: 	return 0;
 1906:     }
 1907:     
 1908: # ---------------------------------------------- Delete local tmp-preview files
 1909:     unlink($copyfile.'.tmp');
 1910: # --------------------------------------------------------------- Copy Metadata
 1911: 
 1912:     $copyfile=$copyfile.'.meta';
 1913:     
 1914:     if (copy($source.'.meta',$copyfile)) {
 1915:         print $logfile "\nCopied original metadata to ".$copyfile."\n";
 1916:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied metadata')));
 1917:     } else {
 1918:         print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
 1919:         $r->print(&Apache::lonhtmlcommon::confirm_success(
 1920:                   &mt('Failed to write metadata copy').", $!",1));
 1921: 	return 0;
 1922:     }
 1923:     $r->rflush;
 1924: 
 1925: # ------------------------------------------------------------- Trigger updates
 1926:     push(@{$modified_urls},[$target,$source]);
 1927:     unless ($registered_cleanup) {
 1928:         my $handlers = $r->get_handlers('PerlCleanupHandler');
 1929:         $r->set_handlers('PerlCleanupHandler' => [\&notify,@{$handlers}]);
 1930: 	$registered_cleanup=1;
 1931:     }
 1932: 
 1933: # ---------------------------------------------------------- Clear local caches
 1934:     my $thisdistarget=$target;
 1935:     $thisdistarget=~s/^\Q$docroot\E//;
 1936:     &Apache::lonnet::devalidate_cache_new('resversion',$target);
 1937:     &Apache::lonnet::devalidate_cache_new('meta',
 1938: 			 &Apache::lonnet::declutter($thisdistarget));
 1939: 
 1940: # ------------------------------------------------------------- Everything done
 1941:     $logfile->close();
 1942:     $r->print('<p class="LC_success">'.&mt('Done').'</p>');
 1943: 
 1944: # ------------------------------------------------ Provide link to new resource
 1945:     unless ($batch) {
 1946:         
 1947:         my $thissrc=&Apache::loncfile::url($source);
 1948:         my $thissrcdir=$thissrc;
 1949:         $thissrcdir=~s/\/[^\/]+$/\//;
 1950:         
 1951:         $r->print(
 1952:             &Apache::lonhtmlcommon::actionbox([
 1953:                 '<a href="'.$thisdistarget.'">'.
 1954:                 &mt('View Published Version').
 1955:                 '</a>',
 1956:                 '<a href="'.$thissrc.'">'.
 1957:                 &mt('Back to Source').
 1958:                 '</a>',
 1959:                 '<a href="'.$thissrcdir.'">'.
 1960:                 &mt('Back to Source Directory').
 1961:                 '</a>'])
 1962:         );
 1963:     }
 1964:     return 1;
 1965: }
 1966: 
 1967: # =============================================================== Notifications
 1968: sub notify {  
 1969: # --------------------------------------------------- Send update notifications
 1970:     foreach my $targetsource (@{$modified_urls}){
 1971: 	my ($target,$source)=@{$targetsource};
 1972: 	my $logfile=Apache::File->new('>>'.$source.'.log');
 1973: 	print $logfile "\nCleanup phase: Notifications\n";
 1974: 	my @subscribed=&get_subscribed_hosts($target);
 1975: 	foreach my $subhost (@subscribed) {
 1976: 	    print $logfile "\nNotifying host ".$subhost.':';
 1977: 	    my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 1978: 	    print $logfile $reply;
 1979: 	}
 1980: # ---------------------------------------- Send update notifications, meta only
 1981: 	my @subscribedmeta=&get_subscribed_hosts("$target.meta");
 1982: 	foreach my $subhost (@subscribedmeta) {
 1983: 	    print $logfile "\nNotifying host for metadata only ".$subhost.':';
 1984: 	    my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 1985: 						$subhost);
 1986: 	    print $logfile $reply;
 1987: 	} 
 1988: # --------------------------------------------------- Notify subscribed courses
 1989: 	my %courses=&coursedependencies($target);
 1990: 	my $now=time;
 1991: 	foreach my $course (keys(%courses)) {
 1992: 	    print $logfile "\nNotifying course ".$course.':';
 1993: 	    my ($cdom,$cname)=split(/\_/,$course);
 1994: 	    my $reply=&Apache::lonnet::cput
 1995: 		('versionupdate',{$target => $now},$cdom,$cname);
 1996: 	    print $logfile $reply;
 1997: 	}
 1998: 	print $logfile "\n============ Done ============\n";
 1999: 	$logfile->close();
 2000:     }
 2001:     if ($lock) { &Apache::lonnet::remove_lock($lock); }
 2002:     return OK;
 2003: }
 2004: 
 2005: #########################################
 2006: 
 2007: sub batchpublish {
 2008:     my ($r,$srcfile,$targetfile)=@_;
 2009:     #publication pollutes %env with form.* values
 2010:     my %oldenv=%env;
 2011:     $srcfile=~s/\/+/\//g;
 2012:     $targetfile=~s/\/+/\//g;
 2013:     $srcfile=~s/\/+/\//g;
 2014: 
 2015:     my $docroot=$r->dir_config('lonDocRoot');
 2016:     my $thisdistarget=$targetfile;
 2017:     $thisdistarget=~s/^\Q$docroot\E//;
 2018: 
 2019: 
 2020:     %metadatafields=();
 2021:     %metadatakeys=();
 2022:     $srcfile=~/\.(\w+)$/;
 2023:     my $thistype=$1;
 2024: 
 2025: 
 2026:     my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 2027:      
 2028:     $r->print('<h2>'
 2029:              .&mt('Publishing [_1]',&Apache::loncfile::display($srcfile))
 2030:              .'</h2>'
 2031:     );
 2032: 
 2033: # phase one takes
 2034: #  my ($source,$target,$style,$batch)=@_;
 2035:     my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
 2036:     $r->print('<p>'.$outstring.'</p>');
 2037: # phase two takes
 2038: # my ($source,$target,$style,$distarget,batch)=@_;
 2039: # $env{'form.allmeta'},$env{'form.title'},$env{'form.author'},...
 2040:     if (!$error) {
 2041: 	$r->print('<p>');
 2042: 	&phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
 2043: 	$r->print('</p>');
 2044:     }
 2045:     %env=%oldenv;
 2046:     return '';
 2047: }
 2048: 
 2049: #########################################
 2050: 
 2051: sub publishdirectory {
 2052:     my ($r,$fn,$thisdisfn)=@_;
 2053:     $fn=~s/\/+/\//g;
 2054:     $thisdisfn=~s/\/+/\//g;
 2055:     my $thisdisresdir=$thisdisfn;
 2056:     $thisdisresdir=~s/^\/priv\//\/res\//;
 2057:     my $resdir = $r->dir_config('lonDocRoot').$thisdisresdir;
 2058:     $r->print('<form name="pubdirpref" method="post" action="">'
 2059:              .&Apache::lonhtmlcommon::start_pick_box()
 2060:              .&Apache::lonhtmlcommon::row_title(&mt('Directory'))
 2061:             .'<span class="LC_filename">'.$thisdisfn.'</span>'
 2062:             .&Apache::lonhtmlcommon::row_closure()
 2063:             .&Apache::lonhtmlcommon::row_title(&mt('Target'))
 2064:             .'<span class="LC_filename">'.$thisdisresdir.'</span>'
 2065:     );
 2066:     my %reasons = &Apache::lonlocal::texthash(
 2067:                       mod => 'Authoring Space file postdates published file',
 2068:                       modmeta => 'Authoring Space metadata file postdates published file',
 2069:                       unpub => 'Resource is unpublished',
 2070:     );
 2071: 
 2072:     my $dirptr=16384;		# Mask indicating a directory in stat.cmode.
 2073:     unless ($env{'form.phase'} eq 'two') {
 2074: # ask user what they want
 2075:         $r->print(&Apache::lonhtmlcommon::row_closure()
 2076:                  .&Apache::lonhtmlcommon::row_title(&mt('Options')
 2077:                  .&Apache::loncommon::help_open_topic('Publishing_Directory_Options')));
 2078:         $r->print(&hiddenfield('phase','two').
 2079: 		  &hiddenfield('filename',$env{'form.filename'}).
 2080:                   '<fieldset><legend>'.&mt('Recurse').'</legend>'.
 2081:                   &checkbox('pubrec','include subdirectories').
 2082:                   '</fieldset>'.
 2083:                   '<fieldset><legend>'.&mt('Force').'</legend>'.
 2084:                   &checkbox('forcerepub','force republication of previously published files').'<br />'.
 2085:                   &checkbox('forceoverride','force directory level metadata over existing').
 2086:                   '</fieldset>'.
 2087:                   '<fieldset><legend>'.&mt('Exclude').'</legend>'.
 2088:                   &checkbox('excludeunpub','exclude currently unpublished files').'<br />'.
 2089:                   &checkbox('excludemod','exclude modified files').'<br />'.
 2090:                   &checkbox('excludemodmeta','exclude files with modified metadata').
 2091:                   '</fieldset>'.
 2092:                   '<fieldset><legend>'.&mt('Actions').'</legend>'.
 2093:                   &checkbox('obsolete','make file(s) obsolete').'<br />'.
 2094:                   &common_access('dist',&mt('apply common copyright/distribution'),
 2095:                                  ['default','domain','custom']).'<br />'.
 2096:                   &common_access('source',&mt('apply common source availability'),
 2097:                                  ['closed','open']).
 2098:                   '</fieldset>'
 2099:         );
 2100:         $r->print(&Apache::lonhtmlcommon::row_closure(1)
 2101:                  .&Apache::lonhtmlcommon::end_pick_box()
 2102:                  .'<br /><input type="submit" value="'.&mt('Publish Directory').'" /></form>'
 2103:         );
 2104:         $lock=0;
 2105:     } else {
 2106:         $r->print(&Apache::lonhtmlcommon::row_closure(1)
 2107:                  .&Apache::lonhtmlcommon::end_pick_box()
 2108:         );
 2109:         my %commonaccess;
 2110:         map { $commonaccess{$_} = 1; } &Apache::loncommon::get_env_multiple('form.commonaccess');
 2111:         unless ($lock) { $lock=&Apache::lonnet::set_lock(&mt('Publishing [_1]',$fn)); }
 2112: # actually publish things
 2113: 	opendir(DIR,$fn);
 2114: 	my @files=sort(readdir(DIR));
 2115: 	foreach my $filename (@files) {
 2116: 	    my ($cdev,$cino,$cmode,$cnlink,
 2117: 		$cuid,$cgid,$crdev,$csize,
 2118: 		$catime,$cmtime,$cctime,
 2119: 		$cblksize,$cblocks)=stat($fn.'/'.$filename);
 2120: 	    
 2121: 	    my $extension='';
 2122: 	    if ($filename=~/\.(\w+)$/) { $extension=$1; }
 2123: 	    if ($cmode&$dirptr) {
 2124: 		if (($filename!~/^\./) && ($env{'form.pubrec'})) {
 2125: 		    &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
 2126: 		}
 2127: 	    } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
 2128: 		     ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
 2129: # find out publication status and/or existing metadata
 2130: 		my $publishthis=0;
 2131:                 my $skipthis;
 2132: 		if (-e $resdir.'/'.$filename) {
 2133: 		    my ($rdev,$rino,$rmode,$rnlink,
 2134: 			$ruid,$rgid,$rrdev,$rsize,
 2135: 			$ratime,$rmtime,$rctime,
 2136: 			$rblksize,$rblocks)=stat($resdir.'/'.$filename);
 2137: 		    if (($rmtime<$cmtime) || ($env{'form.forcerepub'})) {
 2138: # previously published, modified now
 2139:                         if ($env{'form.excludemod'}) {
 2140:                             $skipthis='mod';
 2141:                         } else {
 2142:                             $publishthis=1;
 2143:                         }
 2144: 		    }
 2145:                     unless ($skipthis) {
 2146:                         my $meta_cmtime = (stat($fn.'/'.$filename.'.meta'))[9];
 2147:                         my $meta_rmtime = (stat($resdir.'/'.$filename.'.meta'))[9];
 2148:                         if ( $meta_rmtime<$meta_cmtime ) {
 2149:                             if ($env{'form.excludemodmeta'}) {
 2150:                                 $skipthis='modmeta';
 2151:                                 $publishthis=0;
 2152:                             } else {
 2153:                                 $publishthis=1;
 2154:                             }
 2155:                         } else {
 2156:                             unless (&Apache::loncommon::fileembstyle($extension) eq 'prv') {
 2157:                                 if ($commonaccess{'dist'}) {
 2158:                                     my ($currdist,$currdistfile,$currsourceavail);
 2159:                                     my $currdist =  &Apache::lonnet::metadata($thisdisresdir.'/'.$filename,'copyright');
 2160:                                     if ($currdist eq 'custom') {
 2161:                                         $currdistfile =  &Apache::lonnet::metadata($thisdisresdir.'/'.$filename,'customdistributionfile');
 2162:                                     }
 2163:                                     if ($env{'form.commondistselect'} eq 'custom') {
 2164:                                         if ($env{'form.commoncustomrights'} =~ m{^/res/.+\.rights$}) {
 2165:                                             if ($currdist eq 'custom') {
 2166:                                                 unless ($env{'form.commoncustomrights'} eq $currdistfile) {
 2167:                                                     $publishthis=1;
 2168:                                                 }
 2169:                                             } else {
 2170:                                                 $publishthis=1;
 2171:                                             }
 2172:                                         }
 2173:                                     } elsif ($env{'form.commondistselect'} =~ /^default|domain|public$/) {
 2174:                                         unless ($currdist eq $env{'form.commondistselect'}) {
 2175:                                             $publishthis=1;
 2176:                                         }
 2177:                                     }
 2178:                                 }
 2179:                             }
 2180:                         }
 2181:                     }
 2182: 		} else {
 2183: # never published
 2184:                     if ($env{'form.excludeunpub'}) {
 2185:                         $skipthis='unpub';
 2186:                     } else {
 2187:                         $publishthis=1;
 2188:                     }
 2189: 		}
 2190: 		
 2191: 		if ($publishthis) {
 2192: 		    &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
 2193: 		} else {
 2194:                     my $reason;
 2195:                     if ($skipthis) {
 2196:                         $reason = $reasons{$skipthis};
 2197:                     } else {
 2198:                         $reason = &mt('No changes needed to published resource or metadata');
 2199:                     }
 2200:                     $r->print('<br />'.&mt('Skipping').' '.$filename);
 2201:                     if ($reason) {
 2202:                         $r->print(' ('.$reason.')');
 2203:                     }
 2204:                     $r->print('<br />');
 2205: 		}
 2206: 		$r->rflush();
 2207: 	    }
 2208: 	}
 2209: 	closedir(DIR);
 2210:     }
 2211: }
 2212: 
 2213: #########################################
 2214: # publish a default.meta file
 2215: 
 2216: sub defaultmetapublish {
 2217:     my ($r,$fn,$cuname,$cudom)=@_;
 2218:     unless (-e $fn) {
 2219:        return HTTP_NOT_FOUND;
 2220:     }
 2221:     my $target=$fn;
 2222:     $target=~s/^\Q$Apache::lonnet::perlvar{'lonDocRoot'}\E\/priv\//\Q$Apache::lonnet::perlvar{'lonDocRoot'}\E\/res\//;
 2223: 
 2224: 
 2225:     &Apache::loncommon::content_type($r,'text/html');
 2226:     $r->send_http_header;
 2227: 
 2228:     $r->print(&Apache::loncommon::start_page('Metadata Publication'));
 2229: 
 2230: # ---------------------------------------------------------------- Write Source
 2231:     my $copyfile=$target;
 2232:     
 2233:     my @parts=split(/\//,$copyfile);
 2234:     my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2235:     
 2236:     my $count;
 2237:     for ($count=5;$count<$#parts;$count++) {
 2238:         $path.="/$parts[$count]";
 2239:         if ((-e $path)!=1) {
 2240:             mkdir($path,0777);
 2241:             $r->print('<p>'
 2242:                      .&mt('Created directory [_1]'
 2243:                          ,'<span class="LC_filename">'.$parts[$count].'</span>')
 2244:                      .'</p>'
 2245:             );
 2246:         }
 2247:     }
 2248:     
 2249:     if (copy($fn,$copyfile)) {
 2250:         $r->print('<p>'.&mt('Copied source file').'</p>');
 2251:     } else {
 2252:         return "<span class=\"LC_error\">".
 2253: 	    &mt('Failed to copy source').", $!, ".&mt('FAIL')."</span>";
 2254:     }
 2255: 
 2256: # --------------------------------------------------- Send update notifications
 2257: 
 2258:     my @subscribed=&get_subscribed_hosts($target);
 2259:     foreach my $subhost (@subscribed) {
 2260: 	$r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
 2261: 	my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 2262: 	$r->print($reply.'</p><br />');$r->rflush;
 2263:     }
 2264: # ------------------------------------------------------------------- Link back
 2265:     $r->print("<a href='".&Apache::loncfile::display($fn)."'>".&mt('Back to Metadata').'</a>');
 2266:     $r->print(&Apache::loncommon::end_page());
 2267:     return OK;
 2268: }
 2269: #########################################
 2270: 
 2271: =pod
 2272: 
 2273: =item B<handler>
 2274: 
 2275: A basic outline of the handler subroutine follows.
 2276: 
 2277: =over 4
 2278: 
 2279: =item *
 2280: 
 2281: Get query string for limited number of parameters.
 2282: 
 2283: =item *
 2284: 
 2285: Check filename.
 2286: 
 2287: =item *
 2288: 
 2289: File is there and owned, init lookup tables.
 2290: 
 2291: =item *
 2292: 
 2293: Start page output.
 2294: 
 2295: =item *
 2296: 
 2297: Evaluate individual file, and then output information.
 2298: 
 2299: =item *
 2300: 
 2301: Publishing from $thisfn to $thistarget with $thisembstyle.
 2302: 
 2303: =back
 2304: 
 2305: =cut
 2306: 
 2307: #########################################
 2308: #########################################
 2309: sub handler {
 2310:     my $r=shift;
 2311: 
 2312:     if ($r->header_only) {
 2313: 	&Apache::loncommon::content_type($r,'text/html');
 2314: 	$r->send_http_header;
 2315: 	return OK;
 2316:     }
 2317: 
 2318: # Get query string for limited number of parameters
 2319: 
 2320:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2321:                                             ['filename']);
 2322: 
 2323: # -------------------------------------- Flag and buffer for registered cleanup
 2324:     $registered_cleanup=0;
 2325:     @{$modified_urls}=();
 2326: # -------------------------------------------------------------- Check filename
 2327: 
 2328:     my $fn=&unescape($env{'form.filename'});
 2329:     ($cuname,$cudom)=&Apache::lonnet::constructaccess($fn);
 2330: # ----------------------------------------------------- Do we have permissions?
 2331:      unless (($cuname) && ($cudom)) {
 2332:        $r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
 2333:                       ' trying to publish file '.$env{'form.filename'}.
 2334:                       ' - not authorized', 
 2335:                       $r->filename); 
 2336:        return HTTP_NOT_ACCEPTABLE;
 2337:      }
 2338: # ----------------------------------------------------------------- Get docroot
 2339:     $docroot=$r->dir_config('lonDocRoot');
 2340: 
 2341: 
 2342: # special publication: default.meta file
 2343:     if ($fn=~/\/default.meta$/) {
 2344: 	return &defaultmetapublish($r,$fn,$cuname,$cudom); 
 2345:     }
 2346:     $fn=~s/\.meta$//;
 2347: 
 2348: # sanity test on the filename 
 2349:  
 2350:     unless ($fn) { 
 2351: 	$r->log_reason($cuname.' at '.$cudom.
 2352: 		       ' trying to publish empty filename', $r->filename); 
 2353: 	return HTTP_NOT_FOUND;
 2354:     } 
 2355: 
 2356:     unless (-e $docroot.$fn) { 
 2357: 	$r->log_reason($cuname.' at '.$cudom.
 2358: 		       ' trying to publish non-existing file '.
 2359: 		       $env{'form.filename'}.' ('.$fn.')', 
 2360: 		       $r->filename); 
 2361: 	return HTTP_NOT_FOUND;
 2362:     } 
 2363: 
 2364: # -------------------------------- File is there and owned, init lookup tables.
 2365: 
 2366:     %addid=();
 2367:     
 2368:     {
 2369: 	my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
 2370: 	while (<$fh>=~/(\w+)\s+(\w+)/) {
 2371: 	    $addid{$1}=$2;
 2372: 	}
 2373:     }
 2374: 
 2375:     %nokey=();
 2376: 
 2377:     {
 2378: 	my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
 2379: 	while (<$fh>) {
 2380: 	    my $word=$_;
 2381: 	    chomp($word);
 2382: 	    $nokey{$word}=1;
 2383: 	}
 2384:     }
 2385: 
 2386: # ---------------------------------------------------------- Start page output.
 2387: 
 2388:     &Apache::loncommon::content_type($r,'text/html');
 2389:     $r->send_http_header;
 2390:     
 2391:     # Breadcrumbs
 2392:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 2393:     &Apache::lonhtmlcommon::add_breadcrumb({
 2394:         'text'  => 'Authoring Space',
 2395:         'href'  => &Apache::loncommon::authorspace($fn),
 2396:     });
 2397:     &Apache::lonhtmlcommon::add_breadcrumb({
 2398:         'text'  => 'Resource Publication',
 2399:         'href'  => '',
 2400:     });
 2401: 
 2402:     my $js='<script type="text/javascript">'.
 2403: 	&Apache::loncommon::browser_and_searcher_javascript().
 2404: 	'</script>';
 2405:     my $startargs = {};
 2406:     if ($fn=~/\/$/) {
 2407:         unless ($env{'form.phase'} eq 'two') {
 2408:             $startargs->{'add_entries'} = { onload => 'javascript:setDefaultAccess();' };
 2409:             $js .= <<"END";
 2410: <script type="text/javascript">
 2411: // <![CDATA[
 2412: function showHideAccess(caller,div) {
 2413:     if (document.getElementById(div)) {
 2414:         if (caller.checked) {
 2415:             document.getElementById(div).style.display='inline-block';
 2416:         } else {
 2417:             document.getElementById(div).style.display='none';
 2418:         }
 2419:     }
 2420: }
 2421: 
 2422: function showHideCustom(caller,divid) {
 2423:     if (document.getElementById(divid)) {
 2424:         if (caller.options[caller.selectedIndex].value == 'custom') {
 2425:             document.getElementById(divid).style.display="inline-block";
 2426:         } else {
 2427:             document.getElementById(divid).style.display="none";
 2428:         }
 2429:     }
 2430: }
 2431: function setDefaultAccess() {
 2432:     var chkids = Array('LC_commondist','LC_commonsource');
 2433:     for (var i=0; i<chkids.length; i++) {
 2434:         if (document.getElementById(chkids[i])) {
 2435:             document.getElementById(chkids[i]).checked = false;
 2436:         }
 2437:         if (document.getElementById(chkids[i]+'select')) {
 2438:            document.getElementById(chkids[i]+'select').selectedIndex = 0; 
 2439:         }
 2440:         if (document.getElementById(chkids[i]+'div')) {
 2441:             document.getElementById(chkids[i]+'div').style.display = 'none';
 2442:         }
 2443:     }
 2444: }
 2445: // ]]>
 2446: </script>
 2447: 
 2448: END
 2449:         }
 2450:     }
 2451:     $r->print(&Apache::loncommon::start_page('Resource Publication',$js,$startargs)
 2452:              .&Apache::lonhtmlcommon::breadcrumbs()
 2453:              .&Apache::loncommon::head_subbox(
 2454:                   &Apache::loncommon::CSTR_pageheader($docroot.$fn))
 2455:     );
 2456: 
 2457:     my $thisdisfn=&HTML::Entities::encode($fn,'<>&"');
 2458:     my $thistarget=$fn;
 2459:     $thistarget=~s/^\/priv\//\/res\//;
 2460:     my $thisdistarget=&HTML::Entities::encode($thistarget,'<>&"');
 2461: 
 2462:     if ($fn=~/\/$/) {
 2463: # -------------------------------------------------------- This is a directory
 2464: 	&publishdirectory($r,$docroot.$fn,$thisdisfn);
 2465:         $r->print(
 2466:             '<br /><br />'.
 2467:             &Apache::lonhtmlcommon::actionbox([
 2468:                 '<a href="'.$thisdisfn.'">'.&mt('Return to Directory').'</a>']));
 2469:     } else {
 2470: # ---------------------- Evaluate individual file, and then output information.
 2471: 	$fn=~/\.(\w+)$/;
 2472: 	my $thistype=$1;
 2473: 	my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
 2474:         if ($thistype eq 'page') {  $thisembstyle = 'rat'; }
 2475: 
 2476:         $r->print('<h2>'
 2477:                  .&mt('Publishing [_1]'
 2478:                      ,'<span class="LC_filename">'.$thisdisfn.'</span>')
 2479:                  .'</h2>'
 2480:         );
 2481: 
 2482:         $r->print('<h3>'.&mt('Resource Details').'</h3>');
 2483: 
 2484:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
 2485: 
 2486:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Type'))
 2487:                  .&Apache::loncommon::filedescription($thistype)
 2488:                  .&Apache::lonhtmlcommon::row_closure()
 2489:                  );
 2490: 
 2491:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Link to Resource'))
 2492:                  .'<tt>'
 2493:                  );
 2494: 	$r->print(<<ENDCAPTION);
 2495: <a href='javascript:void(window.open("$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
 2496: $thisdisfn</a>
 2497: ENDCAPTION
 2498:         $r->print('</tt>'
 2499:                  .&Apache::lonhtmlcommon::row_closure()
 2500:                  );
 2501: 
 2502:         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Target'))
 2503:                  .'<tt>'.$thisdistarget.'</tt>'
 2504:                  );
 2505: 	if (($cuname ne $env{'user.name'})||($cudom ne $env{'user.domain'})) {
 2506:             $r->print(&Apache::lonhtmlcommon::row_closure()
 2507:                      .&Apache::lonhtmlcommon::row_title(&mt('Co-Author'))
 2508:                      .'<span class="LC_warning">'
 2509: 		     .&Apache::loncommon::plainname($cuname,$cudom) .' ('.$cuname.':'.$cudom.')'
 2510:                      .'</span>'
 2511:                      );
 2512: 	}
 2513: 
 2514: 	if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
 2515:             $r->print(&Apache::lonhtmlcommon::row_closure()
 2516:                      .&Apache::lonhtmlcommon::row_title(&mt('Diffs')));
 2517: 	    $r->print(<<ENDDIFF);
 2518: <a href='javascript:void(window.open("/adm/diff?filename=$thisdisfn&amp;versiontwo=priv","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
 2519: ENDDIFF
 2520:             $r->print(&mt('Diffs with Current Version').'</a>');
 2521: 	}
 2522:         
 2523:         $r->print(&Apache::lonhtmlcommon::row_closure(1)
 2524:                  .&Apache::lonhtmlcommon::end_pick_box()
 2525:                  );
 2526:   
 2527: # ---------------------- Publishing from $fn to $thistarget with $thisembstyle.
 2528: 
 2529: 	unless ($env{'form.phase'} eq 'two') {
 2530: # ---------------------------------------------------------- Parse for problems
 2531: 	    my ($warningcount,$errorcount);
 2532: 	    if ($thisembstyle eq 'ssi') {
 2533: 		($warningcount,$errorcount)=&checkonthis($r,$fn);
 2534: 	    }
 2535: 	    unless ($errorcount) {
 2536: 		my ($outstring,$error)=
 2537: 		    &publish($docroot.$fn,$docroot.$thistarget,$thisembstyle);
 2538: 		$r->print($outstring);
 2539: 	    } else {
 2540: 		$r->print('<h3 class="LC_error">'.
 2541: 			  &mt('The document contains errors and cannot be published.').
 2542: 			  '</h3>');
 2543: 	    }
 2544: 	} else {
 2545: 	    &phasetwo($r,$docroot.$fn,$docroot.$thistarget,$thisembstyle,$thisdistarget); 
 2546: 	}
 2547:     }
 2548:     $r->print(&Apache::loncommon::end_page());
 2549: 
 2550:     return OK;
 2551: }
 2552: 
 2553: 1;
 2554: __END__
 2555: 
 2556: =pod
 2557: 
 2558: =back
 2559: 
 2560: =cut
 2561: 

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