1: # The LearningOnline Network with CAPA
2: # Publication Handler
3: #
4: # $Id: lonpublisher.pm,v 1.289 2014/01/15 18:49:56 bisitz 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</priv/domain/authorname/> space.
70: They can copy resources into the resource area through the
71: publication step, and move them back through a recover step.
72: Authors do not have direct 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: =cut
106:
107: ######################################################################
108: ######################################################################
109:
110:
111: package Apache::lonpublisher;
112:
113: # ------------------------------------------------- modules used by this module
114: use strict;
115: use Apache::File;
116: use File::Copy;
117: use Apache::Constants qw(:common :http :methods);
118: use HTML::LCParser;
119: use HTML::Entities;
120: use Encode::Encoder;
121: use Apache::lonxml;
122: use DBI;
123: use Apache::lonnet;
124: use Apache::loncommon();
125: use Apache::lonhtmlcommon;
126: use Apache::lonmysql;
127: use Apache::lonlocal;
128: use Apache::loncfile;
129: use LONCAPA::lonmetadata;
130: use Apache::lonmsg;
131: use vars qw(%metadatafields %metadatakeys);
132: use LONCAPA qw(:DEFAULT :match);
133:
134:
135: my %addid;
136: my %nokey;
137:
138: my $docroot;
139:
140: my $cuname;
141: my $cudom;
142:
143: my $registered_cleanup;
144: my $modified_urls;
145:
146: my $lock;
147:
148: =pod
149:
150: =over 4
151:
152: =item B<metaeval>
153:
154: Evaluates a string that contains metadata. This subroutine
155: stores values inside I<%metadatafields> and I<%metadatakeys>.
156: The hash key is a I<$unikey> corresponding to a unique id
157: that is descriptive of the parser location inside the XML tree.
158:
159: Parameters:
160:
161: =over 4
162:
163: =item I<$metastring>
164:
165: A string that contains metadata.
166:
167: =back
168:
169: Returns:
170:
171: nothing
172:
173: =cut
174:
175: #########################################
176: #########################################
177: #
178: # Modifies global %metadatafields %metadatakeys
179: #
180:
181: sub metaeval {
182: my ($metastring,$prefix)=@_;
183:
184: my $parser=HTML::LCParser->new(\$metastring);
185: my $token;
186: while ($token=$parser->get_token) {
187: if ($token->[0] eq 'S') {
188: my $entry=$token->[1];
189: my $unikey=$entry;
190: next if ($entry =~ m/^(?:parameter|stores)_/);
191: if (defined($token->[2]->{'package'})) {
192: $unikey.="\0package\0".$token->[2]->{'package'};
193: }
194: if (defined($token->[2]->{'part'})) {
195: $unikey.="\0".$token->[2]->{'part'};
196: }
197: if (defined($token->[2]->{'id'})) {
198: $unikey.="\0".$token->[2]->{'id'};
199: }
200: if (defined($token->[2]->{'name'})) {
201: $unikey.="\0".$token->[2]->{'name'};
202: }
203: foreach (@{$token->[3]}) {
204: $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
205: if ($metadatakeys{$unikey}) {
206: $metadatakeys{$unikey}.=','.$_;
207: } else {
208: $metadatakeys{$unikey}=$_;
209: }
210: }
211: my $newentry=$parser->get_text('/'.$entry);
212: if (($entry eq 'customdistributionfile') ||
213: ($entry eq 'sourcerights')) {
214: $newentry=~s/^\s*//;
215: if ($newentry !~m|^/res|) { $newentry=$prefix.$newentry; }
216: }
217: # actually store
218: if ( $entry eq 'rule' && exists($metadatafields{$unikey})) {
219: $metadatafields{$unikey}.=','.$newentry;
220: } else {
221: $metadatafields{$unikey}=$newentry;
222: }
223: }
224: }
225: }
226:
227: #########################################
228: #########################################
229:
230: =pod
231:
232: =item B<metaread>
233:
234: Read a metadata file
235:
236: Parameters:
237:
238: =over
239:
240: =item I<$logfile>
241:
242: File output stream to output errors and warnings to.
243:
244: =item I<$fn>
245:
246: File name (including path).
247:
248: =back
249:
250: Returns:
251:
252: =over 4
253:
254: =item Scalar string (if successful)
255:
256: XHTML text that indicates successful reading of the metadata.
257:
258: =back
259:
260: =cut
261:
262: #########################################
263: #########################################
264: sub metaread {
265: my ($logfile,$fn,$prefix)=@_;
266: unless (-e $fn) {
267: print($logfile 'No file '.$fn."\n");
268: return '<p class="LC_warning">'
269: .&mt('No file: [_1]',&Apache::loncfile::display($fn))
270: .'</p>';
271: }
272: print($logfile 'Processing '.$fn."\n");
273: my $metastring;
274: {
275: my $metafh=Apache::File->new($fn);
276: $metastring=join('',<$metafh>);
277: }
278: &metaeval($metastring,$prefix);
279: return '<p class="LC_info">'
280: .&mt('Processed file: [_1]',&Apache::loncfile::display($fn))
281: .'</p>';
282: }
283:
284: #########################################
285: #########################################
286:
287: sub coursedependencies {
288: my $url=&Apache::lonnet::declutter(shift);
289: $url=~s/\.meta$//;
290: my ($adomain,$aauthor)=($url=~ m{^($match_domain)/($match_username)/});
291: my $regexp=quotemeta($url);
292: $regexp='___'.$regexp.'___course';
293: my %evaldata=&Apache::lonnet::dump('nohist_resevaldata',$adomain,
294: $aauthor,$regexp);
295: my %courses=();
296: foreach (keys %evaldata) {
297: if ($_=~/^([a-zA-Z0-9]+_[a-zA-Z0-9]+)___.+___course$/) {
298: $courses{$1}=1;
299: }
300: }
301: return %courses;
302: }
303: #########################################
304: #########################################
305:
306:
307: =pod
308:
309: =item Form-field-generating subroutines.
310:
311: For input parameters, these subroutines take in values
312: such as I<$name>, I<$value> and other form field metadata.
313: The output (scalar string that is returned) is an XHTML
314: string which presents the form field (foreseeably inside
315: <form></form> tags).
316:
317: =over 4
318:
319: =item B<textfield>
320:
321: =item B<hiddenfield>
322:
323: =item B<selectbox>
324:
325: =back
326:
327: =cut
328:
329: #########################################
330: #########################################
331: sub textfield {
332: my ($title,$name,$value,$noline)=@_;
333: $value=~s/^\s+//gs;
334: $value=~s/\s+$//gs;
335: $value=~s/\s+/ /gs;
336: $title=&mt($title);
337: $env{'form.'.$name}=$value;
338: return "\n".&Apache::lonhtmlcommon::row_title($title)
339: .'<input type="text" name="'.$name.'" size="80" value="'.$value.'" />'
340: .&Apache::lonhtmlcommon::row_closure($noline);
341: }
342:
343: sub text_with_browse_field {
344: my ($title,$name,$value,$restriction,$noline)=@_;
345: $value=~s/^\s+//gs;
346: $value=~s/\s+$//gs;
347: $value=~s/\s+/ /gs;
348: $title=&mt($title);
349: $env{'form.'.$name}=$value;
350: return "\n".&Apache::lonhtmlcommon::row_title($title)
351: .'<input type="text" name="'.$name.'" size="80" value="'.$value.'" />'
352: .'<br />'
353: .'<a href="javascript:openbrowser(\'pubform\',\''.$name.'\',\''.$restriction.'\');">'
354: .&mt('Select')
355: .'</a> '
356: .'<a href="javascript:opensearcher(\'pubform\',\''.$name.'\');">'
357: .&mt('Search')
358: .'</a>'
359: .&Apache::lonhtmlcommon::row_closure($noline);
360: }
361:
362: sub hiddenfield {
363: my ($name,$value)=@_;
364: $env{'form.'.$name}=$value;
365: return "\n".'<input type="hidden" name="'.$name.'" value="'.$value.'" />';
366: }
367:
368: sub checkbox {
369: my ($name,$text)=@_;
370: return "\n<br /><label><input type='checkbox' name='$name' /> ".
371: &mt($text)."</label>";
372: }
373:
374: sub selectbox {
375: my ($title,$name,$value,$functionref,@idlist)=@_;
376: $title=&mt($title);
377: $value=(split(/\s*,\s*/,$value))[-1];
378: if (defined($value)) {
379: $env{'form.'.$name}=$value;
380: } else {
381: $env{'form.'.$name}=$idlist[0];
382: }
383: my $selout="\n".&Apache::lonhtmlcommon::row_title($title)
384: .'<select name="'.$name.'">';
385: foreach (@idlist) {
386: $selout.='<option value="'.$_.'"';
387: if ($_ eq $value) {
388: $selout.=' selected="selected"';
389: }
390: $selout.='>'.&{$functionref}($_).'</option>';
391: }
392: $selout.='</select>'.&Apache::lonhtmlcommon::row_closure();
393: return $selout;
394: }
395:
396: sub select_level_form {
397: my ($value,$name)=@_;
398: $env{'form.'.$name}=$value;
399: if (!defined($value)) { $env{'form.'.$name}=0; }
400: return &Apache::loncommon::select_level_form($value,$name);
401: }
402: #########################################
403: #########################################
404:
405: =pod
406:
407: =item B<urlfixup>
408:
409: Fix up a url? First step of publication
410:
411: =cut
412:
413: #########################################
414: #########################################
415: sub urlfixup {
416: my ($url,$target)=@_;
417: unless ($url) { return ''; }
418: #javascript code needs no fixing
419: if ($url =~ /^javascript:/i) { return $url; }
420: if ($url =~ /^mailto:/i) { return $url; }
421: #internal document links need no fixing
422: if ($url =~ /^\#/) { return $url; }
423: my ($host)=($url=~m{(?:(?:http|https|ftp)://)*([^/]+)});
424: my @lonids = &Apache::lonnet::machine_ids($host);
425: if (@lonids) {
426: $url=~s{^(?:http|https|ftp)://}{};
427: $url=~s/^\Q$host\E//;
428: }
429: if ($url=~m{^(?:http|https|ftp)://}) { return $url; }
430: $url=~s{\Q~$cuname\E}{res/$cudom/$cuname};
431: return $url;
432: }
433:
434: #########################################
435: #########################################
436:
437: =pod
438:
439: =item B<absoluteurl>
440:
441: Currently undocumented.
442:
443: =cut
444:
445: #########################################
446: #########################################
447: sub absoluteurl {
448: my ($url,$target)=@_;
449: unless ($url) { return ''; }
450: if ($target) {
451: $target=~s/\/[^\/]+$//;
452: $url=&Apache::lonnet::hreflocation($target,$url);
453: }
454: return $url;
455: }
456:
457: #########################################
458: #########################################
459:
460: =pod
461:
462: =item B<set_allow>
463:
464: Currently undocumented
465:
466: =cut
467:
468: #########################################
469: #########################################
470: sub set_allow {
471: my ($allow,$logfile,$target,$tag,$oldurl)=@_;
472: my $newurl=&urlfixup($oldurl,$target);
473: my $return_url=$oldurl;
474: print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
475: if ($newurl ne $oldurl) {
476: $return_url=$newurl;
477: print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
478: }
479: if (($newurl !~ /^javascript:/i) &&
480: ($newurl !~ /^mailto:/i) &&
481: ($newurl !~ /^(?:http|https|ftp):/i) &&
482: ($newurl !~ /^\#/)) {
483: $$allow{&absoluteurl($newurl,$target)}=1;
484: }
485: return $return_url;
486: }
487:
488: #########################################
489: #########################################
490:
491: =pod
492:
493: =item B<get_subscribed_hosts>
494:
495: Currently undocumented
496:
497: =cut
498:
499: #########################################
500: #########################################
501: sub get_subscribed_hosts {
502: my ($target)=@_;
503: my @subscribed;
504: my $filename;
505: $target=~/(.*)\/([^\/]+)$/;
506: my $srcf=$2;
507: opendir(DIR,$1);
508: # cycle through listed files, subscriptions used to exist
509: # as "filename.lonid"
510: while ($filename=readdir(DIR)) {
511: if ($filename=~/\Q$srcf\E\.($match_lonid)$/) {
512: my $subhost=$1;
513: if (($subhost ne 'meta'
514: && $subhost ne 'subscription'
515: && $subhost ne 'meta.subscription'
516: && $subhost ne 'tmp') &&
517: ($subhost ne $Apache::lonnet::perlvar{'lonHostID'})) {
518: push(@subscribed,$subhost);
519: }
520: }
521: }
522: closedir(DIR);
523: my $sh;
524: if ( $sh=Apache::File->new("$target.subscription") ) {
525: while (my $subline=<$sh>) {
526: if ($subline =~ /^($match_lonid):/) {
527: if ($1 ne $Apache::lonnet::perlvar{'lonHostID'}) {
528: push(@subscribed,$1);
529: }
530: }
531: }
532: }
533: return @subscribed;
534: }
535:
536:
537: #########################################
538: #########################################
539:
540: =pod
541:
542: =item B<get_max_ids_indices>
543:
544: Currently undocumented
545:
546: =cut
547:
548: #########################################
549: #########################################
550: sub get_max_ids_indices {
551: my ($content)=@_;
552: my $maxindex=10;
553: my $maxid=10;
554: my $needsfixup=0;
555: my $duplicateids=0;
556:
557: my %allids;
558: my %duplicatedids;
559:
560: my $parser=HTML::LCParser->new($content);
561: $parser->xml_mode(1);
562: my $token;
563: while ($token=$parser->get_token) {
564: if ($token->[0] eq 'S') {
565: my $counter;
566: if ($counter=$addid{$token->[1]}) {
567: if ($counter eq 'id') {
568: if (defined($token->[2]->{'id'}) &&
569: $token->[2]->{'id'} !~ /^\s*$/) {
570: $maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
571: if (exists($allids{$token->[2]->{'id'}})) {
572: $duplicateids=1;
573: $duplicatedids{$token->[2]->{'id'}}=1;
574: } else {
575: $allids{$token->[2]->{'id'}}=1;
576: }
577: } else {
578: $needsfixup=1;
579: }
580: } else {
581: if (defined($token->[2]->{'index'}) &&
582: $token->[2]->{'index'} !~ /^\s*$/) {
583: $maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
584: } else {
585: $needsfixup=1;
586: }
587: }
588: }
589: }
590: }
591: return ($needsfixup,$maxid,$maxindex,$duplicateids,
592: (keys(%duplicatedids)));
593: }
594:
595: #########################################
596: #########################################
597:
598: =pod
599:
600: =item B<get_all_text_unbalanced>
601:
602: Currently undocumented
603:
604: =cut
605:
606: #########################################
607: #########################################
608: sub get_all_text_unbalanced {
609: #there is a copy of this in lonxml.pm
610: my($tag,$pars)= @_;
611: my $token;
612: my $result='';
613: $tag='<'.$tag.'>';
614: while ($token = $$pars[-1]->get_token) {
615: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
616: $result.=$token->[1];
617: } elsif ($token->[0] eq 'PI') {
618: $result.=$token->[2];
619: } elsif ($token->[0] eq 'S') {
620: $result.=$token->[4];
621: } elsif ($token->[0] eq 'E') {
622: $result.=$token->[2];
623: }
624: if ($result =~ /\Q$tag\E/s) {
625: ($result,my $redo)=$result =~ /(.*)\Q$tag\E(.*)/is;
626: #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
627: #&Apache::lonnet::logthis('Result is :'.$1);
628: $redo=$tag.$redo;
629: push (@$pars,HTML::LCParser->new(\$redo));
630: $$pars[-1]->xml_mode('1');
631: last;
632: }
633: }
634: return $result
635: }
636:
637: #########################################
638: #########################################
639:
640: =pod
641:
642: =item B<fix_ids_and_indices>
643:
644: Currently undocumented
645:
646: =cut
647:
648: #########################################
649: #########################################
650: #Arguably this should all be done as a lonnet::ssi instead
651: sub fix_ids_and_indices {
652: my ($logfile,$source,$target)=@_;
653:
654: my %allow;
655: my $content;
656: {
657: my $org=Apache::File->new($source);
658: $content=join('',<$org>);
659: }
660:
661: my ($needsfixup,$maxid,$maxindex,$duplicateids,@duplicatedids)=
662: &get_max_ids_indices(\$content);
663:
664: print $logfile ("Got $needsfixup,$maxid,$maxindex,$duplicateids--".
665: join(', ',@duplicatedids));
666: if ($duplicateids) {
667: print $logfile "Duplicate ID(s) exist, ".join(', ',@duplicatedids)."\n";
668: my $outstring='<span class="LC_error">'.&mt('Unable to publish file, it contains duplicated ID(s), ID(s) need to be unique. The duplicated ID(s) are').': '.join(', ',@duplicatedids).'</span>';
669: return ($outstring,1);
670: }
671: if ($needsfixup) {
672: print $logfile "Needs ID and/or index fixup\n".
673: "Max ID : $maxid (min 10)\n".
674: "Max Index: $maxindex (min 10)\n";
675: }
676: my $outstring='';
677: my $responsecounter=1;
678: my @parser;
679: $parser[0]=HTML::LCParser->new(\$content);
680: $parser[-1]->xml_mode(1);
681: my $token;
682: while (@parser) {
683: while ($token=$parser[-1]->get_token) {
684: if ($token->[0] eq 'S') {
685: my $counter;
686: my $tag=$token->[1];
687: my $lctag=lc($tag);
688: if ($lctag eq 'allow') {
689: $allow{$token->[2]->{'src'}}=1;
690: next;
691: }
692: if ($lctag eq 'base') { next; }
693: if (($lctag eq 'part') || ($lctag eq 'problem')) {
694: $responsecounter=0;
695: }
696: if ($lctag=~/response$/) { $responsecounter++; }
697: if ($lctag eq 'import') { $responsecounter++; }
698: my %parms=%{$token->[2]};
699: $counter=$addid{$tag};
700: if (!$counter) { $counter=$addid{$lctag}; }
701: if ($counter) {
702: if ($counter eq 'id') {
703: unless (defined($parms{'id'}) &&
704: $parms{'id'}!~/^\s*$/) {
705: $maxid++;
706: $parms{'id'}=$maxid;
707: print $logfile 'ID(new) : '.$tag.':'.$maxid."\n";
708: } else {
709: print $logfile 'ID(kept): '.$tag.':'.$parms{'id'}."\n";
710: }
711: } elsif ($counter eq 'index') {
712: unless (defined($parms{'index'}) &&
713: $parms{'index'}!~/^\s*$/) {
714: $maxindex++;
715: $parms{'index'}=$maxindex;
716: print $logfile 'Index: '.$tag.':'.$maxindex."\n";
717: }
718: }
719: }
720: unless ($parms{'type'} eq 'zombie') {
721: foreach my $type ('src','href','background','bgimg') {
722: foreach my $key (keys(%parms)) {
723: if ($key =~ /^$type$/i) {
724: $parms{$key}=&set_allow(\%allow,$logfile,
725: $target,$tag,
726: $parms{$key});
727: }
728: }
729: }
730: }
731: # probably a <randomlabel> image type <label>
732: # or a <image> tag inside <imageresponse>
733: if (($lctag eq 'label' && defined($parms{'description'}))
734: ||
735: ($lctag eq 'image')) {
736: my $next_token=$parser[-1]->get_token();
737: if ($next_token->[0] eq 'T') {
738: $next_token->[1] =~ s/[\n\r\f]+//g;
739: $next_token->[1]=&set_allow(\%allow,$logfile,
740: $target,$tag,
741: $next_token->[1]);
742: }
743: $parser[-1]->unget_token($next_token);
744: }
745: if ($lctag eq 'applet') {
746: my $codebase='';
747: my $havecodebase=0;
748: foreach my $key (keys(%parms)) {
749: if (lc($key) eq 'codebase') {
750: $codebase=$parms{$key};
751: $havecodebase=1;
752: }
753: }
754: if ($havecodebase) {
755: my $oldcodebase=$codebase;
756: unless ($oldcodebase=~/\/$/) {
757: $oldcodebase.='/';
758: }
759: $codebase=&urlfixup($oldcodebase,$target);
760: $codebase=~s/\/$//;
761: if ($codebase ne $oldcodebase) {
762: $parms{'codebase'}=$codebase;
763: print $logfile 'URL codebase: '.$tag.':'.
764: $oldcodebase.' - '.
765: $codebase."\n";
766: }
767: $allow{&absoluteurl($codebase,$target).'/*'}=1;
768: } else {
769: foreach my $key (keys(%parms)) {
770: if ($key =~ /(archive|code|object)/i) {
771: my $oldurl=$parms{$key};
772: my $newurl=&urlfixup($oldurl,$target);
773: $newurl=~s/\/[^\/]+$/\/\*/;
774: print $logfile 'Allow: applet '.lc($key).':'.
775: $oldurl.' allows '.$newurl."\n";
776: $allow{&absoluteurl($newurl,$target)}=1;
777: }
778: }
779: }
780: }
781: my $newparmstring='';
782: my $endtag='';
783: foreach (keys %parms) {
784: if ($_ eq '/') {
785: $endtag=' /';
786: } else {
787: my $quote=($parms{$_}=~/\"/?"'":'"');
788: $newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
789: }
790: }
791: if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
792: $outstring.='<'.$tag.$newparmstring.$endtag.'>';
793: if ($lctag eq 'm' || $lctag eq 'answer' || $lctag eq 'display' ||
794: $lctag eq 'tex') {
795: $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
796: } elsif ($lctag eq 'script') {
797: if ($parms{'type'} eq 'loncapa/perl') {
798: $outstring.=&get_all_text_unbalanced('/'.$lctag,\@parser);
799: } else {
800: my $script = &get_all_text_unbalanced('/'.$lctag,\@parser);
801: if ($script =~ m{\.set\w+(Src|Swf)\(["']}i) {
802: my @srcs = split(/\.set/i,$script);
803: if (scalar(@srcs) > 1) {
804: foreach my $item (@srcs) {
805: if ($item =~ m{^(FlashPlayerSwf|MediaSrc|XMPSrc|ConfigurationSrc|PosterImageSrc)\((['"])(?:(?!\2).)+\2\)}is) {
806: my $srctype = $1;
807: my $quote = $2;
808: my ($url) = ($item =~ m{^\Q$srctype($quote\E([^$quote]+)\Q$quote)\E});
809: $url = &urlfixup($url);
810: unless ($url=~m{^(?:http|https|ftp)://}) {
811: $allow{&absoluteurl($url,$target)}=1;
812: if ($srctype eq 'ConfigurationSrc') {
813: if ($url =~ m{^(.+/)configuration_express\.xml$}) {
814: #
815: # Camtasia 8.1: express_show/spritesheet.png needed, and included in zip archive.
816: # Not referenced directly in <main>.html or <main>_player.html files,
817: # so add this file to %allow (where <main> is name user gave to file/archive).
818: #
819: my $spritesheet = $1.'express_show/spritesheet.png';
820: $allow{&absoluteurl($spritesheet,$target)}=1;
821: }
822: } elsif ($srctype eq 'PosterImageSrc') {
823: if ($url =~ m{^(.+)_First_Frame\.png$}) {
824: my $prefix = $1;
825: #
826: # Camtasia 8.1: <main>_Thumbnails.png needed, and included in zip archive.
827: # Not referenced directly in <main>.html or <main>_player.html files,
828: # so add this file to %allow (where <main> is name user gave to file/archive).
829: #
830: my $thumbnail = $prefix.'_Thumbnails.png';
831: $allow{&absoluteurl($thumbnail,$target)}=1;
832: }
833: }
834: }
835: }
836: }
837: }
838: }
839: $outstring .= $script
840: }
841: }
842: } elsif ($token->[0] eq 'E') {
843: if ($token->[2]) {
844: unless ($token->[1] eq 'allow') {
845: $outstring.='</'.$token->[1].'>';
846: }
847: }
848: if ((($token->[1] eq 'part') || ($token->[1] eq 'problem'))
849: && (!$responsecounter)) {
850: my $outstring='<span class="LC_error">'.&mt('Found [_1] without responses. This resource cannot be published.',$token->[1]).'</span>';
851: return ($outstring,1);
852: }
853: } else {
854: $outstring.=$token->[1];
855: }
856: }
857: pop(@parser);
858: }
859:
860: if ($needsfixup) {
861: print $logfile "End of ID and/or index fixup\n".
862: "Max ID : $maxid (min 10)\n".
863: "Max Index: $maxindex (min 10)\n";
864: } else {
865: print $logfile "Does not need ID and/or index fixup\n";
866: }
867:
868: return ($outstring,0,%allow);
869: }
870:
871: #########################################
872: #########################################
873:
874: =pod
875:
876: =item B<store_metadata>
877:
878: Store the metadata in the metadata table in the loncapa database.
879: Uses lonmysql to access the database.
880:
881: Inputs: \%metadata
882:
883: Returns: (error,status). error is undef on success, status is undef on error.
884:
885: =cut
886:
887: #########################################
888: #########################################
889: sub store_metadata {
890: my %metadata = @_;
891: my $error;
892: # Determine if the table exists
893: my $status = &Apache::lonmysql::check_table('metadata');
894: if (! defined($status)) {
895: $error='<span class="LC_error">'
896: .&mt('WARNING: Cannot connect to database!')
897: .'</span>';
898: &Apache::lonnet::logthis($error);
899: return ($error,undef);
900: }
901: if ($status == 0) {
902: # It would be nice to actually create the table....
903: $error ='<span class="LC_error">'
904: .&mt('WARNING: The metadata table does not exist in the LON-CAPA database!')
905: .'</span>';
906: &Apache::lonnet::logthis($error);
907: return ($error,undef);
908: }
909: my $dbh = &Apache::lonmysql::get_dbh();
910: if (($metadata{'obsolete'}) || ($metadata{'copyright'} eq 'priv')) {
911: # remove this entry
912: my $delitem = 'url = '.$dbh->quote($metadata{'url'});
913: $status = &LONCAPA::lonmetadata::delete_metadata($dbh,undef,$delitem);
914:
915: } else {
916: $status = &LONCAPA::lonmetadata::update_metadata($dbh,undef,undef,
917: \%metadata);
918: }
919: if (defined($status) && $status ne '') {
920: $error='<span class="LC_error">'
921: .&mt('Error occurred saving new values in metadata table in LON-CAPA database!')
922: .'</span>';
923: &Apache::lonnet::logthis($error);
924: &Apache::lonnet::logthis($status);
925: return ($error,undef);
926: }
927: return (undef,'success');
928: }
929:
930:
931: # ========================================== Parse file for errors and warnings
932:
933: sub checkonthis {
934: my ($r,$source)=@_;
935: my $uri=&Apache::lonnet::hreflocation($source);
936: $uri=~s/\/$//;
937: my $result=&Apache::lonnet::ssi_body($uri,
938: ('grade_target'=>'web',
939: 'return_only_error_and_warning_counts' => 1));
940: my ($errorcount,$warningcount)=split(':',$result);
941: if (($errorcount) || ($warningcount)) {
942: $r->print('<h3>'.&mt('Warnings and Errors').'</h3>');
943: $r->print('<tt>'.$uri.'</tt>:');
944: $r->print('<ul>');
945: if ($warningcount) {
946: $r->print('<li><div class="LC_warning">'
947: .&mt('[quant,_1,warning]',$warningcount)
948: .'</div></li>');
949: }
950: if ($errorcount) {
951: $r->print('<li><div class="LC_error">'
952: .&mt('[quant,_1,error]',$errorcount)
953: .' <img src="/adm/lonMisc/bomb.gif" />'
954: .'</div></li>');
955: }
956: $r->print('</ul>');
957: } else {
958: #$r->print('<font color="green">'.&mt('ok').'</font>');
959: }
960: $r->rflush();
961: return ($warningcount,$errorcount);
962: }
963:
964: # ============================================== Parse file itself for metadata
965: #
966: # parses a file with target meta, sets global %metadatafields %metadatakeys
967:
968: sub parseformeta {
969: my ($source,$style)=@_;
970: my $allmeta='';
971: if (($style eq 'ssi') || ($style eq 'prv')) {
972: my $dir=$source;
973: $dir=~s-/[^/]*$--;
974: my $file=$source;
975: $file=(split('/',$file))[-1];
976: $source=&Apache::lonnet::hreflocation($dir,$file);
977: $allmeta=&Apache::lonnet::ssi_body($source,('grade_target' => 'meta'));
978: &metaeval($allmeta);
979: }
980: return $allmeta;
981: }
982:
983: #########################################
984: #########################################
985:
986: =pod
987:
988: =item B<publish>
989:
990: This is the workhorse function of this module. This subroutine generates
991: backup copies, performs any automatic processing (prior to publication,
992: especially for rat and ssi files),
993:
994: Returns a 2 element array, the first is the string to be shown to the
995: user, the second is an error code, either 1 (an error occurred) or 0
996: (no error occurred)
997:
998: I<Additional documentation needed.>
999:
1000: =cut
1001:
1002: #########################################
1003: #########################################
1004: sub publish {
1005:
1006: my ($source,$target,$style,$batch)=@_;
1007: my $logfile;
1008: my $scrout='';
1009: my $allmeta='';
1010: my $content='';
1011: my %allow=();
1012:
1013: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1014: return ('<span class="LC_error">'.&mt('No write permission to user directory, FAIL').'</span>',1);
1015: }
1016: print $logfile
1017: "\n\n================= Publish ".localtime()." Phase One ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
1018:
1019: if (($style eq 'ssi') || ($style eq 'rat') || ($style eq 'prv')) {
1020: # ------------------------------------------------------- This needs processing
1021:
1022: # ----------------------------------------------------------------- Backup Copy
1023: my $copyfile=$source.'.save';
1024: if (copy($source,$copyfile)) {
1025: print $logfile "Copied original file to ".$copyfile."\n";
1026: } else {
1027: print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
1028: return ("<span class=\"LC_error\">".&mt("Failed to write backup copy, [_1], FAIL",$1)."</span>",1);
1029: }
1030: # ------------------------------------------------------------- IDs and indices
1031:
1032: my ($outstring,$error);
1033: ($outstring,$error,%allow)=&fix_ids_and_indices($logfile,$source,
1034: $target);
1035: if ($error) { return ($outstring,$error); }
1036: # ------------------------------------------------------------ Construct Allows
1037:
1038: my $outdep=''; # Collect dependencies output data
1039: my $allowstr='';
1040: foreach my $thisdep (sort(keys(%allow))) {
1041: if ($thisdep !~ /[^\s]/) { next; }
1042: if ($thisdep =~/\$/) {
1043: $outdep.='<div class="LC_warning">'
1044: .&mt('The resource depends on another resource with variable filename, i.e., [_1].','<tt>'.$thisdep.'</tt>').'<br />'
1045: .&mt('You likely need to explicitly allow access to all possible dependencies using the [_1]-tag.','<tt><allow></tt>')
1046: ."</div>\n";
1047: }
1048: unless ($style eq 'rat') {
1049: $allowstr.="\n".'<allow src="'.$thisdep.'" />';
1050: }
1051: $outdep.='<div>';
1052: if ($thisdep!~/[\*\$]/ && $thisdep!~m|^/adm/|) {
1053: $outdep.='<a href="'.$thisdep.'">';
1054: }
1055: $outdep.='<tt>'.$thisdep.'</tt>';
1056: if ($thisdep!~/[\*\$]/ && $thisdep!~m|^/adm/|) {
1057: $outdep.='</a>';
1058: if (
1059: &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
1060: $thisdep.'.meta') eq '-1') {
1061: $outdep.= ' - <span class="LC_error">'.&mt('Currently not available').
1062: '</span>';
1063: } else {
1064: #
1065: # Store the fact that the dependency has been used by the target file
1066: # Unfortunately, usage is erroneously named sequsage in lonmeta.pm
1067: # The translation happens in lonmetadata.pm
1068: #
1069: my %temphash=(&Apache::lonnet::declutter($target).'___'.
1070: &Apache::lonnet::declutter($thisdep).'___usage'
1071: => time);
1072: $thisdep=~m{^/res/($match_domain)/($match_username)/};
1073: if ((defined($1)) && (defined($2))) {
1074: &Apache::lonnet::put('nohist_resevaldata',\%temphash,
1075: $1,$2);
1076: }
1077: }
1078: }
1079: $outdep.='</div><br />';
1080: }
1081:
1082: if ($outdep) {
1083: $scrout.='<h3>'.&mt('Dependencies').'</h3>'
1084: .$outdep
1085: }
1086: $outstring=~s/\n*(\<\/[^\>]+\>[^<]*)$/$allowstr\n$1\n/s;
1087:
1088: # ------------------------------------------------------------- Write modified.
1089:
1090: {
1091: my $org;
1092: unless ($org=Apache::File->new('>'.$source)) {
1093: print $logfile "No write permit to $source\n";
1094: return ('<span class="LC_error">'.&mt('No write permission to').
1095: ' '.$source.
1096: ', '.&mt('FAIL').'</span>',1);
1097: }
1098: print($org $outstring);
1099: }
1100: $content=$outstring;
1101:
1102: }
1103: # -------------------------------------------- Initial step done, now metadata.
1104:
1105: # --------------------------------------- Storage for metadata keys and fields.
1106: # these are globals
1107: #
1108: %metadatafields=();
1109: %metadatakeys=();
1110:
1111: my %oldparmstores=();
1112:
1113: unless ($batch) {
1114: $scrout.='<h3>'.&mt('Metadata').' ' .
1115: &Apache::loncommon::help_open_topic("Metadata_Description")
1116: . '</h3>';
1117: }
1118:
1119: # ------------------------------------------------ First, check out environment
1120: if ((!(-e $source.'.meta')) || ($env{'form.forceoverride'})) {
1121: $metadatafields{'author'}=$env{'environment.firstname'}.' '.
1122: $env{'environment.middlename'}.' '.
1123: $env{'environment.lastname'}.' '.
1124: $env{'environment.generation'};
1125: $metadatafields{'author'}=~s/\s+/ /g;
1126: $metadatafields{'author'}=~s/\s+$//;
1127: $metadatafields{'owner'}=$cuname.':'.$cudom;
1128:
1129: # ------------------------------------------------ Check out directory hierachy
1130:
1131: my $thisdisfn=$source;
1132:
1133: $thisdisfn=~s/^\Q$docroot\E\/priv\/\Q$cudom\E\/\Q$cuname\E\///;
1134: my @urlparts=('.',split(/\//,$thisdisfn));
1135: $#urlparts--;
1136:
1137: my $currentpath=$docroot.'/priv/'.$cudom.'/'.$cuname.'/';
1138:
1139: my $prefix='../'x($#urlparts);
1140: foreach my $subdir (@urlparts) {
1141: $currentpath.=$subdir.'/';
1142: $scrout.=&metaread($logfile,$currentpath.'default.meta',$prefix);
1143: $prefix=~s|^\.\./||;
1144: }
1145:
1146: # ----------------------------------------------------------- Parse file itself
1147: # read %metadatafields from file itself
1148:
1149: $allmeta=&parseformeta($source,$style);
1150:
1151: # ------------------- Clear out parameters and stores (there should not be any)
1152:
1153: foreach (keys %metadatafields) {
1154: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1155: delete $metadatafields{$_};
1156: }
1157: }
1158:
1159: } else {
1160: # ---------------------- Read previous metafile, remember parameters and stores
1161:
1162: $scrout.=&metaread($logfile,$source.'.meta');
1163:
1164: foreach (keys %metadatafields) {
1165: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1166: $oldparmstores{$_}=1;
1167: delete $metadatafields{$_};
1168: }
1169: }
1170: # ------------------------------------------------------------- Save some stuff
1171: my %savemeta=();
1172: foreach ('title') {
1173: if ($metadatafields{$_}) { $savemeta{$_}=$metadatafields{$_}; }
1174: }
1175: # ------------------------------------------ See if anything new in file itself
1176:
1177: $allmeta=&parseformeta($source,$style);
1178: # ----------------------------------------------------------- Restore the stuff
1179: foreach (keys %savemeta) {
1180: $metadatafields{$_}=$savemeta{$_};
1181: }
1182: }
1183:
1184:
1185: # ---------------- Find and document discrepancies in the parameters and stores
1186:
1187: my $chparms='';
1188: foreach (sort keys %metadatafields) {
1189: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1190: unless ($_=~/\.\w+$/) {
1191: unless ($oldparmstores{$_}) {
1192: my $disp_key = $_;
1193: $disp_key =~ tr/\0/_/;
1194: print $logfile ('New: '.$disp_key."\n");
1195: $chparms .= $disp_key.' ';
1196: }
1197: }
1198: }
1199: }
1200: if ($chparms) {
1201: $scrout.='<p><b>'.&mt('New parameters or saved values').
1202: ':</b> '.$chparms.'</p>';
1203: }
1204:
1205: $chparms='';
1206: foreach (sort keys %oldparmstores) {
1207: if (($_=~/^parameter/) || ($_=~/^stores/)) {
1208: unless (($metadatafields{$_.'.name'}) ||
1209: ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
1210: my $disp_key = $_;
1211: $disp_key =~ tr/\0/_/;
1212: print $logfile ('Obsolete: '.$disp_key."\n");
1213: $chparms.=$disp_key.' ';
1214: }
1215: }
1216: }
1217: if ($chparms) {
1218: $scrout.='<p><b>'.&mt('Obsolete parameters or saved values').':</b> '
1219: .$chparms.'</p>'
1220: .'<p class="LC_warning"><b>'.&mt('Warning!').'</b><br />'
1221: .&mt('If this resource is in active use, student performance data from the previous version may become inaccessible.')
1222: .'</p><hr />';
1223: }
1224: if ($metadatafields{'copyright'} eq 'priv') {
1225: $scrout.='<p class="LC_warning"><b>'.&mt('Warning!').'</b><br />'
1226: .&mt('Copyright/distribution option "Private" is no longer supported. Select another option from below. Consider "Custom Rights" for maximum control over the usage of your resource.')
1227: .'</p><hr />';
1228: }
1229:
1230: # ------------------------------------------------------- Now have all metadata
1231:
1232: my %keywords=();
1233:
1234: if (length($content)<500000) {
1235: my $textonly=$content;
1236: $textonly=~s/\<script[^\<]+\<\/script\>//g;
1237: $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
1238: $textonly=~s/\<[^\>]*\>//g;
1239:
1240: #this is a work simplification for german authors for present
1241: $textonly=HTML::Entities::decode($textonly); #decode HTML-character
1242: $textonly=Encode::Encoder::encode('utf8', $textonly); #encode to perl internal unicode
1243: $textonly=~tr/A-ZÜÄÖ/a-züäö/; #add lowercase rule for german "Umlaute"
1244: $textonly=~s/[\$\&][a-z]\w*//g;
1245: $textonly=~s/[^a-z^ü^ä^ö^ß\s]//g; #dont delete german "Umlaute"
1246:
1247: foreach ($textonly=~m/[^\s]+/g) { #match all but whitespaces
1248: unless ($nokey{$_}) {
1249: $keywords{$_}=1;
1250: }
1251: }
1252:
1253:
1254: }
1255:
1256: foreach my $addkey (split(/[\"\'\,\;]/,$metadatafields{'keywords'})) {
1257: $addkey=~s/\s+/ /g;
1258: $addkey=~s/^\s//;
1259: $addkey=~s/\s$//;
1260: if ($addkey=~/\w/) {
1261: $keywords{$addkey}=1;
1262: }
1263: }
1264: # --------------------------------------------------- Now we also have keywords
1265: # =============================================================================
1266: # interactive mode html goes into $intr_scrout
1267: # batch mode throws away this HTML
1268: # additionally all of the field functions have a by product of setting
1269: # $env{'from.'..} so that it can be used by the phase two handler in
1270: # batch mode
1271:
1272: my $intr_scrout.='<br />'
1273: .'<form name="pubform" action="/adm/publish" method="post">';
1274: unless ($env{'form.makeobsolete'}) {
1275: $intr_scrout.='<p class="LC_warning">'
1276: .&mt('Searching for your resource will be based on the following metadata. Please provide as much data as possible.')
1277: .'</p>'
1278: .'<p><input type="submit" value="'
1279: .&mt('Finalize Publication')
1280: .'" /> <a href="'.&Apache::loncfile::url($source).'">'.&mt('Cancel').'</a></p>';
1281: }
1282: $intr_scrout.=&Apache::lonhtmlcommon::start_pick_box();
1283: $intr_scrout.=
1284: &hiddenfield('phase','two').
1285: &hiddenfield('filename',$env{'form.filename'}).
1286: &hiddenfield('allmeta',&escape($allmeta)).
1287: &hiddenfield('dependencies',join(',',keys %allow));
1288: unless ($env{'form.makeobsolete'}) {
1289: $intr_scrout.=
1290: &textfield('Title','title',$metadatafields{'title'}).
1291: &textfield('Author(s)','author',$metadatafields{'author'}).
1292: &textfield('Subject','subject',$metadatafields{'subject'});
1293: # --------------------------------------------------- Scan content for keywords
1294:
1295: my $keywords_help = &Apache::loncommon::help_open_topic("Publishing_Keywords");
1296: my $keywordout=<<"END";
1297: <script>
1298: function checkAll(field) {
1299: for (i = 0; i < field.length; i++)
1300: field[i].checked = true ;
1301: }
1302:
1303: function uncheckAll(field) {
1304: for (i = 0; i < field.length; i++)
1305: field[i].checked = false ;
1306: }
1307: </script>
1308: END
1309: $keywordout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Keywords'))
1310: .$keywords_help
1311: .'<input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.pubform.keywords)" />'
1312: .'<input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.pubform.keywords)" />'
1313: .'</p><br />'
1314: .&Apache::loncommon::start_data_table();
1315: my $cols_per_row = 10;
1316: my $colcount=0;
1317: my $wordcount=0;
1318: my $numkeywords = scalar(keys(%keywords));
1319:
1320: foreach my $word (sort(keys(%keywords))) {
1321: if ($colcount == 0) {
1322: $keywordout .= &Apache::loncommon::start_data_table_row();
1323: }
1324: $colcount++;
1325: $wordcount++;
1326: if (($wordcount == $numkeywords) && ($colcount < $cols_per_row)) {
1327: my $colspan = 1+$cols_per_row-$colcount;
1328: $keywordout .= '<td colspan="'.$colspan.'">';
1329: } else {
1330: $keywordout .= '<td>';
1331: }
1332: $keywordout.='<label><input type="checkbox" name="keywords" value="'.$word.'"';
1333: if ($metadatafields{'keywords'}) {
1334: if ($metadatafields{'keywords'}=~/\Q$word\E/) {
1335: $keywordout.=' checked="checked"';
1336: $env{'form.keywords'}.=$word.',';
1337: }
1338: } elsif (&Apache::loncommon::keyword($word)) {
1339: $keywordout.=' checked="checked"';
1340: $env{'form.keywords'}.=$word.',';
1341: }
1342: $keywordout.=' />'.$word.'</label></td>';
1343: if ($colcount == $cols_per_row) {
1344: $keywordout.=&Apache::loncommon::end_data_table_row();
1345: $colcount=0;
1346: }
1347: }
1348: if ($colcount > 0) {
1349: $keywordout .= &Apache::loncommon::end_data_table_row();
1350: }
1351:
1352: $env{'form.keywords'}=~s/\,$//;
1353:
1354: $keywordout.=&Apache::loncommon::end_data_table_row()
1355: .&Apache::loncommon::end_data_table()
1356: .&Apache::lonhtmlcommon::row_closure();
1357:
1358: $intr_scrout.=$keywordout;
1359:
1360: $intr_scrout.=&textfield('Additional Keywords','addkey','');
1361:
1362: $intr_scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
1363:
1364: $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Abstract'))
1365: .'<textarea cols="80" rows="5" name="abstract">'
1366: .$metadatafields{'abstract'}
1367: .'</textarea>'
1368: .&Apache::lonhtmlcommon::row_closure();
1369:
1370: $source=~/\.(\w+)$/;
1371:
1372: $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Grade Levels'))
1373: .&mt('Lowest Grade Level:').' '
1374: .&select_level_form($metadatafields{'lowestgradelevel'},'lowestgradelevel')
1375: # .&Apache::lonhtmlcommon::row_closure();
1376: # $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title(&mt('Highest Grade Level'))
1377: .' '.&mt('Highest Grade Level:').' '
1378: .&select_level_form($metadatafields{'highestgradelevel'},'highestgradelevel')
1379: .&Apache::lonhtmlcommon::row_closure();
1380:
1381: $intr_scrout.=&textfield('Standards','standards',$metadatafields{'standards'});
1382:
1383: $intr_scrout.=&hiddenfield('mime',$1);
1384:
1385: my $defaultlanguage=$metadatafields{'language'};
1386: $defaultlanguage =~ s/\s*notset\s*//g;
1387: $defaultlanguage =~ s/^,\s*//g;
1388: $defaultlanguage =~ s/,\s*$//g;
1389:
1390: $intr_scrout.=&selectbox('Language','language',
1391: $defaultlanguage,
1392: \&Apache::loncommon::languagedescription,
1393: (&Apache::loncommon::languageids),
1394: );
1395:
1396: unless ($metadatafields{'creationdate'}) {
1397: $metadatafields{'creationdate'}=time;
1398: }
1399: $intr_scrout.=&hiddenfield('creationdate',
1400: &Apache::lonmysql::unsqltime($metadatafields{'creationdate'}));
1401:
1402: $intr_scrout.=&hiddenfield('lastrevisiondate',time);
1403:
1404: my $pubowner_last;
1405: if ($style eq 'prv') {
1406: $pubowner_last = 1;
1407: }
1408: $intr_scrout.=&textfield('Publisher/Owner','owner',
1409: $metadatafields{'owner'},$pubowner_last);
1410:
1411: # ---------------------------------------------- Retrofix for unused copyright
1412: if ($metadatafields{'copyright'} eq 'free') {
1413: $metadatafields{'copyright'}='default';
1414: $metadatafields{'sourceavail'}='open';
1415: }
1416: if ($metadatafields{'copyright'} eq 'priv') {
1417: $metadatafields{'copyright'}='domain';
1418: }
1419: # ------------------------------------------------ Dial in reasonable defaults
1420: my $defaultoption=$metadatafields{'copyright'};
1421: unless ($defaultoption) { $defaultoption='default'; }
1422: my $defaultsourceoption=$metadatafields{'sourceavail'};
1423: unless ($defaultsourceoption) { $defaultsourceoption='closed'; }
1424: unless ($style eq 'prv') {
1425: # -------------------------------------------------- Correct copyright for rat.
1426: if ($style eq 'rat') {
1427: # -------------------------------------- Retrofix for non-applicable copyright
1428: if ($metadatafields{'copyright'} eq 'public') {
1429: delete $metadatafields{'copyright'};
1430: $defaultoption='default';
1431: }
1432: $intr_scrout.=&selectbox('Copyright/Distribution','copyright',
1433: $defaultoption,
1434: \&Apache::loncommon::copyrightdescription,
1435: (grep !/^(public|priv)$/,(&Apache::loncommon::copyrightids)));
1436: } else {
1437: $intr_scrout.=&selectbox('Copyright/Distribution','copyright',
1438: $defaultoption,
1439: \&Apache::loncommon::copyrightdescription,
1440: (grep !/^priv$/,(&Apache::loncommon::copyrightids)));
1441: }
1442: my $copyright_help =
1443: &Apache::loncommon::help_open_topic('Publishing_Copyright');
1444: my $replace=&mt('Copyright/Distribution:');
1445: $intr_scrout =~ s/$replace/$replace.' '.$copyright_help/ge;
1446:
1447: $intr_scrout.=&text_with_browse_field('Custom Distribution File','customdistributionfile',$metadatafields{'customdistributionfile'},'rights');
1448: $intr_scrout.=&selectbox('Source Distribution','sourceavail',
1449: $defaultsourceoption,
1450: \&Apache::loncommon::source_copyrightdescription,
1451: (&Apache::loncommon::source_copyrightids));
1452: # $intr_scrout.=&text_with_browse_field('Source Custom Distribution File','sourcerights',$metadatafields{'sourcerights'},'rights');
1453: my $uctitle=&mt('Obsolete');
1454: my $obsolete_checked=($metadatafields{'obsolete'})?' checked="checked"':'';
1455: $intr_scrout.="\n".&Apache::lonhtmlcommon::row_title($uctitle)
1456: .'<input type="checkbox" name="obsolete"'.$obsolete_checked.' />'
1457: .&Apache::lonhtmlcommon::row_closure(1);
1458: $intr_scrout.=&text_with_browse_field('Suggested Replacement for Obsolete File',
1459: 'obsoletereplacement',
1460: $metadatafields{'obsoletereplacement'},'',1);
1461: } else {
1462: $intr_scrout.=&hiddenfield('copyright','private');
1463: }
1464: } else {
1465: $intr_scrout.=
1466: &hiddenfield('title',$metadatafields{'title'}).
1467: &hiddenfield('author',$metadatafields{'author'}).
1468: &hiddenfield('subject',$metadatafields{'subject'}).
1469: &hiddenfield('keywords',$metadatafields{'keywords'}).
1470: &hiddenfield('abstract',$metadatafields{'abstract'}).
1471: &hiddenfield('notes',$metadatafields{'notes'}).
1472: &hiddenfield('mime',$metadatafields{'mime'}).
1473: &hiddenfield('creationdate',$metadatafields{'creationdate'}).
1474: &hiddenfield('lastrevisiondate',time).
1475: &hiddenfield('owner',$metadatafields{'owner'}).
1476: &hiddenfield('lowestgradelevel',$metadatafields{'lowestgradelevel'}).
1477: &hiddenfield('standards',$metadatafields{'standards'}).
1478: &hiddenfield('highestgradelevel',$metadatafields{'highestgradelevel'}).
1479: &hiddenfield('language',$metadatafields{'language'}).
1480: &hiddenfield('copyright',$metadatafields{'copyright'}).
1481: &hiddenfield('sourceavail',$metadatafields{'sourceavail'}).
1482: &hiddenfield('customdistributionfile',$metadatafields{'customdistributionfile'}).
1483: &hiddenfield('obsolete',1).
1484: &text_with_browse_field('Suggested Replacement for Obsolete File',
1485: 'obsoletereplacement',
1486: $metadatafields{'obsoletereplacement'},'',1);
1487: }
1488: if (!$batch) {
1489: $scrout.=$intr_scrout
1490: .&Apache::lonhtmlcommon::end_pick_box()
1491: .'<p><input type="submit" value="'
1492: .&mt($env{'form.makeobsolete'}?'Make Obsolete':'Finalize Publication')
1493: .'" /></p>'
1494: .'</form>';
1495: }
1496: return($scrout,0);
1497: }
1498:
1499: #########################################
1500: #########################################
1501:
1502: =pod
1503:
1504: =item B<phasetwo>
1505:
1506: Render second interface showing status of publication steps.
1507: This is publication step two.
1508:
1509: Parameters:
1510:
1511: =over 4
1512:
1513: =item I<$source>
1514:
1515: =item I<$target>
1516:
1517: =item I<$style>
1518:
1519: =item I<$distarget>
1520:
1521: =back
1522:
1523: Returns:
1524:
1525: =over 4
1526:
1527: =item integer
1528:
1529: 0: fail
1530: 1: success
1531:
1532: =back
1533:
1534: =cut
1535:
1536: #'stupid emacs
1537: #########################################
1538: #########################################
1539: sub phasetwo {
1540:
1541: my ($r,$source,$target,$style,$distarget,$batch)=@_;
1542: $source=~s/\/+/\//g;
1543: $target=~s/\/+/\//g;
1544: #
1545: # Unless trying to get rid of something, check name validity
1546: #
1547: unless ($env{'form.obsolete'}) {
1548: if ($target=~/(\_\_\_|\&\&\&|\:\:\:)/) {
1549: $r->print('<span class="LC_error">'.
1550: &mt('Unsupported character combination [_1] in filename, FAIL.',"<tt>'.$1.'</tt>").
1551: '</span>');
1552: return 0;
1553: }
1554: unless ($target=~/\.(\w+)$/) {
1555: $r->print('<span class="LC_error">'.&mt('No valid extension found in filename, FAIL').'</span>');
1556: return 0;
1557: }
1558: if ($target=~/\.(\d+)\.(\w+)$/) {
1559: $r->print('<span class="LC_error">'.&mt('Filename of resource contains internal version number. Cannot publish such resources, FAIL').'</span>');
1560: return 0;
1561: }
1562: }
1563:
1564: #
1565: # End name check
1566: #
1567: $distarget=~s/\/+/\//g;
1568: my $logfile;
1569: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
1570: $r->print(
1571: '<span class="LC_error">'.
1572: &mt('No write permission to user directory, FAIL').'</span>');
1573: return 0;
1574: }
1575:
1576: if ($source =~ /\.rights$/) {
1577: $r->print('<p><span class="LC_warning">'.&mt('Warning: It can take up to 1 hour for rights changes to fully propagate.').'</span></p>');
1578: }
1579:
1580: print $logfile
1581: "\n================= Publish ".localtime()." Phase Two ================\n".$env{'user.name'}.':'.$env{'user.domain'}."\n";
1582:
1583: %metadatafields=();
1584: %metadatakeys=();
1585:
1586: &metaeval(&unescape($env{'form.allmeta'}));
1587:
1588: $metadatafields{'title'}=$env{'form.title'};
1589: $metadatafields{'author'}=$env{'form.author'};
1590: $metadatafields{'subject'}=$env{'form.subject'};
1591: $metadatafields{'notes'}=$env{'form.notes'};
1592: $metadatafields{'abstract'}=$env{'form.abstract'};
1593: $metadatafields{'mime'}=$env{'form.mime'};
1594: $metadatafields{'language'}=$env{'form.language'};
1595: $metadatafields{'creationdate'}=$env{'form.creationdate'};
1596: $metadatafields{'lastrevisiondate'}=$env{'form.lastrevisiondate'};
1597: $metadatafields{'owner'}=$env{'form.owner'};
1598: $metadatafields{'copyright'}=$env{'form.copyright'};
1599: $metadatafields{'standards'}=$env{'form.standards'};
1600: $metadatafields{'lowestgradelevel'}=$env{'form.lowestgradelevel'};
1601: $metadatafields{'highestgradelevel'}=$env{'form.highestgradelevel'};
1602: $metadatafields{'customdistributionfile'}=
1603: $env{'form.customdistributionfile'};
1604: $metadatafields{'sourceavail'}=$env{'form.sourceavail'};
1605: $metadatafields{'obsolete'}=$env{'form.obsolete'};
1606: $metadatafields{'obsoletereplacement'}=
1607: $env{'form.obsoletereplacement'};
1608: $metadatafields{'dependencies'}=$env{'form.dependencies'};
1609: $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
1610: $env{'user.domain'};
1611: $metadatafields{'authorspace'}=$cuname.':'.$cudom;
1612: $metadatafields{'domain'}=$cudom;
1613:
1614: my $allkeywords=$env{'form.addkey'};
1615: if (exists($env{'form.keywords'})) {
1616: if (ref($env{'form.keywords'})) {
1617: $allkeywords .= ','.join(',',@{$env{'form.keywords'}});
1618: } else {
1619: $allkeywords .= ','.$env{'form.keywords'};
1620: }
1621: }
1622: $allkeywords=~s/[\"\']//g;
1623: $allkeywords=~s/\s*[\;\,]\s*/\,/g;
1624: $allkeywords=~s/\s+/ /g;
1625: $allkeywords=~s/^[ \,]//;
1626: $allkeywords=~s/[ \,]$//;
1627: $metadatafields{'keywords'}=$allkeywords;
1628:
1629: # check if custom distribution file is specified
1630: if ($metadatafields{'copyright'} eq 'custom') {
1631: my $file=$metadatafields{'customdistributionfile'};
1632: unless ($file=~/\.rights$/) {
1633: $r->print(
1634: '<span class="LC_error">'.&mt('No valid custom distribution rights file specified, FAIL').
1635: '</span>');
1636: return 0;
1637: }
1638: }
1639: {
1640: print $logfile "\nWrite metadata file for ".$source;
1641: my $mfh;
1642: unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
1643: $r->print(
1644: '<span class="LC_error">'.&mt('Could not write metadata, FAIL').
1645: '</span>');
1646: return 0;
1647: }
1648: foreach (sort keys %metadatafields) {
1649: unless ($_=~/\./) {
1650: my $unikey=$_;
1651: $unikey=~/^([A-Za-z]+)/;
1652: my $tag=$1;
1653: $tag=~tr/A-Z/a-z/;
1654: print $mfh "\n\<$tag";
1655: foreach (split(/\,/,$metadatakeys{$unikey})) {
1656: my $value=$metadatafields{$unikey.'.'.$_};
1657: $value=~s/\"/\'\'/g;
1658: print $mfh ' '.$_.'="'.$value.'"';
1659: }
1660: print $mfh '>'.
1661: &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
1662: .'</'.$tag.'>';
1663: }
1664: }
1665: $r->print('<p>'.&mt('Wrote Metadata').'</p>');
1666: print $logfile "\nWrote metadata";
1667: }
1668:
1669: # -------------------------------- Synchronize entry with SQL metadata database
1670:
1671: $metadatafields{'url'} = $distarget;
1672: $metadatafields{'version'} = 'current';
1673:
1674: my ($error,$success) = &store_metadata(%metadatafields);
1675: if ($success) {
1676: $r->print('<p>'.&mt('Synchronized SQL metadata database').'</p>');
1677: print $logfile "\nSynchronized SQL metadata database";
1678: } else {
1679: $r->print($error);
1680: print $logfile "\n".$error;
1681: }
1682: # --------------------------------------------- Delete author resource messages
1683: my $delresult=&Apache::lonmsg::del_url_author_res_msg($target);
1684: $r->print('<p>'.&mt('Removing error messages:').' '.$delresult.'</p>');
1685: print $logfile "\nRemoving error messages: $delresult";
1686: # ----------------------------------------------------------- Copy old versions
1687:
1688: if (-e $target) {
1689: my $filename;
1690: my $maxversion=0;
1691: $target=~/(.*)\/([^\/]+)\.(\w+)$/;
1692: my $srcf=$2;
1693: my $srct=$3;
1694: my $srcd=$1;
1695: my $docroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1696: unless ($srcd=~/^\Q$docroot\E\/res/) {
1697: print $logfile "\nPANIC: Target dir is ".$srcd;
1698: $r->print(
1699: "<span class=\"LC_error\">".&mt('Invalid target directory, FAIL')."</span>");
1700: return 0;
1701: }
1702: opendir(DIR,$srcd);
1703: while ($filename=readdir(DIR)) {
1704: if (-l $srcd.'/'.$filename) {
1705: unlink($srcd.'/'.$filename);
1706: unlink($srcd.'/'.$filename.'.meta');
1707: } else {
1708: if ($filename=~/^\Q$srcf\E\.(\d+)\.\Q$srct\E$/) {
1709: $maxversion=($1>$maxversion)?$1:$maxversion;
1710: }
1711: }
1712: }
1713: closedir(DIR);
1714: $maxversion++;
1715: $r->print('<p>'.&mt('Creating old version [_1]',$maxversion).'</p>');
1716: print $logfile "\nCreating old version ".$maxversion."\n";
1717:
1718: my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
1719:
1720: if (copy($target,$copyfile)) {
1721: print $logfile "Copied old target to ".$copyfile."\n";
1722: $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied old target file')));
1723: } else {
1724: print $logfile "Unable to write ".$copyfile.':'.$!."\n";
1725: $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Failed to copy old target').", $!",1));
1726: return 0;
1727: }
1728:
1729: # --------------------------------------------------------------- Copy Metadata
1730:
1731: $copyfile=$copyfile.'.meta';
1732:
1733: if (copy($target.'.meta',$copyfile)) {
1734: print $logfile "Copied old target metadata to ".$copyfile."\n";
1735: $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied old metadata')));
1736: } else {
1737: print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1738: if (-e $target.'.meta') {
1739: $r->print(&Apache::lonhtmlcommon::confirm_success(
1740: &mt('Failed to write old metadata copy').", $!",1));
1741: return 0;
1742: }
1743: }
1744:
1745:
1746: } else {
1747: $r->print('<p>'.&mt('Initial version').'</p>');
1748: print $logfile "\nInitial version";
1749: }
1750:
1751: # ---------------------------------------------------------------- Write Source
1752: my $copyfile=$target;
1753:
1754: my @parts=split(/\//,$copyfile);
1755: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1756:
1757: my $count;
1758: for ($count=5;$count<$#parts;$count++) {
1759: $path.="/$parts[$count]";
1760: if ((-e $path)!=1) {
1761: print $logfile "\nCreating directory ".$path;
1762: mkdir($path,0777);
1763: $r->print('<p>'
1764: .&mt('Created directory [_1]'
1765: ,'<span class="LC_filename">'.$parts[$count].'</span>')
1766: .'</p>'
1767: );
1768: }
1769: }
1770:
1771: if (copy($source,$copyfile)) {
1772: print $logfile "\nCopied original source to ".$copyfile."\n";
1773: $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied source file')));
1774: } else {
1775: print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
1776: $r->print(&Apache::lonhtmlcommon::confirm_success(
1777: &mt('Failed to copy source').", $!",1));
1778: return 0;
1779: }
1780:
1781: # ---------------------------------------------- Delete local tmp-preview files
1782: unlink($copyfile.'.tmp');
1783: # --------------------------------------------------------------- Copy Metadata
1784:
1785: $copyfile=$copyfile.'.meta';
1786:
1787: if (copy($source.'.meta',$copyfile)) {
1788: print $logfile "\nCopied original metadata to ".$copyfile."\n";
1789: $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Copied metadata')));
1790: } else {
1791: print $logfile "\nUnable to write metadata ".$copyfile.':'.$!."\n";
1792: $r->print(&Apache::lonhtmlcommon::confirm_success(
1793: &mt('Failed to write metadata copy').", $!",1));
1794: return 0;
1795: }
1796: $r->rflush;
1797:
1798: # ------------------------------------------------------------- Trigger updates
1799: push(@{$modified_urls},[$target,$source]);
1800: unless ($registered_cleanup) {
1801: my $handlers = $r->get_handlers('PerlCleanupHandler');
1802: $r->set_handlers('PerlCleanupHandler' => [\¬ify,@{$handlers}]);
1803: $registered_cleanup=1;
1804: }
1805:
1806: # ---------------------------------------------------------- Clear local caches
1807: my $thisdistarget=$target;
1808: $thisdistarget=~s/^\Q$docroot\E//;
1809: &Apache::lonnet::devalidate_cache_new('resversion',$target);
1810: &Apache::lonnet::devalidate_cache_new('meta',
1811: &Apache::lonnet::declutter($thisdistarget));
1812:
1813: # ------------------------------------------------------------- Everything done
1814: $logfile->close();
1815: $r->print('<p class="LC_success">'.&mt('Done').'</p>');
1816:
1817: # ------------------------------------------------ Provide link to new resource
1818: unless ($batch) {
1819:
1820: my $thissrc=&Apache::loncfile::url($source);
1821: my $thissrcdir=$thissrc;
1822: $thissrcdir=~s/\/[^\/]+$/\//;
1823:
1824: $r->print(
1825: &Apache::lonhtmlcommon::actionbox([
1826: '<a href="'.$thisdistarget.'">'.
1827: &mt('View Published Version').
1828: '</a>',
1829: '<a href="'.$thissrc.'">'.
1830: &mt('Back to Source').
1831: '</a>',
1832: '<a href="'.$thissrcdir.'">'.
1833: &mt('Back to Source Directory').
1834: '</a>'])
1835: );
1836: }
1837: return 1;
1838: }
1839:
1840: # =============================================================== Notifications
1841: sub notify {
1842: # --------------------------------------------------- Send update notifications
1843: foreach my $targetsource (@{$modified_urls}){
1844: my ($target,$source)=@{$targetsource};
1845: my $logfile=Apache::File->new('>>'.$source.'.log');
1846: print $logfile "\nCleanup phase: Notifications\n";
1847: my @subscribed=&get_subscribed_hosts($target);
1848: foreach my $subhost (@subscribed) {
1849: print $logfile "\nNotifying host ".$subhost.':';
1850: my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
1851: print $logfile $reply;
1852: }
1853: # ---------------------------------------- Send update notifications, meta only
1854: my @subscribedmeta=&get_subscribed_hosts("$target.meta");
1855: foreach my $subhost (@subscribedmeta) {
1856: print $logfile "\nNotifying host for metadata only ".$subhost.':';
1857: my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
1858: $subhost);
1859: print $logfile $reply;
1860: }
1861: # --------------------------------------------------- Notify subscribed courses
1862: my %courses=&coursedependencies($target);
1863: my $now=time;
1864: foreach (keys %courses) {
1865: print $logfile "\nNotifying course ".$_.':';
1866: my ($cdom,$cname)=split(/\_/,$_);
1867: my $reply=&Apache::lonnet::cput
1868: ('versionupdate',{$target => $now},$cdom,$cname);
1869: print $logfile $reply;
1870: }
1871: print $logfile "\n============ Done ============\n";
1872: $logfile->close();
1873: }
1874: if ($lock) { &Apache::lonnet::remove_lock($lock); }
1875: return OK;
1876: }
1877:
1878: #########################################
1879:
1880: sub batchpublish {
1881: my ($r,$srcfile,$targetfile)=@_;
1882: #publication pollutes %env with form.* values
1883: my %oldenv=%env;
1884: $srcfile=~s/\/+/\//g;
1885: $targetfile=~s/\/+/\//g;
1886: $srcfile=~s/\/+/\//g;
1887:
1888: my $docroot=$r->dir_config('lonDocRoot');
1889: my $thisdistarget=$targetfile;
1890: $thisdistarget=~s/^\Q$docroot\E//;
1891:
1892:
1893: %metadatafields=();
1894: %metadatakeys=();
1895: $srcfile=~/\.(\w+)$/;
1896: my $thistype=$1;
1897:
1898:
1899: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1900:
1901: $r->print('<h2>'
1902: .&mt('Publishing [_1]',&Apache::loncfile::display($srcfile))
1903: .'</h2>'
1904: );
1905:
1906: # phase one takes
1907: # my ($source,$target,$style,$batch)=@_;
1908: my ($outstring,$error)=&publish($srcfile,$targetfile,$thisembstyle,1);
1909: $r->print('<p>'.$outstring.'</p>');
1910: # phase two takes
1911: # my ($source,$target,$style,$distarget,batch)=@_;
1912: # $env{'form.allmeta'},$env{'form.title'},$env{'form.author'},...
1913: if (!$error) {
1914: $r->print('<p>');
1915: &phasetwo($r,$srcfile,$targetfile,$thisembstyle,$thisdistarget,1);
1916: $r->print('</p>');
1917: }
1918: %env=%oldenv;
1919: return '';
1920: }
1921:
1922: #########################################
1923:
1924: sub publishdirectory {
1925: my ($r,$fn,$thisdisfn)=@_;
1926: $fn=~s/\/+/\//g;
1927: $thisdisfn=~s/\/+/\//g;
1928: my $thisdisresdir=$thisdisfn;
1929: $thisdisresdir=~s/^\/priv\//\/res\//;
1930: my $resdir = $r->dir_config('lonDocRoot').$thisdisresdir;
1931: $r->print('<form name="pubdirpref" method="post" action="">'
1932: .&Apache::lonhtmlcommon::start_pick_box()
1933: .&Apache::lonhtmlcommon::row_title(&mt('Directory'))
1934: .'<span class="LC_filename">'.$thisdisfn.'</span>'
1935: .&Apache::lonhtmlcommon::row_closure()
1936: .&Apache::lonhtmlcommon::row_title(&mt('Target'))
1937: .'<span class="LC_filename">'.$thisdisresdir.'</span>'
1938: );
1939:
1940: my $dirptr=16384; # Mask indicating a directory in stat.cmode.
1941: unless ($env{'form.phase'} eq 'two') {
1942: # ask user what they want
1943: $r->print(&Apache::lonhtmlcommon::row_closure()
1944: .&Apache::lonhtmlcommon::row_title(&mt('Options'))
1945: );
1946: $r->print(&hiddenfield('phase','two').
1947: &hiddenfield('filename',$env{'form.filename'}).
1948: &checkbox('pubrec','include subdirectories').
1949: &checkbox('forcerepub','force republication of previously published files').
1950: &checkbox('obsolete','make file(s) obsolete').
1951: &checkbox('forceoverride','force directory level metadata over existing')
1952: );
1953: $r->print(&Apache::lonhtmlcommon::row_closure(1)
1954: .&Apache::lonhtmlcommon::end_pick_box()
1955: .'<br /><input type="submit" value="'.&mt('Publish Directory').'" /></form>'
1956: );
1957: $lock=0;
1958: } else {
1959: $r->print(&Apache::lonhtmlcommon::row_closure(1)
1960: .&Apache::lonhtmlcommon::end_pick_box()
1961: );
1962: unless ($lock) { $lock=&Apache::lonnet::set_lock(&mt('Publishing [_1]',$fn)); }
1963: # actually publish things
1964: opendir(DIR,$fn);
1965: my @files=sort(readdir(DIR));
1966: foreach my $filename (@files) {
1967: my ($cdev,$cino,$cmode,$cnlink,
1968: $cuid,$cgid,$crdev,$csize,
1969: $catime,$cmtime,$cctime,
1970: $cblksize,$cblocks)=stat($fn.'/'.$filename);
1971:
1972: my $extension='';
1973: if ($filename=~/\.(\w+)$/) { $extension=$1; }
1974: if ($cmode&$dirptr) {
1975: if (($filename!~/^\./) && ($env{'form.pubrec'})) {
1976: &publishdirectory($r,$fn.'/'.$filename,$thisdisfn.'/'.$filename);
1977: }
1978: } elsif ((&Apache::loncommon::fileembstyle($extension) ne 'hdn') &&
1979: ($filename!~/^[\#\.]/) && ($filename!~/\~$/)) {
1980: # find out publication status and/or exiting metadata
1981: my $publishthis=0;
1982: if (-e $resdir.'/'.$filename) {
1983: my ($rdev,$rino,$rmode,$rnlink,
1984: $ruid,$rgid,$rrdev,$rsize,
1985: $ratime,$rmtime,$rctime,
1986: $rblksize,$rblocks)=stat($resdir.'/'.$filename);
1987: if (($rmtime<$cmtime) || ($env{'form.forcerepub'})) {
1988: # previously published, modified now
1989: $publishthis=1;
1990: }
1991: my $meta_cmtime = (stat($fn.'/'.$filename.'.meta'))[9];
1992: my $meta_rmtime = (stat($resdir.'/'.$filename.'.meta'))[9];
1993: if ( $meta_rmtime<$meta_cmtime ) {
1994: $publishthis=1;
1995: }
1996: } else {
1997: # never published
1998: $publishthis=1;
1999: }
2000:
2001: if ($publishthis) {
2002: &batchpublish($r,$fn.'/'.$filename,$resdir.'/'.$filename);
2003: } else {
2004: $r->print('<br />'.&mt('Skipping').' '.$filename.'<br />');
2005: }
2006: $r->rflush();
2007: }
2008: }
2009: closedir(DIR);
2010: }
2011: }
2012:
2013: #########################################
2014: # publish a default.meta file
2015:
2016: sub defaultmetapublish {
2017: my ($r,$fn,$cuname,$cudom)=@_;
2018: unless (-e $fn) {
2019: return HTTP_NOT_FOUND;
2020: }
2021: my $target=$fn;
2022: $target=~s/^\Q$Apache::lonnet::perlvar{'lonDocRoot'}\E\/priv\//\Q$Apache::lonnet::perlvar{'lonDocRoot'}\E\/res\//;
2023:
2024:
2025: &Apache::loncommon::content_type($r,'text/html');
2026: $r->send_http_header;
2027:
2028: $r->print(&Apache::loncommon::start_page('Metadata Publication'));
2029:
2030: # ---------------------------------------------------------------- Write Source
2031: my $copyfile=$target;
2032:
2033: my @parts=split(/\//,$copyfile);
2034: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2035:
2036: my $count;
2037: for ($count=5;$count<$#parts;$count++) {
2038: $path.="/$parts[$count]";
2039: if ((-e $path)!=1) {
2040: mkdir($path,0777);
2041: $r->print('<p>'
2042: .&mt('Created directory [_1]'
2043: ,'<span class="LC_filename">'.$parts[$count].'</span>')
2044: .'</p>'
2045: );
2046: }
2047: }
2048:
2049: if (copy($fn,$copyfile)) {
2050: $r->print('<p>'.&mt('Copied source file').'</p>');
2051: } else {
2052: return "<span class=\"LC_error\">".
2053: &mt('Failed to copy source').", $!, ".&mt('FAIL')."</span>";
2054: }
2055:
2056: # --------------------------------------------------- Send update notifications
2057:
2058: my @subscribed=&get_subscribed_hosts($target);
2059: foreach my $subhost (@subscribed) {
2060: $r->print('<p>'.&mt('Notifying host').' '.$subhost.':');$r->rflush;
2061: my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
2062: $r->print($reply.'</p><br />');$r->rflush;
2063: }
2064: # ------------------------------------------------------------------- Link back
2065: $r->print("<a href='".&Apache::loncfile::display($fn)."'>".&mt('Back to Metadata').'</a>');
2066: $r->print(&Apache::loncommon::end_page());
2067: return OK;
2068: }
2069: #########################################
2070:
2071: =pod
2072:
2073: =item B<handler>
2074:
2075: A basic outline of the handler subroutine follows.
2076:
2077: =over 4
2078:
2079: =item *
2080:
2081: Get query string for limited number of parameters.
2082:
2083: =item *
2084:
2085: Check filename.
2086:
2087: =item *
2088:
2089: File is there and owned, init lookup tables.
2090:
2091: =item *
2092:
2093: Start page output.
2094:
2095: =item *
2096:
2097: Evaluate individual file, and then output information.
2098:
2099: =item *
2100:
2101: Publishing from $thisfn to $thistarget with $thisembstyle.
2102:
2103: =back
2104:
2105: =cut
2106:
2107: #########################################
2108: #########################################
2109: sub handler {
2110: my $r=shift;
2111:
2112: if ($r->header_only) {
2113: &Apache::loncommon::content_type($r,'text/html');
2114: $r->send_http_header;
2115: return OK;
2116: }
2117:
2118: # Get query string for limited number of parameters
2119:
2120: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
2121: ['filename']);
2122:
2123: # -------------------------------------- Flag and buffer for registered cleanup
2124: $registered_cleanup=0;
2125: @{$modified_urls}=();
2126: # -------------------------------------------------------------- Check filename
2127:
2128: my $fn=&unescape($env{'form.filename'});
2129: ($cuname,$cudom)=&Apache::lonnet::constructaccess($fn);
2130: # ----------------------------------------------------- Do we have permissions?
2131: unless (($cuname) && ($cudom)) {
2132: $r->log_reason($env{'user.name'}.' at '.$env{'user.domain'}.
2133: ' trying to publish file '.$env{'form.filename'}.
2134: ' - not authorized',
2135: $r->filename);
2136: return HTTP_NOT_ACCEPTABLE;
2137: }
2138: # ----------------------------------------------------------------- Get docroot
2139: $docroot=$r->dir_config('lonDocRoot');
2140:
2141:
2142: # special publication: default.meta file
2143: if ($fn=~/\/default.meta$/) {
2144: return &defaultmetapublish($r,$fn,$cuname,$cudom);
2145: }
2146: $fn=~s/\.meta$//;
2147:
2148: # sanity test on the filename
2149:
2150: unless ($fn) {
2151: $r->log_reason($cuname.' at '.$cudom.
2152: ' trying to publish empty filename', $r->filename);
2153: return HTTP_NOT_FOUND;
2154: }
2155:
2156: unless (-e $docroot.$fn) {
2157: $r->log_reason($cuname.' at '.$cudom.
2158: ' trying to publish non-existing file '.
2159: $env{'form.filename'}.' ('.$fn.')',
2160: $r->filename);
2161: return HTTP_NOT_FOUND;
2162: }
2163:
2164: # -------------------------------- File is there and owned, init lookup tables.
2165:
2166: %addid=();
2167:
2168: {
2169: my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
2170: while (<$fh>=~/(\w+)\s+(\w+)/) {
2171: $addid{$1}=$2;
2172: }
2173: }
2174:
2175: %nokey=();
2176:
2177: {
2178: my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
2179: while (<$fh>) {
2180: my $word=$_;
2181: chomp($word);
2182: $nokey{$word}=1;
2183: }
2184: }
2185:
2186: # ---------------------------------------------------------- Start page output.
2187:
2188: &Apache::loncommon::content_type($r,'text/html');
2189: $r->send_http_header;
2190:
2191: # Breadcrumbs
2192: &Apache::lonhtmlcommon::clear_breadcrumbs();
2193: &Apache::lonhtmlcommon::add_breadcrumb({
2194: 'text' => 'Authoring Space',
2195: 'href' => &Apache::loncommon::authorspace($fn),
2196: });
2197: &Apache::lonhtmlcommon::add_breadcrumb({
2198: 'text' => 'Resource Publication',
2199: 'href' => '',
2200: });
2201:
2202: my $js='<script type="text/javascript">'.
2203: &Apache::loncommon::browser_and_searcher_javascript().
2204: '</script>';
2205: $r->print(&Apache::loncommon::start_page('Resource Publication',$js)
2206: .&Apache::lonhtmlcommon::breadcrumbs()
2207: .&Apache::loncommon::head_subbox(
2208: &Apache::loncommon::CSTR_pageheader($docroot.$fn))
2209: );
2210:
2211: my $thisdisfn=&HTML::Entities::encode($fn,'<>&"');
2212: my $thistarget=$fn;
2213: $thistarget=~s/^\/priv\//\/res\//;
2214: my $thisdistarget=&HTML::Entities::encode($thistarget,'<>&"');
2215:
2216: if ($fn=~/\/$/) {
2217: # -------------------------------------------------------- This is a directory
2218: &publishdirectory($r,$docroot.$fn,$thisdisfn);
2219: $r->print(
2220: '<br /><br />'.
2221: &Apache::lonhtmlcommon::actionbox([
2222: '<a href="'.$thisdisfn.'">'.&mt('Return to Directory').'</a>']));
2223: } else {
2224: # ---------------------- Evaluate individual file, and then output information.
2225: $fn=~/\.(\w+)$/;
2226: my $thistype=$1;
2227: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
2228: if ($thistype eq 'page') { $thisembstyle = 'rat'; }
2229:
2230: $r->print('<h2>'
2231: .&mt('Publishing [_1]'
2232: ,'<span class="LC_filename">'.$thisdisfn.'</span>')
2233: .'</h2>'
2234: );
2235:
2236: $r->print('<h3>'.&mt('Resource Details').'</h3>');
2237:
2238: $r->print(&Apache::lonhtmlcommon::start_pick_box());
2239:
2240: $r->print(&Apache::lonhtmlcommon::row_title(&mt('Type'))
2241: .&Apache::loncommon::filedescription($thistype)
2242: .&Apache::lonhtmlcommon::row_closure()
2243: );
2244:
2245: $r->print(&Apache::lonhtmlcommon::row_title(&mt('Link to Resource'))
2246: .'<tt>'
2247: );
2248: $r->print(<<ENDCAPTION);
2249: <a href='javascript:void(window.open("$thisdisfn","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
2250: $thisdisfn</a>
2251: ENDCAPTION
2252: $r->print('</tt>'
2253: .&Apache::lonhtmlcommon::row_closure()
2254: );
2255:
2256: $r->print(&Apache::lonhtmlcommon::row_title(&mt('Target'))
2257: .'<tt>'.$thisdistarget.'</tt>'
2258: );
2259: if (($cuname ne $env{'user.name'})||($cudom ne $env{'user.domain'})) {
2260: $r->print(&Apache::lonhtmlcommon::row_closure()
2261: .&Apache::lonhtmlcommon::row_title(&mt('Co-Author'))
2262: .'<span class="LC_warning">'
2263: .&Apache::loncommon::plainname($cuname,$cudom) .' ('.$cuname.':'.$cudom.')'
2264: .'</span>'
2265: );
2266: }
2267:
2268: if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
2269: $r->print(&Apache::lonhtmlcommon::row_closure()
2270: .&Apache::lonhtmlcommon::row_title(&mt('Diffs')));
2271: $r->print(<<ENDDIFF);
2272: <a href='javascript:void(window.open("/adm/diff?filename=$thisdisfn&versiontwo=priv","cat","height=300,width=500,scrollbars=1,resizable=1,menubar=0,location=1"))'>
2273: ENDDIFF
2274: $r->print(&mt('Diffs with Current Version').'</a>');
2275: }
2276:
2277: $r->print(&Apache::lonhtmlcommon::row_closure(1)
2278: .&Apache::lonhtmlcommon::end_pick_box()
2279: );
2280:
2281: # ---------------------- Publishing from $fn to $thistarget with $thisembstyle.
2282:
2283: unless ($env{'form.phase'} eq 'two') {
2284: # ---------------------------------------------------------- Parse for problems
2285: my ($warningcount,$errorcount);
2286: if ($thisembstyle eq 'ssi') {
2287: ($warningcount,$errorcount)=&checkonthis($r,$fn);
2288: }
2289: unless ($errorcount) {
2290: my ($outstring,$error)=
2291: &publish($docroot.$fn,$docroot.$thistarget,$thisembstyle);
2292: $r->print($outstring);
2293: } else {
2294: $r->print('<h3 class="LC_error">'.
2295: &mt('The document contains errors and cannot be published.').
2296: '</h3>');
2297: }
2298: } else {
2299: &phasetwo($r,$docroot.$fn,$docroot.$thistarget,$thisembstyle,$thisdistarget);
2300: }
2301: }
2302: $r->print(&Apache::loncommon::end_page());
2303:
2304: return OK;
2305: }
2306:
2307: 1;
2308: __END__
2309:
2310: =pod
2311:
2312: =back
2313:
2314: =cut
2315:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>