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