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