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