1: # The LearningOnline Network with CAPA
2: # Publication Handler
3: #
4: # $Id: lonpublisher.pm,v 1.142 2003/11/01 17:38:58 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: if (($style eq 'ssi') || ($style eq 'prv')) {
820: my $dir=$source;
821: $dir=~s-/[^/]*$--;
822: my $file=$source;
823: $file=(split('/',$file))[-1];
824: $source=&Apache::lonnet::hreflocation($dir,$file);
825: my $allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
826: &metaeval($allmeta);
827: }
828: }
829:
830: #########################################
831: #########################################
832:
833: =pod
834:
835: =item B<publish>
836:
837: This is the workhorse function of this module. This subroutine generates
838: backup copies, performs any automatic processing (prior to publication,
839: especially for rat and ssi files),
840:
841: Returns a 2 element array, the first is the string to be shown to the
842: user, the second is an error code, either 1 (an error occured) or 0
843: (no error occurred)
844:
845: I<Additional documentation needed.>
846:
847: =cut
848:
849: #########################################
850: #########################################
851: sub publish {
852:
853: my ($source,$target,$style,$batch)=@_;
854: my $logfile;
855: my $scrout='';
856: my $allmeta='';
857: my $content='';
858: my %allow=();
859:
860: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
861: return ('<font color="red">No write permission to user directory, FAIL</font>',1);
862: }
863: print $logfile
864: "\n\n================= Publish ".localtime()." Phase One ================\n".$ENV{'user.name'}.'@'.$ENV{'user.domain'}."\n";
865:
866: if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
867: # ------------------------------------------------------- This needs processing
868:
869: # ----------------------------------------------------------------- Backup Copy
870: my $copyfile=$source.'.save';
871: if (copy($source,$copyfile)) {
872: print $logfile "Copied original file to ".$copyfile."\n";
873: } else {
874: print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
875: return ("<font color=\"red\">Failed to write backup copy, $!,FAIL</font>",1);
876: }
877: # ------------------------------------------------------------- IDs and indices
878:
879: my ($outstring,$error);
880: ($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
881: $target);
882: if ($error) { return ($outstring,$error); }
883: # ------------------------------------------------------------ Construct Allows
884:
885: $scrout.='<h3>Dependencies</h3>';
886: my $allowstr='';
887: foreach (sort(keys(%allow))) {
888: my $thisdep=$_;
889: if ($thisdep !~ /[^\s]/) { next; }
890: unless ($style eq 'rat') {
891: $allowstr.="\n".'<allow src="'.$thisdep.'" />';
892: }
893: $scrout.='<br />';
894: unless ($thisdep=~/\*/) {
895: $scrout.='<a href="'.$thisdep.'">';
896: }
897: $scrout.='<tt>'.$thisdep.'</tt>';
898: unless ($thisdep=~/\*/) {
899: $scrout.='</a>';
900: if (
901: &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
902: $thisdep.'.meta') eq '-1') {
903: $scrout.= ' - <font color="red">Currently not available'.
904: '</font>';
905: } else {
906: my %temphash=(&Apache::lonnet::declutter($target).'___'.
907: &Apache::lonnet::declutter($thisdep).'___usage'
908: => time);
909: $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
910: if ((defined($1)) && (defined($2))) {
911: &Apache::lonnet::put('nohist_resevaldata',\%temphash,
912: $1,$2);
913: }
914: }
915: }
916: }
917: $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
918:
919: ### FIXME: is this really what we want?
920: # I dont' think so, to will corrupt any UTF-8 resources at least,
921: # and any encoding other than ISO-8859-1 will probably break
922: #Encode any High ASCII characters
923: #$outstring=&HTML::Entities::encode($outstring,"\200-\377");
924: # ------------------------------------------------------------- Write modified.
925:
926: {
927: my $org;
928: unless ($org=Apache::File->new('>'.$source)) {
929: print $logfile "No write permit to $source\n";
930: return ('<font color="red">'.&mt('No write permission to').
931: ' '.$source.
932: ', '.&mt('FAIL').'</font>',1);
933: }
934: print($org $outstring);
935: }
936: $content=$outstring;
937:
938: }
939: # -------------------------------------------- Initial step done, now metadata.
940:
941: # --------------------------------------- Storage for metadata keys and fields.
942:
943: %metadatafields=();
944: %metadatakeys=();
945:
946: my %oldparmstores=();
947:
948: unless ($batch) {
949: $scrout.='<h3>'.&mt('Metadata Information').' ' .
950: Apache::loncommon::help_open_topic("Metadata_Description")
951: . '</h3>';
952: }
953:
954: # ------------------------------------------------ First, check out environment
955: unless (-e $source.'.meta') {
956: $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
957: $ENV{'environment.middlename'}.' '.
958: $ENV{'environment.lastname'}.' '.
959: $ENV{'environment.generation'};
960: $metadatafields{'author'}=~s/\s+/ /g;
961: $metadatafields{'author'}=~s/\s+$//;
962: $metadatafields{'owner'}=$cuname.'@'.$cudom;
963: $metadatafields{'modifyinguser'}=$ENV{'user.name'}.'@'.
964: $ENV{'user.domain'};
965: $metadatafields{'authorspace'}=$cuname.'@'.$cudom;
966:
967: # ----------------------------------------------------------- Parse file itself
968:
969: &parseformeta($source,$style);
970: # ------------------------------------------------ Check out directory hierachy
971:
972: my $thisdisfn=$source;
973: $thisdisfn=~s/^\/home\/\Q$cuname\E\///;
974:
975: my @urlparts=split(/\//,$thisdisfn);
976: $#urlparts--;
977:
978: my $currentpath='/home/'.$cuname.'/';
979:
980: my $prefix='../'x($#urlparts);
981: foreach (@urlparts) {
982: $currentpath.=$_.'/';
983: $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
984: $prefix=~s|^\.\./||;
985: }
986:
987: # ------------------- Clear out parameters and stores (there should not be any)
988:
989: foreach (keys %metadatafields) {
990: if (($_=~/^parameter/) || ($_=~/^stores/)) {
991: delete $metadatafields{$_};
992: }
993: }
994:
995: } else {
996: # ---------------------- Read previous metafile, remember parameters and stores
997:
998: $scrout.=&metaread($logfile,$source.'.meta');
999:
1000: foreach (keys %metadatafields) {
1001: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1002: $oldparmstores{$_}=1;
1003: delete $metadatafields{$_};
1004: }
1005: }
1006:
1007: }
1008: # ------------------------------------------ See if anything new in file itself
1009:
1010: &parseformeta($source,$style);
1011:
1012: # ---------------- Find and document discrepancies in the parameters and stores
1013:
1014: my $chparms='';
1015: foreach (sort keys %metadatafields) {
1016: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1017: unless ($_=~/\.\w+$/) {
1018: unless ($oldparmstores{$_}) {
1019: print $logfile 'New: '.$_."\n";
1020: $chparms.=$_.' ';
1021: }
1022: }
1023: }
1024: }
1025: if ($chparms) {
1026: $scrout.='<p><b>'.&mt('New parameters or stored values').
1027: ':</b> '.$chparms.'</p>';
1028: }
1029:
1030: $chparms='';
1031: foreach (sort keys %oldparmstores) {
1032: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1033: unless (($metadatafields{$_.'.name'}) ||
1034: ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
1035: print $logfile 'Obsolete: '.$_."\n";
1036: $chparms.=$_.' ';
1037: }
1038: }
1039: }
1040: if ($chparms) {
1041: $scrout.='<p><b>'.&mt('Obsolete parameters or stored values').':</b> '.
1042: $chparms.'</p>';
1043: }
1044:
1045: # ------------------------------------------------------- Now have all metadata
1046:
1047: my %keywords=();
1048:
1049: if (length($content)<500000) {
1050: my $textonly=$content;
1051: $textonly=~s/\<script[^\<]+\<\/script\>//g;
1052: $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
1053: $textonly=~s/\<[^\>]*\>//g;
1054: $textonly=~tr/A-Z/a-z/;
1055: $textonly=~s/[\$\&][a-z]\w*//g;
1056: $textonly=~s/[^a-z\s]//g;
1057:
1058: foreach ($textonly=~m/(\w+)/g) {
1059: unless ($nokey{$_}) {
1060: $keywords{$_}=1;
1061: }
1062: }
1063: }
1064:
1065:
1066: foreach (split(/\W+/,$metadatafields{'keywords'})) {
1067: $keywords{$_}=1;
1068: }
1069: # --------------------------------------------------- Now we also have keywords
1070: # =============================================================================
1071: # INTERACTIVE MODE
1072: #
1073: unless ($batch) {
1074: $scrout.=
1075: '<form name="pubform" action="/adm/publish" method="post">'.
1076: '<p><input type="submit" value="Finalize Publication" /></p>'.
1077: &hiddenfield('phase','two').
1078: &hiddenfield('filename',$ENV{'form.filename'}).
1079: &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
1080: &hiddenfield('dependencies',join(',',keys %allow)).
1081: &textfield('Title','title',$metadatafields{'title'}).
1082: &textfield('Author(s)','author',$metadatafields{'author'}).
1083: &textfield('Subject','subject',$metadatafields{'subject'});
1084:
1085: # --------------------------------------------------- Scan content for keywords
1086:
1087: my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
1088: my $keywordout=<<"END";
1089: <script>
1090: function checkAll(field) {
1091: for (i = 0; i < field.length; i++)
1092: field[i].checked = true ;
1093: }
1094:
1095: function uncheckAll(field) {
1096: for (i = 0; i < field.length; i++)
1097: field[i].checked = false ;
1098: }
1099: </script>
1100: <p><font color="#800000" face="helvetica"><b>KEYWORDS:</b></font>
1101: $keywords_help</b>
1102: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)" />
1103: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)" />
1104: </p>
1105: <br />
1106: END
1107: $keywordout.='<table border="2"><tr>';
1108: my $colcount=0;
1109:
1110: foreach (sort keys %keywords) {
1111: $keywordout.='<td><input type="checkbox" name="keywords" value="'.$_.'"';
1112: if ($metadatafields{'keywords'}) {
1113: if ($metadatafields{'keywords'}=~/\Q$_\E/) {
1114: $keywordout.=' checked="on"';
1115: }
1116: } elsif (&Apache::loncommon::keyword($_)) {
1117: $keywordout.=' checked="on"';
1118: }
1119: $keywordout.=' />'.$_.'</td>';
1120: if ($colcount>10) {
1121: $keywordout.="</tr><tr>\n";
1122: $colcount=0;
1123: }
1124: $colcount++;
1125: }
1126:
1127: $keywordout.='</tr></table>';
1128:
1129: $scrout.=$keywordout;
1130:
1131: $scrout.=&textfield('Additional Keywords','addkey','');
1132:
1133: $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
1134:
1135: $scrout.=
1136: "\n<p><font color=\"#800000\" face=\"helvetica\"><b>ABSTRACT:".
1137: "</b></font></p><br />".
1138: '<textarea cols="80" rows="5" name="abstract">'.
1139: $metadatafields{'abstract'}.'</textarea></p>';
1140:
1141: $source=~/\.(\w+)$/;
1142:
1143: $scrout.=&hiddenfield('mime',$1);
1144:
1145: my $defaultlanguage=$metadatafields{'language'};
1146: $defaultlanguage =~ s/\s*notset\s*//g;
1147: $defaultlanguage =~ s/^,\s*//g;
1148: $defaultlanguage =~ s/,\s*$//g;
1149:
1150: $scrout.=&selectbox('Language','language',
1151: $defaultlanguage,
1152: \&Apache::loncommon::languagedescription,
1153: (&Apache::loncommon::languageids),
1154: );
1155:
1156: unless ($metadatafields{'creationdate'}) {
1157: $metadatafields{'creationdate'}=time;
1158: }
1159: $scrout.=&hiddenfield('creationdate',
1160: &Apache::loncommon::unsqltime($metadatafields{'creationdate'}));
1161:
1162: $scrout.=&hiddenfield('lastrevisiondate',time);
1163:
1164:
1165: $scrout.=&textfield('Publisher/Owner','owner',
1166: $metadatafields{'owner'});
1167:
1168: # -------------------------------------------------- Correct copyright for rat.
1169: my $defaultoption=$metadatafields{'copyright'};
1170: unless ($defaultoption) { $defaultoption='default'; }
1171: unless ($style eq 'prv') {
1172: if ($style eq 'rat') {
1173: if ($metadatafields{'copyright'} eq 'public') {
1174: delete $metadatafields{'copyright'};
1175: $defaultoption='default';
1176: }
1177: $scrout.=&selectbox('Copyright/Distribution','copyright',
1178: $defaultoption,
1179: \&Apache::loncommon::copyrightdescription,
1180: (grep !/^public$/,(&Apache::loncommon::copyrightids)));
1181: } else {
1182: $scrout.=&selectbox('Copyright/Distribution','copyright',
1183: $defaultoption,
1184: \&Apache::loncommon::copyrightdescription,
1185: (&Apache::loncommon::copyrightids));
1186: }
1187:
1188: my $copyright_help =
1189: Apache::loncommon::help_open_topic('Publishing_Copyright');
1190: $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
1191: $scrout.=&textfield('Custom Distribution File','customdistributionfile',
1192: $metadatafields{'customdistributionfile'}).
1193: $copyright_help;
1194: my $uctitle=uc(&mt('Obsolete'));
1195: $scrout.=
1196: "\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
1197: '</b></font> <input type="checkbox" name="obsolete" ';
1198: if ($metadatafields{'obsolete'}) {
1199: $scrout.=' checked="1" ';
1200: }
1201: $scrout.='/ ></p>'.
1202: &textfield('Suggested Replacement for Obsolete File',
1203: 'obsoletereplacement',
1204: $metadatafields{'obsoletereplacement'});
1205: } else {
1206: $scrout.=&hiddenfield('copyright','private');
1207: }
1208: return ($scrout.'<p><input type="submit" value="'.
1209: &mt('Finalize Publication').'" /></p></form>',0);
1210: # =============================================================================
1211: # BATCH MODE
1212: #
1213: } else {
1214: # Transfer metadata directly to environment for stage 2
1215: foreach (keys %metadatafields) {
1216: $ENV{'form.'.$_}=$metadatafields{$_};
1217: }
1218: $ENV{'form.addkey'}='';
1219: $ENV{'form.keywords'}='';
1220: foreach (keys %keywords) {
1221: if ($metadatafields{'keywords'}) {
1222: if ($metadatafields{'keywords'}=~/\Q$_\E/) {
1223: $ENV{'form.keywords'}.=$_.',';
1224: }
1225: } elsif (&Apache::loncommon::keyword($_)) {
1226: $ENV{'form.keywords'}.=$_.',';
1227: }
1228: }
1229: $ENV{'form.keywords'}=~s/\,$//;
1230: unless ($ENV{'form.creationdate'}) { $ENV{'form.creationdate'}=time; }
1231: $ENV{'form.lastrevisiondate'}=time;
1232: if ((($style eq 'rat') && ($ENV{'form.copyright'} eq 'public')) ||
1233: (!$ENV{'form.copyright'})) {
1234: $ENV{'form.copyright'}='default';
1235: }
1236: $ENV{'form.allmeta'}=&Apache::lonnet::escape($allmeta);
1237: return ($scrout,0);
1238: }
1239: }
1240:
1241: #########################################
1242: #########################################
1243:
1244: =pod
1245:
1246: =item B<phasetwo>
1247:
1248: Render second interface showing status of publication steps.
1249: This is publication step two.
1250:
1251: Parameters:
1252:
1253: =over 4
1254:
1255: =item I<$source>
1256:
1257: =item I<$target>
1258:
1259: =item I<$style>
1260:
1261: =item I<$distarget>
1262:
1263: =back
1264:
1265: Returns:
1266:
1267: =over 4
1268:
1269: =item Scalar string
1270:
1271: String contains status (errors and warnings) and information associated with
1272: the server's attempts at publication.
1273:
1274: =cut
1275:
1276: #'stupid emacs
1277: #########################################
1278: #########################################
1279: sub phasetwo {
1280:
1281: my ($r,$source,$target,$style,$distarget,$batch)=@_;
1282: $source=~s/\/+/\//g;
1283: $target=~s/\/+/\//g;
1284:
1285: if ($target=~/\_\_\_/) {
1286: $r->print(
1287: '<font color="red">'.&mt('Unsupported character combination').
1288: ' "<tt>___</tt>" '.&mt('in filename, FAIL').'</font>');
1289: return 0;
1290: }
1291: $distarget=~s/\/+/\//g;
1292: my $logfile;
1293: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1294: $r->print(
1295: '<font color="red">'.
1296: &mt('No write permission to user directory, FAIL').'</font>');
1297: return 0;
1298: }
1299: print $logfile
1300: "\n================= Publish ".localtime()." Phase Two ================\n".$ENV{'user.name'}.'@'.$ENV{'user.domain'}."\n";
1301:
1302: %metadatafields=();
1303: %metadatakeys=();
1304:
1305: &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
1306:
1307: $metadatafields{'title'}=$ENV{'form.title'};
1308: $metadatafields{'author'}=$ENV{'form.author'};
1309: $metadatafields{'subject'}=$ENV{'form.subject'};
1310: $metadatafields{'notes'}=$ENV{'form.notes'};
1311: $metadatafields{'abstract'}=$ENV{'form.abstract'};
1312: $metadatafields{'mime'}=$ENV{'form.mime'};
1313: $metadatafields{'language'}=$ENV{'form.language'};
1314: $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
1315: $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
1316: $metadatafields{'owner'}=$ENV{'form.owner'};
1317: $metadatafields{'copyright'}=$ENV{'form.copyright'};
1318: $metadatafields{'customdistributionfile'}=
1319: $ENV{'form.customdistributionfile'};
1320: $metadatafields{'obsolete'}=$ENV{'form.obsolete'};
1321: $metadatafields{'obsoletereplacement'}=
1322: $ENV{'form.obsoletereplacement'};
1323: $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
1324:
1325: my $allkeywords=$ENV{'form.addkey'};
1326: if (exists($ENV{'form.keywords'})) {
1327: if (ref($ENV{'form.keywords'})) {
1328: $allkeywords .= ','.join(',',@{$ENV{'form.keywords'}});
1329: } else {
1330: $allkeywords .= ','.$ENV{'form.keywords'};
1331: }
1332: }
1333: $allkeywords=~s/\W+/\,/;
1334: $allkeywords=~s/^\,//;
1335: $metadatafields{'keywords'}=$allkeywords;
1336:
1337: {
1338: print $logfile "\nWrite metadata file for ".$source;
1339: my $mfh;
1340: unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
1341: return
1342: '<font color="red">'.&mt('Could not write metadata, FAIL').
1343: '</font>';
1344: }
1345: foreach (sort keys %metadatafields) {
1346: unless ($_=~/\./) {
1347: my $unikey=$_;
1348: $unikey=~/^([A-Za-z]+)/;
1349: my $tag=$1;
1350: $tag=~tr/A-Z/a-z/;
1351: print $mfh "\n\<$tag";
1352: foreach (split(/\,/,$metadatakeys{$unikey})) {
1353: my $value=$metadatafields{$unikey.'.'.$_};
1354: $value=~s/\"/\'\'/g;
1355: print $mfh ' '.$_.'="'.$value.'"';
1356: }
1357: print $mfh '>'.
1358: &HTML::Entities::encode($metadatafields{$unikey})
1359: .'</'.$tag.'>';
1360: }
1361: }
1362: $r->print('<p>'.&mt('Wrote Metadata').'</p>');
1363: print $logfile "\nWrote metadata";
1364: }
1365:
1366: # -------------------------------- Synchronize entry with SQL metadata database
1367:
1368: $metadatafields{'url'} = $distarget;
1369: $metadatafields{'version'} = 'current';
1370: unless ($metadatafields{'copyright'} eq 'priv') {
1371: my ($error,$success) = &store_metadata(\%metadatafields);
1372: if ($success) {
1373: $r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
1374: print $logfile "\nSynchronized SQL metadata database";
1375: } else {
1376: $r->print($error);
1377: print $logfile "\n".$error;
1378: }
1379: } else {
1380: $r->print('<p>'.
1381: &mt('Private Publication - did not synchronize database').'</p>');
1382: print $logfile "\nPrivate: Did not synchronize data into ".
1383: "SQL metadata database";
1384: }
1385: # ----------------------------------------------------------- Copy old versions
1386:
1387: if (-e $target) {
1388: my $filename;
1389: my $maxversion=0;
1390: $target=~/(.*)\/([^\/]+)\.(\w+)$/;
1391: my $srcf=$2;
1392: my $srct=$3;
1393: my $srcd=$1;
1394: unless ($srcd=~/^\/home\/httpd\/html\/res/) {
1395: print $logfile "\nPANIC: Target dir is ".$srcd;
1396: return "<font color=\"red\">Invalid target directory, FAIL</font>";
1397: }
1398: opendir(DIR,$srcd);
1399: while ($filename=readdir(DIR)) {
1400: if (-l $srcd.'/'.$filename) {
1401: unlink($srcd.'/'.$filename);
1402: unlink($srcd.'/'.$filename.'.meta');
1403: } else {
1404: if ($filename=~/\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
1405: $maxversion=($1>$maxversion)?$1:$maxversion;
1406: }
1407: }
1408: }
1409: closedir(DIR);
1410: $maxversion++;
1411: $r->print('<p>Creating old version '.$maxversion.'</p>');
1412: print $logfile "\nCreating old version ".$maxversion."\n";
1413:
1414: my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
1415:
1416: if (copy($target,$copyfile)) {
1417: print $logfile "Copied old target to ".$copyfile."\n";
1418: $r->print('<p>'.&mt('Copied old target file').'</p>');
1419: } else {
1420: print $logfile "Unable to write ".$copyfile.':'.$!."\n";
1421: return "<font color=\"red\">".&mt('Failed to copy old target').
1422: ", $!, ".&mt('FAIL')."</font>";
1423: }
1424:
1425: # --------------------------------------------------------------- Copy Metadata
1426:
1427: $copyfile=$copyfile.'.meta';
1428:
1429: if (copy($target.'.meta',$copyfile)) {
1430: print $logfile "Copied old target metadata to ".$copyfile."\n";
1431: $r->print('<p>'.&mt('Copied old metadata').'</p>')
1432: } else {
1433: print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1434: if (-e $target.'.meta') {
1435: return
1436: "<font color=\"red\">".
1437: &mt('Failed to write old metadata copy').", $!, ".&mt('FAIL')."</font>";
1438: }
1439: }
1440:
1441:
1442: } else {
1443: $r->print('<p>'.&mt('Initial version').'</p>');
1444: print $logfile "\nInitial version";
1445: }
1446:
1447: # ---------------------------------------------------------------- Write Source
1448: my $copyfile=$target;
1449:
1450: my @parts=split(/\//,$copyfile);
1451: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1452:
1453: my $count;
1454: for ($count=5;$count<$#parts;$count++) {
1455: $path.="/$parts[$count]";
1456: if ((-e $path)!=1) {
1457: print $logfile "\nCreating directory ".$path;
1458: $r->print('<p>'.&mt('Created directory').' '.$parts[$count].'</p>');
1459: mkdir($path,0777);
1460: }
1461: }
1462:
1463: if (copy($source,$copyfile)) {
1464: print $logfile "\nCopied original source to ".$copyfile."\n";
1465: $r->print('<p>'.&mt('Copied source file').'</p>');
1466: } else {
1467: print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
1468: return "<font color=\"red\">".
1469: &mt('Failed to copy source').", $!, ".&mt('FAIL')."</font>";
1470: }
1471:
1472: # --------------------------------------------------------------- Copy Metadata
1473:
1474: $copyfile=$copyfile.'.meta';
1475:
1476: if (copy($source.'.meta',$copyfile)) {
1477: print $logfile "\nCopied original metadata to ".$copyfile."\n";
1478: $r->print('<p>'.&mt('Copied metadata').'</p>');
1479: } else {
1480: print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
1481: return
1482: "<font color=\"red\">".&mt('Failed to write metadata copy').", $!, ".&mt('FAIL')."</font>";
1483: }
1484: $r->rflush;
1485: # --------------------------------------------------- Send update notifications
1486:
1487: my @subscribed=&get_subscribed_hosts($target);
1488: foreach my $subhost (@subscribed) {
1489: $r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
1490: print $logfile "\nNotifying host ".$subhost.':';
1491: my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
1492: $r->print($reply.'</p><br />');$r->rflush;
1493: print $logfile $reply;
1494: }
1495:
1496: # ---------------------------------------- Send update notifications, meta only
1497:
1498: my @subscribedmeta=&get_subscribed_hosts("$target.meta");
1499: foreach my $subhost (@subscribedmeta) {
1500: $r->print('<p>'.
1501: &mt('Notifying host for metadata only').' '.$subhost.':');$r->rflush;
1502: print $logfile "\nNotifying host for metadata only ".$subhost.':';
1503: my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
1504: $subhost);
1505: $r->print($reply.'</p><br />');$r->rflush;
1506: print $logfile $reply;
1507: }
1508:
1509: # --------------------------------------------------- Notify subscribed courses
1510: my %courses=&coursedependencies($target);
1511: my $now=time;
1512: foreach (keys %courses) {
1513: $r->print('<p>'.&mt('Notifying course').' '.$_.':');$r->rflush;
1514: print $logfile "\nNotifying host ".$_.':';
1515: my ($cdom,$cname)=split(/\_/,$_);
1516: my $reply=&Apache::lonnet::cput
1517: ('versionupdate',{$target => $now},$cdom,$cname);
1518: $r->print($reply.'</p><br />');$r->rflush;
1519: print $logfile $reply;
1520: }
1521: # ------------------------------------------------ Provide link to new resource
1522: unless ($batch) {
1523: my $thisdistarget=$target;
1524: $thisdistarget=~s/^\Q$docroot\E//;
1525:
1526: my $thissrc=$source;
1527: $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
1528:
1529: my $thissrcdir=$thissrc;
1530: $thissrcdir=~s/\/[^\/]+$/\//;
1531:
1532:
1533: $r->print(
1534: '<hr /><a href="'.$thisdistarget.'"><font size="+2">'.
1535: &mt('View Published Version').'</font></a>'.
1536: '<p><a href="'.$thissrc.'"><font size=+2>'.
1537: &mt('Back to Source').'</font></a></p>'.
1538: '<p><a href="'.$thissrcdir.
1539: '"><font size="+2">'.
1540: &mt('Back to Source Directory').'</font></a></p>');
1541: }
1542: }
1543:
1544: #########################################
1545:
1546: sub batchpublish {
1547: my ($r,$srcfile,$targetfile)=@_;
1548: #publication pollutes %ENV with form.* values
1549: my %oldENV=%ENV;
1550: $srcfile=~s/\/+/\//g;
1551: $targetfile=~s/\/+/\//g;
1552: my $thisdisfn=$srcfile;
1553: $thisdisfn=~s/\/home\/korte\/public_html\///;
1554: $srcfile=~s/\/+/\//g;
1555:
1556: my $docroot=$r->dir_config('lonDocRoot');
1557: my $thisdistarget=$targetfile;
1558: $thisdistarget=~s/^\Q$docroot\E//;
1559:
1560:
1561: %metadatafields=();
1562: %metadatakeys=();
1563: $srcfile=~/\.(\w+)$/;
1564: my $thistype=$1;
1565:
1566:
1567: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1568:
1569: $r->print('<h2>'.&mt('Publishing').' <tt>'.$thisdisfn.'</tt></h2>');
1570:
1571: # phase one takes
1572: # my ($source,$target,$style,$batch)=@_;
1573: my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
1574: $r->print('<p>'.$outstring.'</p>');
1575: # phase two takes
1576: # my ($source,$target,$style,$distarget,batch)=@_;
1577: # $ENV{'form.allmeta'},$ENV{'form.title'},$ENV{'form.author'},...
1578: if (!$error) {
1579: $r->print('<p>');
1580: &phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
1581: $r->print('</p>');
1582: }
1583: %ENV=%oldENV;
1584: return '';
1585: }
1586:
1587: #########################################
1588:
1589: sub publishdirectory {
1590: my ($r,$fn,$thisdisfn)=@_;
1591: $fn=~s/\/+/\//g;
1592: $thisdisfn=~s/\/+/\//g;
1593: my $resdir=
1594: $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cudom.'/'.$cuname.'/'.
1595: $thisdisfn;
1596: $r->print('<h1>Directory <tt>'.$thisdisfn.'</tt></h1>'.
1597: 'Target: <tt>'.$resdir.'</tt><br />');
1598:
1599: my $dirptr=16384; # Mask indicating a directory in stat.cmode.
1600:
1601: opendir(DIR,$fn);
1602: my @files=sort(readdir(DIR));
1603: foreach my $filename (@files) {
1604: my ($cdev,$cino,$cmode,$cnlink,
1605: $cuid,$cgid,$crdev,$csize,
1606: $catime,$cmtime,$cctime,
1607: $cblksize,$cblocks)=stat($fn.'/'.$filename);
1608:
1609: my $extension='';
1610: if ($filename=~/\.(\w+)$/) { $extension=$1; }
1611: if ($cmode&$dirptr) {
1612: if (($filename!~/^\./) && ($ENV{'form.pubrec'})) {
1613: &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
1614: }
1615: } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
1616: ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
1617: # find out publication status and/or exiting metadata
1618: my $publishthis=0;
1619: if (-e $resdir.'/'.$filename) {
1620: my ($rdev,$rino,$rmode,$rnlink,
1621: $ruid,$rgid,$rrdev,$rsize,
1622: $ratime,$rmtime,$rctime,
1623: $rblksize,$rblocks)=stat($resdir.'/'.$filename);
1624: if (($rmtime<$cmtime) || ($ENV{'form.forcerepub'})) {
1625: # previously published, modified now
1626: $publishthis=1;
1627: }
1628: } else {
1629: # never published
1630: $publishthis=1;
1631: }
1632: if ($publishthis) {
1633: &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
1634: } else {
1635: $r->print('<br />Skipping '.$filename.'<br />');
1636: }
1637: $r->rflush();
1638: }
1639: }
1640: closedir(DIR);
1641: }
1642: #########################################
1643:
1644: =pod
1645:
1646: =item B<handler>
1647:
1648: A basic outline of the handler subroutine follows.
1649:
1650: =over 4
1651:
1652: =item *
1653:
1654: Get query string for limited number of parameters.
1655:
1656: =item *
1657:
1658: Check filename.
1659:
1660: =item *
1661:
1662: File is there and owned, init lookup tables.
1663:
1664: =item *
1665:
1666: Start page output.
1667:
1668: =item *
1669:
1670: Evaluate individual file, and then output information.
1671:
1672: =item *
1673:
1674: Publishing from $thisfn to $thistarget with $thisembstyle.
1675:
1676: =back
1677:
1678: =cut
1679:
1680: #########################################
1681: #########################################
1682: sub handler {
1683: my $r=shift;
1684:
1685: if ($r->header_only) {
1686: &Apache::loncommon::content_type($r,'text/html');
1687: $r->send_http_header;
1688: return OK;
1689: }
1690:
1691: # Get query string for limited number of parameters
1692:
1693: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1694: ['filename']);
1695:
1696: # -------------------------------------------------------------- Check filename
1697:
1698: my $fn=&Apache::lonnet::unescape($ENV{'form.filename'});
1699:
1700:
1701: unless ($fn) {
1702: $r->log_reason($cuname.' at '.$cudom.
1703: ' trying to publish empty filename', $r->filename);
1704: return HTTP_NOT_FOUND;
1705: }
1706:
1707: ($cuname,$cudom)=
1708: &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
1709: unless (($cuname) && ($cudom)) {
1710: $r->log_reason($cuname.' at '.$cudom.
1711: ' trying to publish file '.$ENV{'form.filename'}.
1712: ' ('.$fn.') - not authorized',
1713: $r->filename);
1714: return HTTP_NOT_ACCEPTABLE;
1715: }
1716:
1717: unless (&Apache::lonnet::homeserver($cuname,$cudom)
1718: eq $r->dir_config('lonHostID')) {
1719: $r->log_reason($cuname.' at '.$cudom.
1720: ' trying to publish file '.$ENV{'form.filename'}.
1721: ' ('.$fn.') - not homeserver ('.
1722: &Apache::lonnet::homeserver($cuname,$cudom).')',
1723: $r->filename);
1724: return HTTP_NOT_ACCEPTABLE;
1725: }
1726:
1727: $fn=~s/^http\:\/\/[^\/]+//;
1728: $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
1729:
1730: my $targetdir='';
1731: $docroot=$r->dir_config('lonDocRoot');
1732: if ($1 ne $cuname) {
1733: $r->log_reason($cuname.' at '.$cudom.
1734: ' trying to publish unowned file '.
1735: $ENV{'form.filename'}.' ('.$fn.')',
1736: $r->filename);
1737: return HTTP_NOT_ACCEPTABLE;
1738: } else {
1739: $targetdir=$docroot.'/res/'.$cudom;
1740: }
1741:
1742:
1743: unless (-e $fn) {
1744: $r->log_reason($cuname.' at '.$cudom.
1745: ' trying to publish non-existing file '.
1746: $ENV{'form.filename'}.' ('.$fn.')',
1747: $r->filename);
1748: return HTTP_NOT_FOUND;
1749: }
1750:
1751: unless ($ENV{'form.phase'} eq 'two') {
1752:
1753: # -------------------------------- File is there and owned, init lookup tables.
1754:
1755: %addid=();
1756:
1757: {
1758: my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
1759: while (<$fh>=~/(\w+)\s+(\w+)/) {
1760: $addid{$1}=$2;
1761: }
1762: }
1763:
1764: %nokey=();
1765:
1766: {
1767: my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
1768: while (<$fh>) {
1769: my $word=$_;
1770: chomp($word);
1771: $nokey{$word}=1;
1772: }
1773: }
1774:
1775: }
1776:
1777: # ---------------------------------------------------------- Start page output.
1778:
1779: &Apache::loncommon::content_type($r,'text/html');
1780: $r->send_http_header;
1781:
1782: $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
1783: $r->print(&Apache::loncommon::bodytag('Resource Publication'));
1784:
1785:
1786: my $thisfn=$fn;
1787:
1788: my $thistarget=$thisfn;
1789:
1790: $thistarget=~s/^\/home/$targetdir/;
1791: $thistarget=~s/\/public\_html//;
1792:
1793: my $thisdistarget=$thistarget;
1794: $thisdistarget=~s/^\Q$docroot\E//;
1795:
1796: my $thisdisfn=$thisfn;
1797: $thisdisfn=~s/^\/home\/\Q$cuname\E\/public_html\///;
1798:
1799: if ($fn=~/\/$/) {
1800: # -------------------------------------------------------- This is a directory
1801: &publishdirectory($r,$fn,$thisdisfn);
1802: $r->print('<hr><font size="+2">'.&mt('Done').'</font><br><a href="/priv/'
1803: .$cuname.'/'.$thisdisfn
1804: .'">'.&mt('Return to Directory').'</a>');
1805:
1806:
1807: } else {
1808: # ---------------------- Evaluate individual file, and then output information.
1809: $thisfn=~/\.(\w+)$/;
1810: my $thistype=$1;
1811: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1812: $r->print('<h2>'.&mt('Publishing').' '.
1813: &Apache::loncommon::filedescription($thistype).' <tt>');
1814:
1815: $r->print(<<ENDCAPTION);
1816: <a href='javascript:void(window.open("/~$cuname/$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
1817: $thisdisfn</a>
1818: ENDCAPTION
1819: $r->print('</tt></h2><b>'.&mt('Target').':</b> <tt>'.
1820: $thisdistarget.'</tt><br />');
1821:
1822: if (($cuname ne $ENV{'user.name'})||($cudom ne $ENV{'user.domain'})) {
1823: $r->print('<h3><font color="red">'.&mt('Co-Author').': '.
1824: $cuname.&mt(' at ').$cudom.'</font></h3>');
1825: }
1826:
1827: if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
1828: $r->print(<<ENDDIFF);
1829: <br />
1830: <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"))'>
1831: ENDDIFF
1832: $r->print(&mt('Diffs with Current Version').'</a><br />');
1833: }
1834:
1835: # ------------------ Publishing from $thisfn to $thistarget with $thisembstyle.
1836:
1837: unless ($ENV{'form.phase'} eq 'two') {
1838: my ($outstring,$error)=&publish($thisfn,$thistarget,$thisembstyle);
1839: $r->print('<hr />'.$outstring);
1840: } else {
1841: $r->print('<hr />');
1842: &phasetwo($r,$thisfn,$thistarget,$thisembstyle,$thisdistarget);
1843: }
1844: }
1845: $r->print('</body></html>');
1846:
1847: return OK;
1848: }
1849:
1850: 1;
1851: __END__
1852:
1853: =pod
1854:
1855: =back
1856:
1857: =back
1858:
1859: =cut
1860:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>