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