1: # The LearningOnline Network with CAPA
2: # Publication Handler
3: #
4: # $Id: lonpublisher.pm,v 1.141 2003/11/01 17:09:52 www 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: # (TeX Content Handler
30: #
31: # 05/29/00,05/30,10/11 Gerd Kortemeyer)
32: #
33: # 11/28,11/29,11/30,12/01,12/02,12/04,12/23 Gerd Kortemeyer
34: # 03/23 Guy Albertelli
35: # 03/24,03/29,04/03 Gerd Kortemeyer
36: # 05/03,05/05,05/07 Gerd Kortemeyer
37: # 06/23,08/07,08/11,8/13,8/17,8/18,8/24,9/26,10/16 Gerd Kortemeyer
38: # 12/04,12/05 Guy Albertelli
39: # 12/05 Gerd Kortemeyer
40: # 12/05 Guy Albertelli
41: # 12/06,12/07 Gerd Kortemeyer
42: # 12/25 Gerd Kortemeyer
43: # YEAR=2002
44: # 1/17 Gerd Kortemeyer
45: #
46: ###
47:
48: ###############################################################################
49: ## ##
50: ## ORGANIZATION OF THIS PERL MODULE ##
51: ## ##
52: ## 1. Modules used by this module ##
53: ## 2. Various subroutines ##
54: ## 3. Publication Step One ##
55: ## 4. Phase Two ##
56: ## 5. Main Handler ##
57: ## ##
58: ###############################################################################
59:
60:
61: ######################################################################
62: ######################################################################
63:
64: =pod
65:
66: =head1 NAME
67:
68: lonpublisher - LON-CAPA publishing handler
69:
70: =head1 SYNOPSIS
71:
72: B<lonpublisher> is used by B<mod_perl> inside B<Apache>. This is the
73: invocation by F<loncapa_apache.conf>:
74:
75: <Location /adm/publish>
76: PerlAccessHandler Apache::lonacc
77: SetHandler perl-script
78: PerlHandler Apache::lonpublisher
79: ErrorDocument 403 /adm/login
80: ErrorDocument 404 /adm/notfound.html
81: ErrorDocument 406 /adm/unauthorized.html
82: ErrorDocument 500 /adm/errorhandler
83: </Location>
84:
85: =head1 OVERVIEW
86:
87: Authors can only write-access the C</~authorname/> space. They can
88: copy resources into the resource area through the publication step,
89: and move them back through a recover step. Authors do not have direct
90: write-access to their resource space.
91:
92: During the publication step, several events will be
93: triggered. Metadata is gathered, where a wizard manages default
94: entries on a hierarchical per-directory base: The wizard imports the
95: metadata (including access privileges and royalty information) from
96: the most recent published resource in the current directory, and if
97: that is not available, from the next directory above, etc. The Network
98: keeps all previous versions of a resource and makes them available by
99: an explicit version number, which is inserted between the file name
100: and extension, for example C<foo.2.html>, while the most recent
101: version does not carry a version number (C<foo.html>). Servers
102: subscribing to a changed resource are notified that a new version is
103: available.
104:
105: =head1 DESCRIPTION
106:
107: B<lonpublisher> takes the proper steps to add resources to the LON-CAPA
108: digital library. This includes updating the metadata table in the
109: LON-CAPA database.
110:
111: B<lonpublisher> is many things to many people.
112:
113: This module publishes a file. This involves gathering metadata,
114: versioning the file, copying file from construction space to
115: publication space, and copying metadata from construction space
116: to publication space.
117:
118: =head2 SUBROUTINES
119:
120: Many of the undocumented subroutines implement various magical
121: parsing shortcuts.
122:
123: =over 4
124:
125: =cut
126:
127: ######################################################################
128: ######################################################################
129:
130:
131: package Apache::lonpublisher;
132:
133: # ------------------------------------------------- modules used by this module
134: use strict;
135: use Apache::File;
136: use File::Copy;
137: use Apache::Constants qw(:common :http :methods);
138: use HTML::LCParser;
139: use Apache::lonxml;
140: use Apache::loncacc;
141: use DBI;
142: use Apache::lonnet();
143: use Apache::loncommon();
144: use Apache::lonmysql;
145: use Apache::lonlocal;
146: use vars qw(%metadatafields %metadatakeys);
147:
148: my %addid;
149: my %nokey;
150:
151: my $docroot;
152:
153: my $cuname;
154: my $cudom;
155:
156: =pod
157:
158: =item B<metaeval>
159:
160: Evaluates a string that contains metadata. This subroutine
161: stores values inside I<%metadatafields> and I<%metadatakeys>.
162: The hash key is a I<$unikey> corresponding to a unique id
163: that is descriptive of the parser location inside the XML tree.
164:
165: Parameters:
166:
167: =over 4
168:
169: =item I<$metastring>
170:
171: A string that contains metadata.
172:
173: =back
174:
175: Returns:
176:
177: nothing
178:
179: =cut
180:
181: #########################################
182: #########################################
183: sub metaeval {
184: my ($metastring,$prefix)=@_;
185:
186: my $parser=HTML::LCParser->new(\$metastring);
187: my $token;
188: while ($token=$parser->get_token) {
189: if ($token->[0] eq 'S') {
190: my $entry=$token->[1];
191: my $unikey=$entry;
192: if (defined($token->[2]->{'package'})) {
193: $unikey.='_package_'.$token->[2]->{'package'};
194: }
195: if (defined($token->[2]->{'part'})) {
196: $unikey.='_'.$token->[2]->{'part'};
197: }
198: if (defined($token->[2]->{'id'})) {
199: $unikey.='_'.$token->[2]->{'id'};
200: }
201: if (defined($token->[2]->{'name'})) {
202: $unikey.='_'.$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: $newentry=~s/^\s*//;
215: if ($newentry !~m|^/res|) { $newentry=$prefix.$newentry; }
216: }
217: if ($metadatafields{$unikey}) {
218: unless (($metadatafields{$unikey}=~/\Q$newentry\E/) ||
219: ($newentry eq '')) {
220: $metadatafields{$unikey}.=', '.$newentry;
221: }
222: } else {
223: $metadatafields{$unikey}=$newentry;
224: }
225: }
226: }
227: }
228:
229: #########################################
230: #########################################
231:
232: =pod
233:
234: =item B<metaread>
235:
236: Read a metadata file
237:
238: Parameters:
239:
240: =over
241:
242: =item I<$logfile>
243:
244: File output stream to output errors and warnings to.
245:
246: =item I<$fn>
247:
248: File name (including path).
249:
250: =back
251:
252: Returns:
253:
254: =over 4
255:
256: =item Scalar string (if successful)
257:
258: XHTML text that indicates successful reading of the metadata.
259:
260: =back
261:
262: =cut
263:
264: #########################################
265: #########################################
266: sub metaread {
267: my ($logfile,$fn,$prefix)=@_;
268: unless (-e $fn) {
269: print($logfile 'No file '.$fn."\n");
270: return '<br /><b>No file:</b> <tt>'.$fn.'</tt>';
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 '<br /><b>Processed file:</b> <tt>'.$fn.'</tt>';
280: }
281:
282: #########################################
283: #########################################
284:
285: sub coursedependencies {
286: my $url=&Apache::lonnet::declutter(shift);
287: $url=~s/\.meta$//;
288: my ($adomain,$aauthor)=($url=~/^(\w+)\/(\w+)\//);
289: my $regexp=$url;
290: $regexp=~s/(\W)/\\$1/g;
291: $regexp='___'.$regexp.'___course';
292: my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
293: $aauthor,$regexp);
294: my %courses=();
295: foreach (keys %evaldata) {
296: if ($_=~/^([a-zA-Z0-9]+_[a-zA-Z0-9]+)___.+___course$/) {
297: $courses{$1}=1;
298: }
299: }
300: return %courses;
301: }
302: #########################################
303: #########################################
304:
305:
306: =pod
307:
308: =item Form-field-generating subroutines.
309:
310: For input parameters, these subroutines take in values
311: such as I<$name>, I<$value> and other form field metadata.
312: The output (scalar string that is returned) is an XHTML
313: string which presents the form field (foreseeably inside
314: <form></form> tags).
315:
316: =over 4
317:
318: =item B<textfield>
319:
320: =item B<hiddenfield>
321:
322: =item B<selectbox>
323:
324: =back
325:
326: =cut
327:
328: #########################################
329: #########################################
330: sub textfield {
331: my ($title,$name,$value)=@_;
332: $value=~s/^\s+//gs;
333: $value=~s/\s+$//gs;
334: $value=~s/\s+/ /gs;
335: $title=&mt($title);
336: my $uctitle=uc($title);
337: return "\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
338: "</b></font></p><br />".
339: '<input type="text" name="'.$name.'" size=80 value="'.$value.'" />';
340: }
341:
342: sub hiddenfield {
343: my ($name,$value)=@_;
344: return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
345: }
346:
347: sub selectbox {
348: my ($title,$name,$value,$functionref,@idlist)=@_;
349: $title=&mt($title);
350: my $uctitle=uc($title);
351: $value=(split(/\s*,\s*/,$value))[-1];
352: my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
353: '</b></font></p><br /><select name="'.$name.'">';
354: foreach (@idlist) {
355: $selout.='<option value=\''.$_.'\'';
356: if ($_ eq $value) {
357: $selout.=' selected>'.&{$functionref}($_).'</option>';
358: }
359: else {$selout.='>'.&{$functionref}($_).'</option>';}
360: }
361: return $selout.'</select>';
362: }
363:
364: #########################################
365: #########################################
366:
367: =pod
368:
369: =item B<urlfixup>
370:
371: Fix up a url? First step of publication
372:
373: =cut
374:
375: #########################################
376: #########################################
377: sub urlfixup {
378: my ($url,$target)=@_;
379: unless ($url) { return ''; }
380: #javascript code needs no fixing
381: if ($url =~ /^javascript:/i) { return $url; }
382: if ($url =~ /^mailto:/i) { return $url; }
383: #internal document links need no fixing
384: if ($url =~ /^\#/) { return $url; }
385: my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
386: foreach (values %Apache::lonnet::hostname) {
387: if ($_ eq $host) {
388: $url=~s/^http\:\/\///;
389: $url=~s/^$host//;
390: }
391: }
392: if ($url=~/^http\:\/\//) { return $url; }
393: $url=~s/\~$cuname/res\/$cudom\/$cuname/;
394: return $url;
395: }
396:
397: #########################################
398: #########################################
399:
400: =pod
401:
402: =item B<absoluteurl>
403:
404: Currently undocumented.
405:
406: =cut
407:
408: #########################################
409: #########################################
410: sub absoluteurl {
411: my ($url,$target)=@_;
412: unless ($url) { return ''; }
413: if ($target) {
414: $target=~s/\/[^\/]+$//;
415: $url=&Apache::lonnet::hreflocation($target,$url);
416: }
417: return $url;
418: }
419:
420: #########################################
421: #########################################
422:
423: =pod
424:
425: =item B<set_allow>
426:
427: Currently undocumented
428:
429: =cut
430:
431: #########################################
432: #########################################
433: sub set_allow {
434: my ($allow,$logfile,$target,$tag,$oldurl)=@_;
435: my $newurl=&urlfixup($oldurl,$target);
436: my $return_url=$oldurl;
437: print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
438: if ($newurl ne $oldurl) {
439: $return_url=$newurl;
440: print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
441: }
442: if (($newurl !~ /^javascript:/i) &&
443: ($newurl !~ /^mailto:/i) &&
444: ($newurl !~ /^http:/i) &&
445: ($newurl !~ /^\#/)) {
446: $$allow{&absoluteurl($newurl,$target)}=1;
447: }
448: return $return_url
449: }
450:
451: #########################################
452: #########################################
453:
454: =pod
455:
456: =item B<get_subscribed_hosts>
457:
458: Currently undocumented
459:
460: =cut
461:
462: #########################################
463: #########################################
464: sub get_subscribed_hosts {
465: my ($target)=@_;
466: my @subscribed;
467: my $filename;
468: $target=~/(.*)\/([^\/]+)$/;
469: my $srcf=$2;
470: opendir(DIR,$1);
471: while ($filename=readdir(DIR)) {
472: if ($filename=~/\Q$srcf\E\.(\w+)$/) {
473: my $subhost=$1;
474: if (($subhost ne 'meta' && $subhost ne 'subscription') &&
475: ($subhost ne $Apache::lonnet::perlvar{'lonHostID'})) {
476: push(@subscribed,$subhost);
477: }
478: }
479: }
480: closedir(DIR);
481: my $sh;
482: if ( $sh=Apache::File->new("$target.subscription") ) {
483: &Apache::lonnet::logthis("opened $target.subscription");
484: while (my $subline=<$sh>) {
485: &Apache::lonnet::logthis("Trying $subline");
486: if ($subline =~ /(^\w+):/) {
487: if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) {
488: push(@subscribed,$1);
489: }
490: } else {
491: &Apache::lonnet::logthis("No Match for $subline");
492: }
493: }
494: } else {
495: &Apache::lonnet::logthis("Unable to open $target.subscription");
496: }
497: return @subscribed;
498: }
499:
500:
501: #########################################
502: #########################################
503:
504: =pod
505:
506: =item B<get_max_ids_indices>
507:
508: Currently undocumented
509:
510: =cut
511:
512: #########################################
513: #########################################
514: sub get_max_ids_indices {
515: my ($content)=@_;
516: my $maxindex=10;
517: my $maxid=10;
518: my $needsfixup=0;
519: my $duplicateids=0;
520:
521: my %allids;
522: my %duplicatedids;
523:
524: my $parser=HTML::LCParser->new($content);
525: my $token;
526: while ($token=$parser->get_token) {
527: if ($token->[0] eq 'S') {
528: my $counter;
529: if ($counter=$addid{$token->[1]}) {
530: if ($counter eq 'id') {
531: if (defined($token->[2]->{'id'})) {
532: $maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
533: if (exists($allids{$token->[2]->{'id'}})) {
534: $duplicateids=1;
535: $duplicatedids{$token->[2]->{'id'}}=1;
536: } else {
537: $allids{$token->[2]->{'id'}}=1;
538: }
539: } else {
540: $needsfixup=1;
541: }
542: } else {
543: if (defined($token->[2]->{'index'})) {
544: $maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
545: } else {
546: $needsfixup=1;
547: }
548: }
549: }
550: }
551: }
552: return ($needsfixup,$maxid,$maxindex,$duplicateids,
553: (keys(%duplicatedids)));
554: }
555:
556: #########################################
557: #########################################
558:
559: =pod
560:
561: =item B<get_all_text_unbalanced>
562:
563: Currently undocumented
564:
565: =cut
566:
567: #########################################
568: #########################################
569: sub get_all_text_unbalanced {
570: #there is a copy of this in lonxml.pm
571: my($tag,$pars)= @_;
572: my $token;
573: my $result='';
574: $tag='<'.$tag.'>';
575: while ($token = $$pars[-1]->get_token) {
576: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
577: $result.=$token->[1];
578: } elsif ($token->[0] eq 'PI') {
579: $result.=$token->[2];
580: } elsif ($token->[0] eq 'S') {
581: $result.=$token->[4];
582: } elsif ($token->[0] eq 'E') {
583: $result.=$token->[2];
584: }
585: if ($result =~ /(.*)\Q$tag\E(.*)/s) {
586: #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
587: #&Apache::lonnet::logthis('Result is :'.$1);
588: $result=$1;
589: my $redo=$tag.$2;
590: push (@$pars,HTML::LCParser->new(\$redo));
591: $$pars[-1]->xml_mode('1');
592: last;
593: }
594: }
595: return $result
596: }
597:
598: #########################################
599: #########################################
600:
601: =pod
602:
603: =item B<fix_ids_and_indices>
604:
605: Currently undocumented
606:
607: =cut
608:
609: #########################################
610: #########################################
611: #Arguably this should all be done as a lonnet::ssi instead
612: sub fix_ids_and_indices {
613: my ($logfile,$source,$target)=@_;
614:
615: my %allow;
616: my $content;
617: {
618: my $org=Apache::File->new($source);
619: $content=join('',<$org>);
620: }
621:
622: my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
623: &get_max_ids_indices(\$content);
624:
625: print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
626: join(', ',@duplicatedids));
627: if ($duplicateids) {
628: print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
629: my $outstring='<font color="red">Unable to publish file, it contains duplicated ID(s), ID(s) need to be unique. The duplicated ID(s) are: '.join(', ',@duplicatedids).'</font>';
630: return ($outstring,1);
631: }
632: if ($needsfixup) {
633: print $logfile "Needs ID and/or index fixup\n".
634: "Max ID : $maxid (min 10)\n".
635: "Max Index: $maxindex (min 10)\n";
636: }
637: my $outstring='';
638: my @parser;
639: $parser[0]=HTML::LCParser->new(\$content);
640: $parser[-1]->xml_mode(1);
641: my $token;
642: while (@parser) {
643: while ($token=$parser[-1]->get_token) {
644: if ($token->[0] eq 'S') {
645: my $counter;
646: my $tag=$token->[1];
647: my $lctag=lc($tag);
648: if ($lctag eq 'allow') {
649: $allow{$token->[2]->{'src'}}=1;
650: next;
651: }
652: my %parms=%{$token->[2]};
653: $counter=$addid{$tag};
654: if (!$counter) { $counter=$addid{$lctag}; }
655: if ($counter) {
656: if ($counter eq 'id') {
657: unless (defined($parms{'id'})) {
658: $maxid++;
659: $parms{'id'}=$maxid;
660: print $logfile 'ID: '.$tag.':'.$maxid."\n";
661: }
662: } elsif ($counter eq 'index') {
663: unless (defined($parms{'index'})) {
664: $maxindex++;
665: $parms{'index'}=$maxindex;
666: print $logfile 'Index: '.$tag.':'.$maxindex."\n";
667: }
668: }
669: }
670: foreach my $type ('src','href','background','bgimg') {
671: foreach my $key (keys(%parms)) {
672: if ($key =~ /^$type$/i) {
673: $parms{$key}=&set_allow(\%allow,$logfile,
674: $target,$tag,
675: $parms{$key});
676: }
677: }
678: }
679: # probably a <randomlabel> image type <label>
680: # or a <image> tag inside <imageresponse>
681: if (($lctag eq 'label' && defined($parms{'description'}))
682: ||
683: ($lctag eq 'image')) {
684: my $next_token=$parser[-1]->get_token();
685: if ($next_token->[0] eq 'T') {
686: $next_token->[1]=&set_allow(\%allow,$logfile,
687: $target,$tag,
688: $next_token->[1]);
689: }
690: $parser[-1]->unget_token($next_token);
691: }
692: if ($lctag eq 'applet') {
693: my $codebase='';
694: if (defined($parms{'codebase'})) {
695: my $oldcodebase=$parms{'codebase'};
696: unless ($oldcodebase=~/\/$/) {
697: $oldcodebase.='/';
698: }
699: $codebase=&urlfixup($oldcodebase,$target);
700: $codebase=~s/\/$//;
701: if ($codebase ne $oldcodebase) {
702: $parms{'codebase'}=$codebase;
703: print $logfile 'URL codebase: '.$tag.':'.
704: $oldcodebase.' - '.
705: $codebase."\n";
706: }
707: $allow{&absoluteurl($codebase,$target).'/*'}=1;
708: } else {
709: foreach ('archive','code','object') {
710: if (defined($parms{$_})) {
711: my $oldurl=$parms{$_};
712: my $newurl=&urlfixup($oldurl,$target);
713: $newurl=~s/\/[^\/]+$/\/\*/;
714: print $logfile 'Allow: applet '.$_.':'.
715: $oldurl.' allows '.
716: $newurl."\n";
717: $allow{&absoluteurl($newurl,$target)}=1;
718: }
719: }
720: }
721: }
722: my $newparmstring='';
723: my $endtag='';
724: foreach (keys %parms) {
725: if ($_ eq '/') {
726: $endtag=' /';
727: } else {
728: my $quote=($parms{$_}=~/\"/?"'":'"');
729: $newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
730: }
731: }
732: if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
733: $outstring.='<'.$tag.$newparmstring.$endtag.'>';
734: if ($lctag eq 'm' || $lctag eq 'script'
735: || $lctag eq 'display' || $lctag eq 'tex') {
736: $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
737: }
738: } elsif ($token->[0] eq 'E') {
739: if ($token->[2]) {
740: unless ($token->[1] eq 'allow') {
741: $outstring.='</'.$token->[1].'>';
742: }
743: }
744: } else {
745: $outstring.=$token->[1];
746: }
747: }
748: pop(@parser);
749: }
750:
751: if ($needsfixup) {
752: print $logfile "End of ID and/or index fixup\n".
753: "Max ID : $maxid (min 10)\n".
754: "Max Index: $maxindex (min 10)\n";
755: } else {
756: print $logfile "Does not need ID and/or index fixup\n";
757: }
758:
759: return ($outstring,0,%allow);
760: }
761:
762: #########################################
763: #########################################
764:
765: =pod
766:
767: =item B<store_metadata>
768:
769: Store the metadata in the metadata table in the loncapa database.
770: Uses lonmysql to access the database.
771:
772: Inputs: \%metadata
773:
774: Returns: (error,status). error is undef on success, status is undef on error.
775:
776: =cut
777:
778: #########################################
779: #########################################
780: sub store_metadata {
781: my %metadata = %{shift()};
782: my $error;
783: # Determine if the table exists
784: my $status = &Apache::lonmysql::check_table('metadata');
785: if (! defined($status)) {
786: $error='<font color="red">WARNING: Cannot connect to '.
787: 'database!</font>';
788: &Apache::lonnet::logthis($error);
789: return ($error,undef);
790: }
791: if ($status == 0) {
792: # It would be nice to actually create the table....
793: $error ='<font color="red">WARNING: The metadata table does not '.
794: 'exist in the LON-CAPA database.</font>';
795: &Apache::lonnet::logthis($error);
796: return ($error,undef);
797: }
798: # Remove old value from table
799: $status = &Apache::lonmysql::remove_from_table
800: ('metadata','url',$metadata{'url'});
801: if (! defined($status)) {
802: $error = '<font color="red">Error when removing old values from '.
803: 'metadata table in LON-CAPA database.</font>';
804: &Apache::lonnet::logthis($error);
805: return ($error,undef);
806: }
807: # Store data in table.
808: $status = &Apache::lonmysql::store_row('metadata',\%metadata);
809: if (! defined($status)) {
810: $error='<font color="red">Error occured storing new values in '.
811: 'metadata table in LON-CAPA database</font>';
812: &Apache::lonnet::logthis($error);
813: return ($error,undef);
814: }
815: return (undef,$status);
816: }
817:
818: #########################################
819: #########################################
820:
821: =pod
822:
823: =item B<publish>
824:
825: This is the workhorse function of this module. This subroutine generates
826: backup copies, performs any automatic processing (prior to publication,
827: especially for rat and ssi files),
828:
829: Returns a 2 element array, the first is the string to be shown to the
830: user, the second is an error code, either 1 (an error occured) or 0
831: (no error occurred)
832:
833: I<Additional documentation needed.>
834:
835: =cut
836:
837: #########################################
838: #########################################
839: sub publish {
840:
841: my ($source,$target,$style,$batch)=@_;
842: my $logfile;
843: my $scrout='';
844: my $allmeta='';
845: my $content='';
846: my %allow=();
847:
848: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
849: return ('<font color="red">No write permission to user directory, FAIL</font>',1);
850: }
851: print $logfile
852: "\n\n================= Publish ".localtime()." Phase One ================\n".$ENV{'user.name'}.'@'.$ENV{'user.domain'}."\n";
853:
854: if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
855: # ------------------------------------------------------- This needs processing
856:
857: # ----------------------------------------------------------------- Backup Copy
858: my $copyfile=$source.'.save';
859: if (copy($source,$copyfile)) {
860: print $logfile "Copied original file to ".$copyfile."\n";
861: } else {
862: print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
863: return ("<font color=\"red\">Failed to write backup copy, $!,FAIL</font>",1);
864: }
865: # ------------------------------------------------------------- IDs and indices
866:
867: my ($outstring,$error);
868: ($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
869: $target);
870: if ($error) { return ($outstring,$error); }
871: # ------------------------------------------------------------ Construct Allows
872:
873: $scrout.='<h3>Dependencies</h3>';
874: my $allowstr='';
875: foreach (sort(keys(%allow))) {
876: my $thisdep=$_;
877: if ($thisdep !~ /[^\s]/) { next; }
878: unless ($style eq 'rat') {
879: $allowstr.="\n".'<allow src="'.$thisdep.'" />';
880: }
881: $scrout.='<br />';
882: unless ($thisdep=~/\*/) {
883: $scrout.='<a href="'.$thisdep.'">';
884: }
885: $scrout.='<tt>'.$thisdep.'</tt>';
886: unless ($thisdep=~/\*/) {
887: $scrout.='</a>';
888: if (
889: &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
890: $thisdep.'.meta') eq '-1') {
891: $scrout.= ' - <font color="red">Currently not available'.
892: '</font>';
893: } else {
894: my %temphash=(&Apache::lonnet::declutter($target).'___'.
895: &Apache::lonnet::declutter($thisdep).'___usage'
896: => time);
897: $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
898: if ((defined($1)) && (defined($2))) {
899: &Apache::lonnet::put('nohist_resevaldata',\%temphash,
900: $1,$2);
901: }
902: }
903: }
904: }
905: $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
906:
907: ### FIXME: is this really what we want?
908: # I dont' think so, to will corrupt any UTF-8 resources at least,
909: # and any encoding other than ISO-8859-1 will probably break
910: #Encode any High ASCII characters
911: #$outstring=&HTML::Entities::encode($outstring,"\200-\377");
912: # ------------------------------------------------------------- Write modified.
913:
914: {
915: my $org;
916: unless ($org=Apache::File->new('>'.$source)) {
917: print $logfile "No write permit to $source\n";
918: return ('<font color="red">'.&mt('No write permission to').
919: ' '.$source.
920: ', '.&mt('FAIL').'</font>',1);
921: }
922: print($org $outstring);
923: }
924: $content=$outstring;
925:
926: }
927: # -------------------------------------------- Initial step done, now metadata.
928:
929: # --------------------------------------- Storage for metadata keys and fields.
930:
931: %metadatafields=();
932: %metadatakeys=();
933:
934: my %oldparmstores=();
935:
936: unless ($batch) {
937: $scrout.='<h3>'.&mt('Metadata Information').' ' .
938: Apache::loncommon::help_open_topic("Metadata_Description")
939: . '</h3>';
940: }
941:
942: # ------------------------------------------------ First, check out environment
943: unless (-e $source.'.meta') {
944: $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
945: $ENV{'environment.middlename'}.' '.
946: $ENV{'environment.lastname'}.' '.
947: $ENV{'environment.generation'};
948: $metadatafields{'author'}=~s/\s+/ /g;
949: $metadatafields{'author'}=~s/\s+$//;
950: $metadatafields{'owner'}=$cuname.'@'.$cudom;
951: $metadatafields{'modifyinguser'}=$ENV{'user.name'}.'@'.
952: $ENV{'user.domain'};
953: $metadatafields{'authorspace'}=$cuname.'@'.$cudom;
954:
955: # ------------------------------------------------ Check out directory hierachy
956:
957: my $thisdisfn=$source;
958: $thisdisfn=~s/^\/home\/\Q$cuname\E\///;
959:
960: my @urlparts=split(/\//,$thisdisfn);
961: $#urlparts--;
962:
963: my $currentpath='/home/'.$cuname.'/';
964:
965: my $prefix='../'x($#urlparts);
966: foreach (@urlparts) {
967: $currentpath.=$_.'/';
968: $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
969: $prefix=~s|^\.\./||;
970: }
971:
972: # ------------------- Clear out parameters and stores (there should not be any)
973:
974: foreach (keys %metadatafields) {
975: if (($_=~/^parameter/) || ($_=~/^stores/)) {
976: delete $metadatafields{$_};
977: }
978: }
979:
980: } else {
981: # ---------------------- Read previous metafile, remember parameters and stores
982:
983: $scrout.=&metaread($logfile,$source.'.meta');
984:
985: foreach (keys %metadatafields) {
986: if (($_=~/^parameter/) || ($_=~/^stores/)) {
987: $oldparmstores{$_}=1;
988: delete $metadatafields{$_};
989: }
990: }
991:
992: }
993:
994: # -------------------------------------------------- Parse content for metadata
995: if (($style eq 'ssi') || ($style eq 'prv')) {
996: my $dir=$source;
997: $dir=~s-/[^/]*$--;
998: my $file=$source;
999: $file=(split('/',$file))[-1];
1000: $source=&Apache::lonnet::hreflocation($dir,$file);
1001: $allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
1002:
1003: &metaeval($allmeta);
1004: }
1005: # ---------------- Find and document discrepancies in the parameters and stores
1006:
1007: my $chparms='';
1008: foreach (sort keys %metadatafields) {
1009: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1010: unless ($_=~/\.\w+$/) {
1011: unless ($oldparmstores{$_}) {
1012: print $logfile 'New: '.$_."\n";
1013: $chparms.=$_.' ';
1014: }
1015: }
1016: }
1017: }
1018: if ($chparms) {
1019: $scrout.='<p><b>'.&mt('New parameters or stored values').
1020: ':</b> '.$chparms.'</p>';
1021: }
1022:
1023: $chparms='';
1024: foreach (sort keys %oldparmstores) {
1025: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1026: unless (($metadatafields{$_.'.name'}) ||
1027: ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
1028: print $logfile 'Obsolete: '.$_."\n";
1029: $chparms.=$_.' ';
1030: }
1031: }
1032: }
1033: if ($chparms) {
1034: $scrout.='<p><b>'.&mt('Obsolete parameters or stored values').':</b> '.
1035: $chparms.'</p>';
1036: }
1037:
1038: # ------------------------------------------------------- Now have all metadata
1039:
1040: my %keywords=();
1041:
1042: if (length($content)<500000) {
1043: my $textonly=$content;
1044: $textonly=~s/\<script[^\<]+\<\/script\>//g;
1045: $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
1046: $textonly=~s/\<[^\>]*\>//g;
1047: $textonly=~tr/A-Z/a-z/;
1048: $textonly=~s/[\$\&][a-z]\w*//g;
1049: $textonly=~s/[^a-z\s]//g;
1050:
1051: foreach ($textonly=~m/(\w+)/g) {
1052: unless ($nokey{$_}) {
1053: $keywords{$_}=1;
1054: }
1055: }
1056: }
1057:
1058:
1059: foreach (split(/\W+/,$metadatafields{'keywords'})) {
1060: $keywords{$_}=1;
1061: }
1062: # --------------------------------------------------- Now we also have keywords
1063: # =============================================================================
1064: # INTERACTIVE MODE
1065: #
1066: unless ($batch) {
1067: $scrout.=
1068: '<form name="pubform" action="/adm/publish" method="post">'.
1069: '<p><input type="submit" value="Finalize Publication" /></p>'.
1070: &hiddenfield('phase','two').
1071: &hiddenfield('filename',$ENV{'form.filename'}).
1072: &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
1073: &hiddenfield('dependencies',join(',',keys %allow)).
1074: &textfield('Title','title',$metadatafields{'title'}).
1075: &textfield('Author(s)','author',$metadatafields{'author'}).
1076: &textfield('Subject','subject',$metadatafields{'subject'});
1077:
1078: # --------------------------------------------------- Scan content for keywords
1079:
1080: my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
1081: my $keywordout=<<"END";
1082: <script>
1083: function checkAll(field) {
1084: for (i = 0; i < field.length; i++)
1085: field[i].checked = true ;
1086: }
1087:
1088: function uncheckAll(field) {
1089: for (i = 0; i < field.length; i++)
1090: field[i].checked = false ;
1091: }
1092: </script>
1093: <p><font color="#800000" face="helvetica"><b>KEYWORDS:</b></font>
1094: $keywords_help</b>
1095: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)" />
1096: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)" />
1097: </p>
1098: <br />
1099: END
1100: $keywordout.='<table border="2"><tr>';
1101: my $colcount=0;
1102:
1103: foreach (sort keys %keywords) {
1104: $keywordout.='<td><input type="checkbox" name="keywords" value="'.$_.'"';
1105: if ($metadatafields{'keywords'}) {
1106: if ($metadatafields{'keywords'}=~/\Q$_\E/) {
1107: $keywordout.=' checked="on"';
1108: }
1109: } elsif (&Apache::loncommon::keyword($_)) {
1110: $keywordout.=' checked="on"';
1111: }
1112: $keywordout.=' />'.$_.'</td>';
1113: if ($colcount>10) {
1114: $keywordout.="</tr><tr>\n";
1115: $colcount=0;
1116: }
1117: $colcount++;
1118: }
1119:
1120: $keywordout.='</tr></table>';
1121:
1122: $scrout.=$keywordout;
1123:
1124: $scrout.=&textfield('Additional Keywords','addkey','');
1125:
1126: $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
1127:
1128: $scrout.=
1129: "\n<p><font color=\"#800000\" face=\"helvetica\"><b>ABSTRACT:".
1130: "</b></font></p><br />".
1131: '<textarea cols="80" rows="5" name="abstract">'.
1132: $metadatafields{'abstract'}.'</textarea></p>';
1133:
1134: $source=~/\.(\w+)$/;
1135:
1136: $scrout.=&hiddenfield('mime',$1);
1137:
1138: my $defaultlanguage=$metadatafields{'language'};
1139: $defaultlanguage =~ s/\s*notset\s*//g;
1140: $defaultlanguage =~ s/^,\s*//g;
1141: $defaultlanguage =~ s/,\s*$//g;
1142:
1143: $scrout.=&selectbox('Language','language',
1144: $defaultlanguage,
1145: \&Apache::loncommon::languagedescription,
1146: (&Apache::loncommon::languageids),
1147: );
1148:
1149: unless ($metadatafields{'creationdate'}) {
1150: $metadatafields{'creationdate'}=time;
1151: }
1152: $scrout.=&hiddenfield('creationdate',
1153: &Apache::loncommon::unsqltime($metadatafields{'creationdate'}));
1154:
1155: $scrout.=&hiddenfield('lastrevisiondate',time);
1156:
1157:
1158: $scrout.=&textfield('Publisher/Owner','owner',
1159: $metadatafields{'owner'});
1160:
1161: # -------------------------------------------------- Correct copyright for rat.
1162: my $defaultoption=$metadatafields{'copyright'};
1163: unless ($defaultoption) { $defaultoption='default'; }
1164: unless ($style eq 'prv') {
1165: if ($style eq 'rat') {
1166: if ($metadatafields{'copyright'} eq 'public') {
1167: delete $metadatafields{'copyright'};
1168: $defaultoption='default';
1169: }
1170: $scrout.=&selectbox('Copyright/Distribution','copyright',
1171: $defaultoption,
1172: \&Apache::loncommon::copyrightdescription,
1173: (grep !/^public$/,(&Apache::loncommon::copyrightids)));
1174: } else {
1175: $scrout.=&selectbox('Copyright/Distribution','copyright',
1176: $defaultoption,
1177: \&Apache::loncommon::copyrightdescription,
1178: (&Apache::loncommon::copyrightids));
1179: }
1180:
1181: my $copyright_help =
1182: Apache::loncommon::help_open_topic('Publishing_Copyright');
1183: $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
1184: $scrout.=&textfield('Custom Distribution File','customdistributionfile',
1185: $metadatafields{'customdistributionfile'}).
1186: $copyright_help;
1187: my $uctitle=uc(&mt('Obsolete'));
1188: $scrout.=
1189: "\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
1190: '</b></font> <input type="checkbox" name="obsolete" ';
1191: if ($metadatafields{'obsolete'}) {
1192: $scrout.=' checked="1" ';
1193: }
1194: $scrout.='/ ></p>'.
1195: &textfield('Suggested Replacement for Obsolete File',
1196: 'obsoletereplacement',
1197: $metadatafields{'obsoletereplacement'});
1198: } else {
1199: $scrout.=&hiddenfield('copyright','private');
1200: }
1201: return ($scrout.'<p><input type="submit" value="'.
1202: &mt('Finalize Publication').'" /></p></form>',0);
1203: # =============================================================================
1204: # BATCH MODE
1205: #
1206: } else {
1207: # Transfer metadata directly to environment for stage 2
1208: foreach (keys %metadatafields) {
1209: $ENV{'form.'.$_}=$metadatafields{$_};
1210: }
1211: $ENV{'form.addkey'}='';
1212: $ENV{'form.keywords'}='';
1213: foreach (keys %keywords) {
1214: if ($metadatafields{'keywords'}) {
1215: if ($metadatafields{'keywords'}=~/\Q$_\E/) {
1216: $ENV{'form.keywords'}.=$_.',';
1217: }
1218: } elsif (&Apache::loncommon::keyword($_)) {
1219: $ENV{'form.keywords'}.=$_.',';
1220: }
1221: }
1222: $ENV{'form.keywords'}=~s/\,$//;
1223: unless ($ENV{'form.creationdate'}) { $ENV{'form.creationdate'}=time; }
1224: $ENV{'form.lastrevisiondate'}=time;
1225: if ((($style eq 'rat') && ($ENV{'form.copyright'} eq 'public')) ||
1226: (!$ENV{'form.copyright'})) {
1227: $ENV{'form.copyright'}='default';
1228: }
1229: $ENV{'form.allmeta'}=&Apache::lonnet::escape($allmeta);
1230: return ($scrout,0);
1231: }
1232: }
1233:
1234: #########################################
1235: #########################################
1236:
1237: =pod
1238:
1239: =item B<phasetwo>
1240:
1241: Render second interface showing status of publication steps.
1242: This is publication step two.
1243:
1244: Parameters:
1245:
1246: =over 4
1247:
1248: =item I<$source>
1249:
1250: =item I<$target>
1251:
1252: =item I<$style>
1253:
1254: =item I<$distarget>
1255:
1256: =back
1257:
1258: Returns:
1259:
1260: =over 4
1261:
1262: =item Scalar string
1263:
1264: String contains status (errors and warnings) and information associated with
1265: the server's attempts at publication.
1266:
1267: =cut
1268:
1269: #'stupid emacs
1270: #########################################
1271: #########################################
1272: sub phasetwo {
1273:
1274: my ($r,$source,$target,$style,$distarget,$batch)=@_;
1275: $source=~s/\/+/\//g;
1276: $target=~s/\/+/\//g;
1277:
1278: if ($target=~/\_\_\_/) {
1279: $r->print(
1280: '<font color="red">'.&mt('Unsupported character combination').
1281: ' "<tt>___</tt>" '.&mt('in filename, FAIL').'</font>');
1282: return 0;
1283: }
1284: $distarget=~s/\/+/\//g;
1285: my $logfile;
1286: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1287: $r->print(
1288: '<font color="red">'.
1289: &mt('No write permission to user directory, FAIL').'</font>');
1290: return 0;
1291: }
1292: print $logfile
1293: "\n================= Publish ".localtime()." Phase Two ================\n".$ENV{'user.name'}.'@'.$ENV{'user.domain'}."\n";
1294:
1295: %metadatafields=();
1296: %metadatakeys=();
1297:
1298: &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
1299:
1300: $metadatafields{'title'}=$ENV{'form.title'};
1301: $metadatafields{'author'}=$ENV{'form.author'};
1302: $metadatafields{'subject'}=$ENV{'form.subject'};
1303: $metadatafields{'notes'}=$ENV{'form.notes'};
1304: $metadatafields{'abstract'}=$ENV{'form.abstract'};
1305: $metadatafields{'mime'}=$ENV{'form.mime'};
1306: $metadatafields{'language'}=$ENV{'form.language'};
1307: $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
1308: $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
1309: $metadatafields{'owner'}=$ENV{'form.owner'};
1310: $metadatafields{'copyright'}=$ENV{'form.copyright'};
1311: $metadatafields{'customdistributionfile'}=
1312: $ENV{'form.customdistributionfile'};
1313: $metadatafields{'obsolete'}=$ENV{'form.obsolete'};
1314: $metadatafields{'obsoletereplacement'}=
1315: $ENV{'form.obsoletereplacement'};
1316: $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
1317:
1318: my $allkeywords=$ENV{'form.addkey'};
1319: if (exists($ENV{'form.keywords'})) {
1320: if (ref($ENV{'form.keywords'})) {
1321: $allkeywords .= ','.join(',',@{$ENV{'form.keywords'}});
1322: } else {
1323: $allkeywords .= ','.$ENV{'form.keywords'};
1324: }
1325: }
1326: $allkeywords=~s/\W+/\,/;
1327: $allkeywords=~s/^\,//;
1328: $metadatafields{'keywords'}=$allkeywords;
1329:
1330: {
1331: print $logfile "\nWrite metadata file for ".$source;
1332: my $mfh;
1333: unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
1334: return
1335: '<font color="red">'.&mt('Could not write metadata, FAIL').
1336: '</font>';
1337: }
1338: foreach (sort keys %metadatafields) {
1339: unless ($_=~/\./) {
1340: my $unikey=$_;
1341: $unikey=~/^([A-Za-z]+)/;
1342: my $tag=$1;
1343: $tag=~tr/A-Z/a-z/;
1344: print $mfh "\n\<$tag";
1345: foreach (split(/\,/,$metadatakeys{$unikey})) {
1346: my $value=$metadatafields{$unikey.'.'.$_};
1347: $value=~s/\"/\'\'/g;
1348: print $mfh ' '.$_.'="'.$value.'"';
1349: }
1350: print $mfh '>'.
1351: &HTML::Entities::encode($metadatafields{$unikey})
1352: .'</'.$tag.'>';
1353: }
1354: }
1355: $r->print('<p>'.&mt('Wrote Metadata').'</p>');
1356: print $logfile "\nWrote metadata";
1357: }
1358:
1359: # -------------------------------- Synchronize entry with SQL metadata database
1360:
1361: $metadatafields{'url'} = $distarget;
1362: $metadatafields{'version'} = 'current';
1363: unless ($metadatafields{'copyright'} eq 'priv') {
1364: my ($error,$success) = &store_metadata(\%metadatafields);
1365: if ($success) {
1366: $r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
1367: print $logfile "\nSynchronized SQL metadata database";
1368: } else {
1369: $r->print($error);
1370: print $logfile "\n".$error;
1371: }
1372: } else {
1373: $r->print('<p>'.
1374: &mt('Private Publication - did not synchronize database').'</p>');
1375: print $logfile "\nPrivate: Did not synchronize data into ".
1376: "SQL metadata database";
1377: }
1378: # ----------------------------------------------------------- Copy old versions
1379:
1380: if (-e $target) {
1381: my $filename;
1382: my $maxversion=0;
1383: $target=~/(.*)\/([^\/]+)\.(\w+)$/;
1384: my $srcf=$2;
1385: my $srct=$3;
1386: my $srcd=$1;
1387: unless ($srcd=~/^\/home\/httpd\/html\/res/) {
1388: print $logfile "\nPANIC: Target dir is ".$srcd;
1389: return "<font color=\"red\">Invalid target directory, FAIL</font>";
1390: }
1391: opendir(DIR,$srcd);
1392: while ($filename=readdir(DIR)) {
1393: if (-l $srcd.'/'.$filename) {
1394: unlink($srcd.'/'.$filename);
1395: unlink($srcd.'/'.$filename.'.meta');
1396: } else {
1397: if ($filename=~/\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
1398: $maxversion=($1>$maxversion)?$1:$maxversion;
1399: }
1400: }
1401: }
1402: closedir(DIR);
1403: $maxversion++;
1404: $r->print('<p>Creating old version '.$maxversion.'</p>');
1405: print $logfile "\nCreating old version ".$maxversion."\n";
1406:
1407: my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
1408:
1409: if (copy($target,$copyfile)) {
1410: print $logfile "Copied old target to ".$copyfile."\n";
1411: $r->print('<p>'.&mt('Copied old target file').'</p>');
1412: } else {
1413: print $logfile "Unable to write ".$copyfile.':'.$!."\n";
1414: return "<font color=\"red\">".&mt('Failed to copy old target').
1415: ", $!, ".&mt('FAIL')."</font>";
1416: }
1417:
1418: # --------------------------------------------------------------- Copy Metadata
1419:
1420: $copyfile=$copyfile.'.meta';
1421:
1422: if (copy($target.'.meta',$copyfile)) {
1423: print $logfile "Copied old target metadata to ".$copyfile."\n";
1424: $r->print('<p>'.&mt('Copied old metadata').'</p>')
1425: } else {
1426: print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1427: if (-e $target.'.meta') {
1428: return
1429: "<font color=\"red\">".
1430: &mt('Failed to write old metadata copy').", $!, ".&mt('FAIL')."</font>";
1431: }
1432: }
1433:
1434:
1435: } else {
1436: $r->print('<p>'.&mt('Initial version').'</p>');
1437: print $logfile "\nInitial version";
1438: }
1439:
1440: # ---------------------------------------------------------------- Write Source
1441: my $copyfile=$target;
1442:
1443: my @parts=split(/\//,$copyfile);
1444: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1445:
1446: my $count;
1447: for ($count=5;$count<$#parts;$count++) {
1448: $path.="/$parts[$count]";
1449: if ((-e $path)!=1) {
1450: print $logfile "\nCreating directory ".$path;
1451: $r->print('<p>'.&mt('Created directory').' '.$parts[$count].'</p>');
1452: mkdir($path,0777);
1453: }
1454: }
1455:
1456: if (copy($source,$copyfile)) {
1457: print $logfile "\nCopied original source to ".$copyfile."\n";
1458: $r->print('<p>'.&mt('Copied source file').'</p>');
1459: } else {
1460: print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
1461: return "<font color=\"red\">".
1462: &mt('Failed to copy source').", $!, ".&mt('FAIL')."</font>";
1463: }
1464:
1465: # --------------------------------------------------------------- Copy Metadata
1466:
1467: $copyfile=$copyfile.'.meta';
1468:
1469: if (copy($source.'.meta',$copyfile)) {
1470: print $logfile "\nCopied original metadata to ".$copyfile."\n";
1471: $r->print('<p>'.&mt('Copied metadata').'</p>');
1472: } else {
1473: print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
1474: return
1475: "<font color=\"red\">".&mt('Failed to write metadata copy').", $!, ".&mt('FAIL')."</font>";
1476: }
1477: $r->rflush;
1478: # --------------------------------------------------- Send update notifications
1479:
1480: my @subscribed=&get_subscribed_hosts($target);
1481: foreach my $subhost (@subscribed) {
1482: $r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
1483: print $logfile "\nNotifying host ".$subhost.':';
1484: my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
1485: $r->print($reply.'</p><br />');$r->rflush;
1486: print $logfile $reply;
1487: }
1488:
1489: # ---------------------------------------- Send update notifications, meta only
1490:
1491: my @subscribedmeta=&get_subscribed_hosts("$target.meta");
1492: foreach my $subhost (@subscribedmeta) {
1493: $r->print('<p>'.
1494: &mt('Notifying host for metadata only').' '.$subhost.':');$r->rflush;
1495: print $logfile "\nNotifying host for metadata only ".$subhost.':';
1496: my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
1497: $subhost);
1498: $r->print($reply.'</p><br />');$r->rflush;
1499: print $logfile $reply;
1500: }
1501:
1502: # --------------------------------------------------- Notify subscribed courses
1503: my %courses=&coursedependencies($target);
1504: my $now=time;
1505: foreach (keys %courses) {
1506: $r->print('<p>'.&mt('Notifying course').' '.$_.':');$r->rflush;
1507: print $logfile "\nNotifying host ".$_.':';
1508: my ($cdom,$cname)=split(/\_/,$_);
1509: my $reply=&Apache::lonnet::cput
1510: ('versionupdate',{$target => $now},$cdom,$cname);
1511: $r->print($reply.'</p><br />');$r->rflush;
1512: print $logfile $reply;
1513: }
1514: # ------------------------------------------------ Provide link to new resource
1515: unless ($batch) {
1516: my $thisdistarget=$target;
1517: $thisdistarget=~s/^\Q$docroot\E//;
1518:
1519: my $thissrc=$source;
1520: $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
1521:
1522: my $thissrcdir=$thissrc;
1523: $thissrcdir=~s/\/[^\/]+$/\//;
1524:
1525:
1526: $r->print(
1527: '<hr /><a href="'.$thisdistarget.'"><font size="+2">'.
1528: &mt('View Published Version').'</font></a>'.
1529: '<p><a href="'.$thissrc.'"><font size=+2>'.
1530: &mt('Back to Source').'</font></a></p>'.
1531: '<p><a href="'.$thissrcdir.
1532: '"><font size="+2">'.
1533: &mt('Back to Source Directory').'</font></a></p>');
1534: }
1535: }
1536:
1537: #########################################
1538:
1539: sub batchpublish {
1540: my ($r,$srcfile,$targetfile)=@_;
1541: #publication pollutes %ENV with form.* values
1542: my %oldENV=%ENV;
1543: $srcfile=~s/\/+/\//g;
1544: $targetfile=~s/\/+/\//g;
1545: my $thisdisfn=$srcfile;
1546: $thisdisfn=~s/\/home\/korte\/public_html\///;
1547: $srcfile=~s/\/+/\//g;
1548:
1549: my $docroot=$r->dir_config('lonDocRoot');
1550: my $thisdistarget=$targetfile;
1551: $thisdistarget=~s/^\Q$docroot\E//;
1552:
1553:
1554: %metadatafields=();
1555: %metadatakeys=();
1556: $srcfile=~/\.(\w+)$/;
1557: my $thistype=$1;
1558:
1559:
1560: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1561:
1562: $r->print('<h2>'.&mt('Publishing').' <tt>'.$thisdisfn.'</tt></h2>');
1563:
1564: # phase one takes
1565: # my ($source,$target,$style,$batch)=@_;
1566: my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
1567: $r->print('<p>'.$outstring.'</p>');
1568: # phase two takes
1569: # my ($source,$target,$style,$distarget,batch)=@_;
1570: # $ENV{'form.allmeta'},$ENV{'form.title'},$ENV{'form.author'},...
1571: if (!$error) {
1572: $r->print('<p>');
1573: &phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
1574: $r->print('</p>');
1575: }
1576: %ENV=%oldENV;
1577: return '';
1578: }
1579:
1580: #########################################
1581:
1582: sub publishdirectory {
1583: my ($r,$fn,$thisdisfn)=@_;
1584: $fn=~s/\/+/\//g;
1585: $thisdisfn=~s/\/+/\//g;
1586: my $resdir=
1587: $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cudom.'/'.$cuname.'/'.
1588: $thisdisfn;
1589: $r->print('<h1>Directory <tt>'.$thisdisfn.'</tt></h1>'.
1590: 'Target: <tt>'.$resdir.'</tt><br />');
1591:
1592: my $dirptr=16384; # Mask indicating a directory in stat.cmode.
1593:
1594: opendir(DIR,$fn);
1595: my @files=sort(readdir(DIR));
1596: foreach my $filename (@files) {
1597: my ($cdev,$cino,$cmode,$cnlink,
1598: $cuid,$cgid,$crdev,$csize,
1599: $catime,$cmtime,$cctime,
1600: $cblksize,$cblocks)=stat($fn.'/'.$filename);
1601:
1602: my $extension='';
1603: if ($filename=~/\.(\w+)$/) { $extension=$1; }
1604: if ($cmode&$dirptr) {
1605: if (($filename!~/^\./) && ($ENV{'form.pubrec'})) {
1606: &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
1607: }
1608: } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
1609: ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
1610: # find out publication status and/or exiting metadata
1611: my $publishthis=0;
1612: if (-e $resdir.'/'.$filename) {
1613: my ($rdev,$rino,$rmode,$rnlink,
1614: $ruid,$rgid,$rrdev,$rsize,
1615: $ratime,$rmtime,$rctime,
1616: $rblksize,$rblocks)=stat($resdir.'/'.$filename);
1617: if (($rmtime<$cmtime) || ($ENV{'form.forcerepub'})) {
1618: # previously published, modified now
1619: $publishthis=1;
1620: }
1621: } else {
1622: # never published
1623: $publishthis=1;
1624: }
1625: if ($publishthis) {
1626: &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
1627: } else {
1628: $r->print('<br />Skipping '.$filename.'<br />');
1629: }
1630: $r->rflush();
1631: }
1632: }
1633: closedir(DIR);
1634: }
1635: #########################################
1636:
1637: =pod
1638:
1639: =item B<handler>
1640:
1641: A basic outline of the handler subroutine follows.
1642:
1643: =over 4
1644:
1645: =item *
1646:
1647: Get query string for limited number of parameters.
1648:
1649: =item *
1650:
1651: Check filename.
1652:
1653: =item *
1654:
1655: File is there and owned, init lookup tables.
1656:
1657: =item *
1658:
1659: Start page output.
1660:
1661: =item *
1662:
1663: Evaluate individual file, and then output information.
1664:
1665: =item *
1666:
1667: Publishing from $thisfn to $thistarget with $thisembstyle.
1668:
1669: =back
1670:
1671: =cut
1672:
1673: #########################################
1674: #########################################
1675: sub handler {
1676: my $r=shift;
1677:
1678: if ($r->header_only) {
1679: &Apache::loncommon::content_type($r,'text/html');
1680: $r->send_http_header;
1681: return OK;
1682: }
1683:
1684: # Get query string for limited number of parameters
1685:
1686: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1687: ['filename']);
1688:
1689: # -------------------------------------------------------------- Check filename
1690:
1691: my $fn=&Apache::lonnet::unescape($ENV{'form.filename'});
1692:
1693:
1694: unless ($fn) {
1695: $r->log_reason($cuname.' at '.$cudom.
1696: ' trying to publish empty filename', $r->filename);
1697: return HTTP_NOT_FOUND;
1698: }
1699:
1700: ($cuname,$cudom)=
1701: &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
1702: unless (($cuname) && ($cudom)) {
1703: $r->log_reason($cuname.' at '.$cudom.
1704: ' trying to publish file '.$ENV{'form.filename'}.
1705: ' ('.$fn.') - not authorized',
1706: $r->filename);
1707: return HTTP_NOT_ACCEPTABLE;
1708: }
1709:
1710: unless (&Apache::lonnet::homeserver($cuname,$cudom)
1711: eq $r->dir_config('lonHostID')) {
1712: $r->log_reason($cuname.' at '.$cudom.
1713: ' trying to publish file '.$ENV{'form.filename'}.
1714: ' ('.$fn.') - not homeserver ('.
1715: &Apache::lonnet::homeserver($cuname,$cudom).')',
1716: $r->filename);
1717: return HTTP_NOT_ACCEPTABLE;
1718: }
1719:
1720: $fn=~s/^http\:\/\/[^\/]+//;
1721: $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
1722:
1723: my $targetdir='';
1724: $docroot=$r->dir_config('lonDocRoot');
1725: if ($1 ne $cuname) {
1726: $r->log_reason($cuname.' at '.$cudom.
1727: ' trying to publish unowned file '.
1728: $ENV{'form.filename'}.' ('.$fn.')',
1729: $r->filename);
1730: return HTTP_NOT_ACCEPTABLE;
1731: } else {
1732: $targetdir=$docroot.'/res/'.$cudom;
1733: }
1734:
1735:
1736: unless (-e $fn) {
1737: $r->log_reason($cuname.' at '.$cudom.
1738: ' trying to publish non-existing file '.
1739: $ENV{'form.filename'}.' ('.$fn.')',
1740: $r->filename);
1741: return HTTP_NOT_FOUND;
1742: }
1743:
1744: unless ($ENV{'form.phase'} eq 'two') {
1745:
1746: # -------------------------------- File is there and owned, init lookup tables.
1747:
1748: %addid=();
1749:
1750: {
1751: my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
1752: while (<$fh>=~/(\w+)\s+(\w+)/) {
1753: $addid{$1}=$2;
1754: }
1755: }
1756:
1757: %nokey=();
1758:
1759: {
1760: my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
1761: while (<$fh>) {
1762: my $word=$_;
1763: chomp($word);
1764: $nokey{$word}=1;
1765: }
1766: }
1767:
1768: }
1769:
1770: # ---------------------------------------------------------- Start page output.
1771:
1772: &Apache::loncommon::content_type($r,'text/html');
1773: $r->send_http_header;
1774:
1775: $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
1776: $r->print(&Apache::loncommon::bodytag('Resource Publication'));
1777:
1778:
1779: my $thisfn=$fn;
1780:
1781: my $thistarget=$thisfn;
1782:
1783: $thistarget=~s/^\/home/$targetdir/;
1784: $thistarget=~s/\/public\_html//;
1785:
1786: my $thisdistarget=$thistarget;
1787: $thisdistarget=~s/^\Q$docroot\E//;
1788:
1789: my $thisdisfn=$thisfn;
1790: $thisdisfn=~s/^\/home\/\Q$cuname\E\/public_html\///;
1791:
1792: if ($fn=~/\/$/) {
1793: # -------------------------------------------------------- This is a directory
1794: &publishdirectory($r,$fn,$thisdisfn);
1795: $r->print('<hr><font size="+2">'.&mt('Done').'</font><br><a href="/priv/'
1796: .$cuname.'/'.$thisdisfn
1797: .'">'.&mt('Return to Directory').'</a>');
1798:
1799:
1800: } else {
1801: # ---------------------- Evaluate individual file, and then output information.
1802: $thisfn=~/\.(\w+)$/;
1803: my $thistype=$1;
1804: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1805: $r->print('<h2>'.&mt('Publishing').' '.
1806: &Apache::loncommon::filedescription($thistype).' <tt>');
1807:
1808: $r->print(<<ENDCAPTION);
1809: <a href='javascript:void(window.open("/~$cuname/$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
1810: $thisdisfn</a>
1811: ENDCAPTION
1812: $r->print('</tt></h2><b>'.&mt('Target').':</b> <tt>'.
1813: $thisdistarget.'</tt><br />');
1814:
1815: if (($cuname ne $ENV{'user.name'})||($cudom ne $ENV{'user.domain'})) {
1816: $r->print('<h3><font color="red">'.&mt('Co-Author').': '.
1817: $cuname.&mt(' at ').$cudom.'</font></h3>');
1818: }
1819:
1820: if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
1821: $r->print(<<ENDDIFF);
1822: <br />
1823: <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"))'>
1824: ENDDIFF
1825: $r->print(&mt('Diffs with Current Version').'</a><br />');
1826: }
1827:
1828: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
1829:
1830: unless ($ENV{'form.phase'} eq 'two') {
1831: my ($outstring,$error)=&publish($thisfn,$thistarget,$thisembstyle);
1832: $r->print('<hr />'.$outstring);
1833: } else {
1834: $r->print('<hr />');
1835: &phasetwo($r,$thisfn,$thistarget,$thisembstyle,$thisdistarget);
1836: }
1837: }
1838: $r->print('</body></html>');
1839:
1840: return OK;
1841: }
1842:
1843: 1;
1844: __END__
1845:
1846: =pod
1847:
1848: =back
1849:
1850: =back
1851:
1852: =cut
1853:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>