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