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