1: # The LearningOnline Network with CAPA
2: # Publication Handler
3: #
4: # $Id: lonpublisher.pm,v 1.89 2002/08/09 17:57:48 matthew Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: #
29: # (TeX Content Handler
30: #
31: # 05/29/00,05/30,10/11 Gerd Kortemeyer)
32: #
33: # 11/28,11/29,11/30,12/01,12/02,12/04,12/23 Gerd Kortemeyer
34: # 03/23 Guy Albertelli
35: # 03/24,03/29,04/03 Gerd Kortemeyer
36: # 04/16/2001 Scott Harrison
37: # 05/03,05/05,05/07 Gerd Kortemeyer
38: # 05/28/2001 Scott Harrison
39: # 06/23,08/07,08/11,8/13,8/17,8/18,8/24,9/26,10/16 Gerd Kortemeyer
40: # 12/04,12/05 Guy Albertelli
41: # 12/05 Gerd Kortemeyer
42: # 12/05 Guy Albertelli
43: # 12/06,12/07 Gerd Kortemeyer
44: # 12/15,12/16 Scott Harrison
45: # 12/25 Gerd Kortemeyer
46: # YEAR=2002
47: # 1/16,1/17 Scott Harrison
48: # 1/17 Gerd Kortemeyer
49: #
50: ###
51:
52: ###############################################################################
53: ## ##
54: ## ORGANIZATION OF THIS PERL MODULE ##
55: ## ##
56: ## 1. Modules used by this module ##
57: ## 2. Various subroutines ##
58: ## 3. Publication Step One ##
59: ## 4. Phase Two ##
60: ## 5. Main Handler ##
61: ## ##
62: ###############################################################################
63:
64: package Apache::lonpublisher;
65:
66: # ------------------------------------------------- modules used by this module
67: use strict;
68: use Apache::File;
69: use File::Copy;
70: use Apache::Constants qw(:common :http :methods);
71: use HTML::LCParser;
72: use Apache::lonxml;
73: use Apache::lonhomework;
74: use Apache::loncacc;
75: use DBI;
76: use Apache::lonnet();
77: use Apache::loncommon();
78: use Apache::lonmysql;
79:
80: my %addid;
81: my %nokey;
82:
83: my %metadatafields;
84: my %metadatakeys;
85:
86: my $docroot;
87:
88: my $cuname;
89: my $cudom;
90:
91: # ----------------------------------------------- Evaluate string with metadata
92: sub metaeval {
93: my $metastring=shift;
94:
95: my $parser=HTML::LCParser->new(\$metastring);
96: my $token;
97: while ($token=$parser->get_token) {
98: if ($token->[0] eq 'S') {
99: my $entry=$token->[1];
100: my $unikey=$entry;
101: if (defined($token->[2]->{'package'})) {
102: $unikey.='_package_'.$token->[2]->{'package'};
103: }
104: if (defined($token->[2]->{'part'})) {
105: $unikey.='_'.$token->[2]->{'part'};
106: }
107: if (defined($token->[2]->{'id'})) {
108: $unikey.='_'.$token->[2]->{'id'};
109: }
110: if (defined($token->[2]->{'name'})) {
111: $unikey.='_'.$token->[2]->{'name'};
112: }
113: foreach (@{$token->[3]}) {
114: $metadatafields{$unikey.'.'.$_}=$token->[2]->{$_};
115: if ($metadatakeys{$unikey}) {
116: $metadatakeys{$unikey}.=','.$_;
117: } else {
118: $metadatakeys{$unikey}=$_;
119: }
120: }
121: if ($metadatafields{$unikey}) {
122: my $newentry=$parser->get_text('/'.$entry);
123: unless (($metadatafields{$unikey}=~/$newentry/) ||
124: ($newentry eq '')) {
125: $metadatafields{$unikey}.=', '.$newentry;
126: }
127: } else {
128: $metadatafields{$unikey}=$parser->get_text('/'.$entry);
129: }
130: }
131: }
132: }
133:
134: # -------------------------------------------------------- Read a metadata file
135: sub metaread {
136: my ($logfile,$fn)=@_;
137: unless (-e $fn) {
138: print $logfile 'No file '.$fn."\n";
139: return '<br><b>No file:</b> <tt>'.$fn.'</tt>';
140: }
141: print $logfile 'Processing '.$fn."\n";
142: my $metastring;
143: {
144: my $metafh=Apache::File->new($fn);
145: $metastring=join('',<$metafh>);
146: }
147: &metaeval($metastring);
148: return '<br><b>Processed file:</b> <tt>'.$fn.'</tt>';
149: }
150:
151: # ---------------------------- convert 'time' format into a datetime sql format
152: sub sqltime {
153: my $timef=shift @_;
154: my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
155: localtime($timef);
156: $mon++; $year+=1900;
157: return "$year-$mon-$mday $hour:$min:$sec";
158: }
159:
160: # --------------------------------------------------------- Various form fields
161:
162: sub textfield {
163: my ($title,$name,$value)=@_;
164: return "\n<p><b>$title:</b><br>".
165: '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
166: }
167:
168: sub hiddenfield {
169: my ($name,$value)=@_;
170: return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
171: }
172:
173: sub selectbox {
174: my ($title,$name,$value,$functionref,@idlist)=@_;
175: my $uctitle=uc($title);
176: my $selout="\n<p><font color=\"#800000\" face=\"helvetica\"><b>$uctitle:".
177: "</b></font><br />".'<select name="'.$name.'">';
178: foreach (@idlist) {
179: $selout.='<option value=\''.$_.'\'';
180: if ($_ eq $value) {
181: $selout.=' selected>'.&{$functionref}($_).'</option>';
182: }
183: else {$selout.='>'.&{$functionref}($_).'</option>';}
184: }
185: return $selout.'</select>';
186: }
187:
188: # -------------------------------------------------------- Publication Step One
189:
190: sub urlfixup {
191: my ($url,$target)=@_;
192: unless ($url) { return ''; }
193: #javascript code needs no fixing
194: if ($url =~ /^javascript:/i) { return $url; }
195: if ($url =~ /^mailto:/i) { return $url; }
196: #internal document links need no fixing
197: if ($url =~ /^\#/) { return $url; }
198: my ($host)=($url=~/(?:http\:\/\/)*([^\/]+)/);
199: foreach (values %Apache::lonnet::hostname) {
200: if ($_ eq $host) {
201: $url=~s/^http\:\/\///;
202: $url=~s/^$host//;
203: }
204: }
205: if ($url=~/^http\:\/\//) { return $url; }
206: $url=~s/\~$cuname/res\/$cudom\/$cuname/;
207: return $url;
208: }
209:
210:
211: sub absoluteurl {
212: my ($url,$target)=@_;
213: unless ($url) { return ''; }
214: if ($target) {
215: $target=~s/\/[^\/]+$//;
216: $url=&Apache::lonnet::hreflocation($target,$url);
217: }
218: return $url;
219: }
220:
221: sub set_allow {
222: my ($allow,$logfile,$target,$tag,$oldurl)=@_;
223: my $newurl=&urlfixup($oldurl,$target);
224: my $return_url=$oldurl;
225: print $logfile 'GUYURL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
226: if ($newurl ne $oldurl) {
227: $return_url=$newurl;
228: print $logfile 'URL: '.$tag.':'.$oldurl.' - '.$newurl."\n";
229: }
230: if (($newurl !~ /^javascript:/i) &&
231: ($newurl !~ /^mailto:/i) &&
232: ($newurl !~ /^http:/i) &&
233: ($newurl !~ /^\#/)) {
234: $$allow{&absoluteurl($newurl,$target)}=1;
235: }
236: return $return_url
237: }
238:
239: sub get_subscribed_hosts {
240: my ($target)=@_;
241: my @subscribed;
242: my $filename;
243: $target=~/(.*)\/([^\/]+)$/;
244: my $srcf=$2;
245: opendir(DIR,$1);
246: while ($filename=readdir(DIR)) {
247: if ($filename=~/$srcf\.(\w+)$/) {
248: my $subhost=$1;
249: if ($subhost ne 'meta' && $subhost ne 'subscription') {
250: push(@subscribed,$subhost);
251: }
252: }
253: }
254: closedir(DIR);
255: my $sh;
256: if ( $sh=Apache::File->new("$target.subscription") ) {
257: &Apache::lonnet::logthis("opened $target.subscription");
258: while (my $subline=<$sh>) {
259: &Apache::lonnet::logthis("Trying $subline");
260: if ($subline =~ /(^\w+):/) { push(@subscribed,$1); } else {
261: &Apache::lonnet::logthis("No Match for $subline");
262: }
263: }
264: } else {
265: &Apache::lonnet::logthis("Un able to open $target.subscription");
266: }
267: &Apache::lonnet::logthis("Got list of ".join(':',@subscribed));
268: return @subscribed;
269: }
270:
271:
272: sub get_max_ids_indices {
273: my ($content)=@_;
274: my $maxindex=10;
275: my $maxid=10;
276: my $needsfixup=0;
277:
278: my $parser=HTML::LCParser->new($content);
279: my $token;
280: while ($token=$parser->get_token) {
281: if ($token->[0] eq 'S') {
282: my $counter;
283: if ($counter=$addid{$token->[1]}) {
284: if ($counter eq 'id') {
285: if (defined($token->[2]->{'id'})) {
286: $maxid=($token->[2]->{'id'}>$maxid)?$token->[2]->{'id'}:$maxid;
287: } else {
288: $needsfixup=1;
289: }
290: } else {
291: if (defined($token->[2]->{'index'})) {
292: $maxindex=($token->[2]->{'index'}>$maxindex)?$token->[2]->{'index'}:$maxindex;
293: } else {
294: $needsfixup=1;
295: }
296: }
297: }
298: }
299: }
300: return ($needsfixup,$maxid,$maxindex);
301: }
302:
303: sub get_all_text_unbalanced {
304: #there is a copy of this in lonxml.pm
305: my($tag,$pars)= @_;
306: my $token;
307: my $result='';
308: $tag='<'.$tag.'>';
309: while ($token = $$pars[-1]->get_token) {
310: if (($token->[0] eq 'T')||($token->[0] eq 'C')||($token->[0] eq 'D')) {
311: $result.=$token->[1];
312: } elsif ($token->[0] eq 'PI') {
313: $result.=$token->[2];
314: } elsif ($token->[0] eq 'S') {
315: $result.=$token->[4];
316: } elsif ($token->[0] eq 'E') {
317: $result.=$token->[2];
318: }
319: if ($result =~ /(.*)$tag(.*)/) {
320: #&Apache::lonnet::logthis('Got a winner with leftovers ::'.$2);
321: #&Apache::lonnet::logthis('Result is :'.$1);
322: $result=$1;
323: my $redo=$tag.$2;
324: push (@$pars,HTML::LCParser->new(\$redo));
325: $$pars[-1]->xml_mode('1');
326: last;
327: }
328: }
329: return $result
330: }
331:
332: #Arguably this should all be done as a lonnet::ssi instead
333: sub fix_ids_and_indices {
334: my ($logfile,$source,$target)=@_;
335:
336: my %allow;
337: my $content;
338: {
339: my $org=Apache::File->new($source);
340: $content=join('',<$org>);
341: }
342:
343: my ($needsfixup,$maxid,$maxindex)=&get_max_ids_indices(\$content);
344:
345: if ($needsfixup) {
346: print $logfile "Needs ID and/or index fixup\n".
347: "Max ID : $maxid (min 10)\n".
348: "Max Index: $maxindex (min 10)\n";
349: }
350: my $outstring='';
351: my @parser;
352: $parser[0]=HTML::LCParser->new(\$content);
353: $parser[-1]->xml_mode(1);
354: my $token;
355: while (@parser) {
356: while ($token=$parser[-1]->get_token) {
357: if ($token->[0] eq 'S') {
358: my $counter;
359: my $tag=$token->[1];
360: my $lctag=lc($tag);
361: if ($lctag eq 'allow') {
362: $allow{$token->[2]->{'src'}}=1;
363: next;
364: }
365: my %parms=%{$token->[2]};
366: $counter=$addid{$tag};
367: if (!$counter) { $counter=$addid{$lctag}; }
368: if ($counter) {
369: if ($counter eq 'id') {
370: unless (defined($parms{'id'})) {
371: $maxid++;
372: $parms{'id'}=$maxid;
373: print $logfile 'ID: '.$tag.':'.$maxid."\n";
374: }
375: } elsif ($counter eq 'index') {
376: unless (defined($parms{'index'})) {
377: $maxindex++;
378: $parms{'index'}=$maxindex;
379: print $logfile 'Index: '.$tag.':'.$maxindex."\n";
380: }
381: }
382: }
383: foreach my $type ('src','href','background','bgimg') {
384: foreach my $key (keys(%parms)) {
385: if ($key =~ /^$type$/i) {
386: $parms{$key}=&set_allow(\%allow,$logfile,
387: $target,$tag,
388: $parms{$key});
389: }
390: }
391: }
392: # probably a <randomlabel> image type <label>
393: if ($lctag eq 'label' && defined($parms{'description'})) {
394: my $next_token=$parser[-1]->get_token();
395: if ($next_token->[0] eq 'T') {
396: $next_token->[1]=&set_allow(\%allow,$logfile,
397: $target,$tag,
398: $next_token->[1]);
399: }
400: $parser[-1]->unget_token($next_token);
401: }
402: if ($lctag eq 'applet') {
403: my $codebase='';
404: if (defined($parms{'codebase'})) {
405: my $oldcodebase=$parms{'codebase'};
406: unless ($oldcodebase=~/\/$/) {
407: $oldcodebase.='/';
408: }
409: $codebase=&urlfixup($oldcodebase,$target);
410: $codebase=~s/\/$//;
411: if ($codebase ne $oldcodebase) {
412: $parms{'codebase'}=$codebase;
413: print $logfile 'URL codebase: '.$tag.':'.
414: $oldcodebase.' - '.
415: $codebase."\n";
416: }
417: $allow{&absoluteurl($codebase,$target).'/*'}=1;
418: } else {
419: foreach ('archive','code','object') {
420: if (defined($parms{$_})) {
421: my $oldurl=$parms{$_};
422: my $newurl=&urlfixup($oldurl,$target);
423: $newurl=~s/\/[^\/]+$/\/\*/;
424: print $logfile 'Allow: applet '.$_.':'.
425: $oldurl.' allows '.
426: $newurl."\n";
427: $allow{&absoluteurl($newurl,$target)}=1;
428: }
429: }
430: }
431: }
432: my $newparmstring='';
433: my $endtag='';
434: foreach (keys %parms) {
435: if ($_ eq '/') {
436: $endtag=' /';
437: } else {
438: my $quote=($parms{$_}=~/\"/?"'":'"');
439: $newparmstring.=' '.$_.'='.$quote.$parms{$_}.$quote;
440: }
441: }
442: if (!$endtag) { if ($token->[4]=~m:/>$:) { $endtag=' /'; }; }
443: $outstring.='<'.$tag.$newparmstring.$endtag.'>';
444: if ($lctag eq 'm') {
445: $outstring.=&get_all_text_unbalanced('/m',\@parser);
446: }
447: } elsif ($token->[0] eq 'E') {
448: if ($token->[2]) {
449: unless ($token->[1] eq 'allow') {
450: $outstring.='</'.$token->[1].'>';
451: }
452: }
453: } else {
454: $outstring.=$token->[1];
455: }
456: }
457: pop(@parser);
458: }
459:
460: if ($needsfixup) {
461: print $logfile "End of ID and/or index fixup\n".
462: "Max ID : $maxid (min 10)\n".
463: "Max Index: $maxindex (min 10)\n";
464: } else {
465: print $logfile "Does not need ID and/or index fixup\n";
466: }
467:
468: return ($outstring,%allow);
469: }
470:
471: #########################################
472: #########################################
473:
474: =pod
475:
476: =item store_metadata
477:
478: Store the metadata in the metadata table in the loncapa database.
479: Uses lonmysql to access the database.
480:
481: Inputs: \%metadata
482:
483: Returns: (error,status). error is undef on success, status is undef on error.
484:
485: =cut
486:
487: #########################################
488: #########################################
489: sub store_metadata {
490: my %metadata = %{shift()};
491: my $error;
492: # Determine if the table exists
493: my $status = &Apache::lonmysql::check_table('metadata');
494: if (! defined($status)) {
495: $error='<font color="red">WARNING: Cannot connect to '.
496: 'database!</font>';
497: &Apache::lonnet::logthis($error);
498: return ($error,undef);
499: }
500: if ($status == 0) {
501: # It would be nice to actually create the table....
502: $error ='<font color="red">WARNING: The metadata table does not '.
503: 'exist in the LON-CAPA database.</font>';
504: &Apache::lonnet::logthis($error);
505: return ($error,undef);
506: }
507: # Remove old value from table
508: $status = &Apache::lonmysql::remove_from_table
509: ('metadata','url',$metadata{'url'});
510: if (! defined($status)) {
511: $error = '<font color="red">Error when removing old values from '.
512: 'metadata table in LON-CAPA database.</font>';
513: &Apache::lonnet::logthis($error);
514: return ($error,undef);
515: }
516: # Store data in table.
517: $status = &Apache::lonmysql::store_row('metadata',\%metadata);
518: if (! defined($status)) {
519: $error='<font color="red">Error occured storing new values in '.
520: 'metadata table in LON-CAPA database</font>';
521: &Apache::lonnet::logthis($error);
522: return ($error,undef);
523: }
524: return (undef,$status);
525: }
526:
527: sub publish {
528:
529: my ($source,$target,$style)=@_;
530: my $logfile;
531: my $scrout='';
532: my $allmeta='';
533: my $content='';
534: my %allow=();
535:
536: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
537: return
538: '<font color=red>No write permission to user directory, FAIL</font>';
539: }
540: print $logfile
541: "\n\n================= Publish ".localtime()." Phase One ================\n";
542:
543: if (($style eq 'ssi') || ($style eq 'rat')) {
544: # ------------------------------------------------------- This needs processing
545:
546: # ----------------------------------------------------------------- Backup Copy
547: my $copyfile=$source.'.save';
548: if (copy($source,$copyfile)) {
549: print $logfile "Copied original file to ".$copyfile."\n";
550: } else {
551: print $logfile "Unable to write backup ".$copyfile.':'.$!."\n";
552: return "<font color=red>Failed to write backup copy, $!,FAIL</font>";
553: }
554: # ------------------------------------------------------------- IDs and indices
555:
556: my $outstring;
557: ($outstring,%allow)=&fix_ids_and_indices($logfile,$source,$target);
558: # ------------------------------------------------------------ Construct Allows
559:
560: $scrout.='<h3>Dependencies</h3>';
561: my $allowstr='';
562: foreach (sort(keys(%allow))) {
563: my $thisdep=$_;
564: if ($thisdep !~ /[^\s]/) { next; }
565: unless ($style eq 'rat') {
566: $allowstr.="\n".'<allow src="'.$thisdep.'" />';
567: }
568: $scrout.='<br>';
569: unless ($thisdep=~/\*/) {
570: $scrout.='<a href="'.$thisdep.'">';
571: }
572: $scrout.='<tt>'.$thisdep.'</tt>';
573: unless ($thisdep=~/\*/) {
574: $scrout.='</a>';
575: if (
576: &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
577: $thisdep.'.meta') eq '-1') {
578: $scrout.=
579: ' - <font color=red>Currently not available</font>';
580: } else {
581: my %temphash=(&Apache::lonnet::declutter($target).'___'.
582: &Apache::lonnet::declutter($thisdep).'___usage'
583: => time);
584: $thisdep=~/^\/res\/(\w+)\/(\w+)\//;
585: if ((defined($1)) && (defined($2))) {
586: &Apache::lonnet::put('resevaldata',\%temphash,$1,$2);
587: }
588: }
589: }
590: }
591: $outstring=~s/\n*(\<\/[^\>]+\>)\s*$/$allowstr\n$1\n/s;
592:
593: #Encode any High ASCII characters
594: $outstring=&HTML::Entities::encode($outstring,"\200-\377");
595: # ------------------------------------------------------------- Write modified
596:
597: {
598: my $org;
599: unless ($org=Apache::File->new('>'.$source)) {
600: print $logfile "No write permit to $source\n";
601: return
602: "<font color=red>No write permission to $source, FAIL</font>";
603: }
604: print $org $outstring;
605: }
606: $content=$outstring;
607:
608: }
609: # --------------------------------------------- Initial step done, now metadata
610:
611: # ---------------------------------------- Storage for metadata keys and fields
612:
613: %metadatafields=();
614: %metadatakeys=();
615:
616: my %oldparmstores=();
617:
618:
619: $scrout.='<h3>Metadata Information ' .
620: Apache::loncommon::help_open_topic("Metadata_Description")
621: . '</h3>';
622:
623: # ------------------------------------------------ First, check out environment
624: unless (-e $source.'.meta') {
625: $metadatafields{'author'}=$ENV{'environment.firstname'}.' '.
626: $ENV{'environment.middlename'}.' '.
627: $ENV{'environment.lastname'}.' '.
628: $ENV{'environment.generation'};
629: $metadatafields{'author'}=~s/\s+/ /g;
630: $metadatafields{'author'}=~s/\s+$//;
631: $metadatafields{'owner'}=$cuname.'@'.$cudom;
632:
633: # ------------------------------------------------ Check out directory hierachy
634:
635: my $thisdisfn=$source;
636: $thisdisfn=~s/^\/home\/$cuname\///;
637:
638: my @urlparts=split(/\//,$thisdisfn);
639: $#urlparts--;
640:
641: my $currentpath='/home/'.$cuname.'/';
642:
643: foreach (@urlparts) {
644: $currentpath.=$_.'/';
645: $scrout.=&metaread($logfile,$currentpath.'default.meta');
646: }
647:
648: # ------------------- Clear out parameters and stores (there should not be any)
649:
650: foreach (keys %metadatafields) {
651: if (($_=~/^parameter/) || ($_=~/^stores/)) {
652: delete $metadatafields{$_};
653: }
654: }
655:
656: } else {
657: # ---------------------- Read previous metafile, remember parameters and stores
658:
659: $scrout.=&metaread($logfile,$source.'.meta');
660:
661: foreach (keys %metadatafields) {
662: if (($_=~/^parameter/) || ($_=~/^stores/)) {
663: $oldparmstores{$_}=1;
664: delete $metadatafields{$_};
665: }
666: }
667:
668: }
669:
670: # -------------------------------------------------- Parse content for metadata
671: if ($style eq 'ssi') {
672: my $oldenv=$ENV{'request.uri'};
673:
674: $ENV{'request.uri'}=$target;
675: $allmeta=Apache::lonxml::xmlparse(undef,'meta',$content);
676: $ENV{'request.uri'}=$oldenv;
677:
678: &metaeval($allmeta);
679: }
680: # ---------------- Find and document discrepancies in the parameters and stores
681:
682: my $chparms='';
683: foreach (sort keys %metadatafields) {
684: if (($_=~/^parameter/) || ($_=~/^stores/)) {
685: unless ($_=~/\.\w+$/) {
686: unless ($oldparmstores{$_}) {
687: print $logfile 'New: '.$_."\n";
688: $chparms.=$_.' ';
689: }
690: }
691: }
692: }
693: if ($chparms) {
694: $scrout.='<p><b>New parameters or stored values:</b> '.
695: $chparms;
696: }
697:
698: $chparms='';
699: foreach (sort keys %oldparmstores) {
700: if (($_=~/^parameter/) || ($_=~/^stores/)) {
701: unless (($metadatafields{$_.'.name'}) ||
702: ($metadatafields{$_.'.package'}) || ($_=~/\.\w+$/)) {
703: print $logfile 'Obsolete: '.$_."\n";
704: $chparms.=$_.' ';
705: }
706: }
707: }
708: if ($chparms) {
709: $scrout.='<p><b>Obsolete parameters or stored values:</b> '.
710: $chparms;
711: }
712:
713: # ------------------------------------------------------- Now have all metadata
714:
715: $scrout.=
716: '<form name="pubform" action="/adm/publish" method="post">'.
717: '<p><input type="submit" value="Finalize Publication" /></p>'.
718: &hiddenfield('phase','two').
719: &hiddenfield('filename',$ENV{'form.filename'}).
720: &hiddenfield('allmeta',&Apache::lonnet::escape($allmeta)).
721: &hiddenfield('dependencies',join(',',keys %allow)).
722: &textfield('Title','title',$metadatafields{'title'}).
723: &textfield('Author(s)','author',$metadatafields{'author'}).
724: &textfield('Subject','subject',$metadatafields{'subject'});
725:
726: # --------------------------------------------------- Scan content for keywords
727:
728: my $keywords_help = Apache::loncommon::help_open_topic("Publishing_Keywords");
729: my $keywordout=<<"END";
730: <script>
731: function checkAll(field)
732: {
733: for (i = 0; i < field.length; i++)
734: field[i].checked = true ;
735: }
736:
737: function uncheckAll(field)
738: {
739: for (i = 0; i < field.length; i++)
740: field[i].checked = false ;
741: }
742: </script>
743: <p><b>Keywords: $keywords_help</b>
744: <input type="button" value="check all" onclick="javascript:checkAll(document.pubform.keywords)">
745: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.pubform.keywords)">
746: <br />
747: END
748: $keywordout.='<table border=2><tr>';
749: my $colcount=0;
750: my %keywords=();
751:
752: if (length($content)<500000) {
753: my $textonly=$content;
754: $textonly=~s/\<script[^\<]+\<\/script\>//g;
755: $textonly=~s/\<m\>[^\<]+\<\/m\>//g;
756: $textonly=~s/\<[^\>]*\>//g;
757: $textonly=~tr/A-Z/a-z/;
758: $textonly=~s/[\$\&][a-z]\w*//g;
759: $textonly=~s/[^a-z\s]//g;
760:
761: foreach ($textonly=~m/(\w+)/g) {
762: unless ($nokey{$_}) {
763: $keywords{$_}=1;
764: }
765: }
766: }
767:
768:
769: foreach (split(/\W+/,$metadatafields{'keywords'})) {
770: $keywords{$_}=1;
771: }
772:
773: foreach (sort keys %keywords) {
774: $keywordout.='<td><input type=checkbox name="keywords" value="'.$_.'"';
775: if ($metadatafields{'keywords'}) {
776: if ($metadatafields{'keywords'}=~/$_/) {
777: $keywordout.=' checked';
778: }
779: } elsif (&Apache::loncommon::keyword($_)) {
780: $keywordout.=' checked';
781: }
782: $keywordout.='>'.$_.'</td>';
783: if ($colcount>10) {
784: $keywordout.="</tr><tr>\n";
785: $colcount=0;
786: }
787: $colcount++;
788: }
789:
790: $keywordout.='</tr></table>';
791:
792: $scrout.=$keywordout;
793:
794: $scrout.=&textfield('Additional Keywords','addkey','');
795:
796: $scrout.=&textfield('Notes','notes',$metadatafields{'notes'});
797:
798: $scrout.=
799: '<p><b>Abstract:</b><br><textarea cols=80 rows=5 name=abstract>'.
800: $metadatafields{'abstract'}.'</textarea>';
801:
802: $source=~/\.(\w+)$/;
803:
804: $scrout.=&hiddenfield('mime',$1);
805:
806: $scrout.=&selectbox('Language','language',
807: $metadatafields{'language'},
808: \&Apache::loncommon::languagedescription,
809: (&Apache::loncommon::languageids),
810: );
811:
812: unless ($metadatafields{'creationdate'}) {
813: $metadatafields{'creationdate'}=time;
814: }
815: $scrout.=&hiddenfield('creationdate',$metadatafields{'creationdate'});
816:
817: $scrout.=&hiddenfield('lastrevisiondate',time);
818:
819:
820: $scrout.=&textfield('Publisher/Owner','owner',
821: $metadatafields{'owner'});
822: # --------------------------------------------------- Correct copyright for rat
823:
824: if ($style eq 'rat') {
825: if ($metadatafields{'copyright'} eq 'public') {
826: delete $metadatafields{'copyright'};
827: }
828: $scrout.=&selectbox('Copyright/Distribution','copyright',
829: $metadatafields{'copyright'},
830: \&Apache::loncommon::copyrightdescription,
831: (grep !/^public$/,(&Apache::loncommon::copyrightids)));
832: }
833: else {
834: $scrout.=&selectbox('Copyright/Distribution','copyright',
835: $metadatafields{'copyright'},
836: \&Apache::loncommon::copyrightdescription,
837: (&Apache::loncommon::copyrightids));
838: }
839:
840: my $copyright_help = Apache::loncommon::help_open_topic("Publishing_Copyright");
841: $scrout =~ s/DISTRIBUTION:/'DISTRIBUTION: ' . $copyright_help/ge;
842: return $scrout.
843: '<p><input type="submit" value="Finalize Publication" /></p></form>';
844: }
845:
846: # -------------------------------------------------------- Publication Step Two
847:
848: sub phasetwo {
849:
850: my ($source,$target,$style,$distarget)=@_;
851: my $logfile;
852: my $scrout='';
853: unless ($logfile=Apache::File->new('>>'.$source.'.log')) {
854: return
855: '<font color=red>No write permission to user directory, FAIL</font>';
856: }
857: print $logfile
858: "\n================= Publish ".localtime()." Phase Two ================\n";
859:
860: %metadatafields=();
861: %metadatakeys=();
862:
863: &metaeval(&Apache::lonnet::unescape($ENV{'form.allmeta'}));
864:
865: $metadatafields{'title'}=$ENV{'form.title'};
866: $metadatafields{'author'}=$ENV{'form.author'};
867: $metadatafields{'subject'}=$ENV{'form.subject'};
868: $metadatafields{'notes'}=$ENV{'form.notes'};
869: $metadatafields{'abstract'}=$ENV{'form.abstract'};
870: $metadatafields{'mime'}=$ENV{'form.mime'};
871: $metadatafields{'language'}=$ENV{'form.language'};
872: $metadatafields{'creationdate'}=$ENV{'form.creationdate'};
873: $metadatafields{'lastrevisiondate'}=$ENV{'form.lastrevisiondate'};
874: $metadatafields{'owner'}=$ENV{'form.owner'};
875: $metadatafields{'copyright'}=$ENV{'form.copyright'};
876: $metadatafields{'dependencies'}=$ENV{'form.dependencies'};
877:
878: my $allkeywords=$ENV{'form.addkey'};
879: if (exists($ENV{'form.keywords'}) && (ref($ENV{'form.keywords'}))) {
880: my @Keywords = @{$ENV{'form.keywords'}};
881: foreach (@Keywords) {
882: $allkeywords.=','.$_;
883: }
884: }
885: $allkeywords=~s/\W+/\,/;
886: $allkeywords=~s/^\,//;
887: $metadatafields{'keywords'}=$allkeywords;
888:
889: {
890: print $logfile "\nWrite metadata file for ".$source;
891: my $mfh;
892: unless ($mfh=Apache::File->new('>'.$source.'.meta')) {
893: return
894: '<font color=red>Could not write metadata, FAIL</font>';
895: }
896: foreach (sort keys %metadatafields) {
897: unless ($_=~/\./) {
898: my $unikey=$_;
899: $unikey=~/^([A-Za-z]+)/;
900: my $tag=$1;
901: $tag=~tr/A-Z/a-z/;
902: print $mfh "\n\<$tag";
903: foreach (split(/\,/,$metadatakeys{$unikey})) {
904: my $value=$metadatafields{$unikey.'.'.$_};
905: $value=~s/\"/\'\'/g;
906: print $mfh ' '.$_.'="'.$value.'"';
907: }
908: print $mfh '>'.
909: &HTML::Entities::encode($metadatafields{$unikey})
910: .'</'.$tag.'>';
911: }
912: }
913: $scrout.='<p>Wrote Metadata';
914: print $logfile "\nWrote metadata";
915: }
916:
917: # -------------------------------- Synchronize entry with SQL metadata database
918: my $warning;
919: $metadatafields{'url'} = $distarget;
920: $metadatafields{'version'} = 'current';
921: unless ($metadatafields{'copyright'} eq 'priv') {
922: my ($error,$success) = &store_metadata(\%metadatafields);
923: if (! $success) {
924: $scrout.='<p>Synchronized SQL metadata database';
925: print $logfile "\nSynchronized SQL metadata database";
926: } else {
927: $warning.=$error;
928: print $logfile "\n".$error;
929: }
930: } else {
931: $scrout.='<p>Private Publication - did not synchronize database';
932: print $logfile "\nPrivate: Did not synchronize data into ".
933: "SQL metadata database";
934: }
935: # ----------------------------------------------------------- Copy old versions
936:
937: if (-e $target) {
938: my $filename;
939: my $maxversion=0;
940: $target=~/(.*)\/([^\/]+)\.(\w+)$/;
941: my $srcf=$2;
942: my $srct=$3;
943: my $srcd=$1;
944: unless ($srcd=~/^\/home\/httpd\/html\/res/) {
945: print $logfile "\nPANIC: Target dir is ".$srcd;
946: return "<font color=red>Invalid target directory, FAIL</font>";
947: }
948: opendir(DIR,$srcd);
949: while ($filename=readdir(DIR)) {
950: if ($filename=~/$srcf\.(\d+)\.$srct$/) {
951: $maxversion=($1>$maxversion)?$1:$maxversion;
952: }
953: }
954: closedir(DIR);
955: $maxversion++;
956: $scrout.='<p>Creating old version '.$maxversion;
957: print $logfile "\nCreating old version ".$maxversion;
958:
959: my $copyfile=$srcd.'/'.$srcf.'.'.$maxversion.'.'.$srct;
960:
961: if (copy($target,$copyfile)) {
962: print $logfile "Copied old target to ".$copyfile."\n";
963: $scrout.='<p>Copied old target file';
964: } else {
965: print $logfile "Unable to write ".$copyfile.':'.$!."\n";
966: return "<font color=red>Failed to copy old target, $!, FAIL</font>";
967: }
968:
969: # --------------------------------------------------------------- Copy Metadata
970:
971: $copyfile=$copyfile.'.meta';
972:
973: if (copy($target.'.meta',$copyfile)) {
974: print $logfile "Copied old target metadata to ".$copyfile."\n";
975: $scrout.='<p>Copied old metadata';
976: } else {
977: print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
978: if (-e $target.'.meta') {
979: return
980: "<font color=red>Failed to write old metadata copy, $!, FAIL</font>";
981: }
982: }
983:
984:
985: } else {
986: $scrout.='<p>Initial version';
987: print $logfile "\nInitial version";
988: }
989:
990: # ---------------------------------------------------------------- Write Source
991: my $copyfile=$target;
992:
993: my @parts=split(/\//,$copyfile);
994: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
995:
996: my $count;
997: for ($count=5;$count<$#parts;$count++) {
998: $path.="/$parts[$count]";
999: if ((-e $path)!=1) {
1000: print $logfile "\nCreating directory ".$path;
1001: $scrout.='<p>Created directory '.$parts[$count];
1002: mkdir($path,0777);
1003: }
1004: }
1005:
1006: if (copy($source,$copyfile)) {
1007: print $logfile "Copied original source to ".$copyfile."\n";
1008: $scrout.='<p>Copied source file';
1009: } else {
1010: print $logfile "Unable to write ".$copyfile.':'.$!."\n";
1011: return "<font color=red>Failed to copy source, $!, FAIL</font>";
1012: }
1013:
1014: # --------------------------------------------------------------- Copy Metadata
1015:
1016: $copyfile=$copyfile.'.meta';
1017:
1018: if (copy($source.'.meta',$copyfile)) {
1019: print $logfile "Copied original metadata to ".$copyfile."\n";
1020: $scrout.='<p>Copied metadata';
1021: } else {
1022: print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
1023: return
1024: "<font color=red>Failed to write metadata copy, $!, FAIL</font>";
1025: }
1026:
1027: # --------------------------------------------------- Send update notifications
1028:
1029: my @subscribed=&get_subscribed_hosts($target);
1030: foreach my $subhost (@subscribed) {
1031: $scrout.='<p>Notifying host '.$subhost.':';
1032: print $logfile "\nNotifying host ".$subhost.':';
1033: my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
1034: $scrout.=$reply;
1035: print $logfile $reply;
1036: }
1037:
1038: # ---------------------------------------- Send update notifications, meta only
1039:
1040: my @subscribedmeta=&get_subscribed_hosts("$target.meta");
1041: foreach my $subhost (@subscribedmeta) {
1042: $scrout.='<p>Notifying host for metadata only '.$subhost.':';
1043: print $logfile "\nNotifying host for metadata only ".$subhost.':';
1044: my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
1045: $subhost);
1046: $scrout.=$reply;
1047: print $logfile $reply;
1048: }
1049:
1050: # ------------------------------------------------ Provide link to new resource
1051:
1052: my $thisdistarget=$target;
1053: $thisdistarget=~s/^$docroot//;
1054:
1055: my $thissrc=$source;
1056: $thissrc=~s/^\/home\/(\w+)\/public_html/\/priv\/$1/;
1057:
1058: my $thissrcdir=$thissrc;
1059: $thissrcdir=~s/\/[^\/]+$/\//;
1060:
1061:
1062: return $warning.$scrout.
1063: '<hr><a href="'.$thisdistarget.'"><font size=+2>View Published Version</font></a>'.
1064: '<p><a href="'.$thissrc.'"><font size=+2>Back to Source</font></a>'.
1065: '<p><a href="'.$thissrcdir.
1066: '"><font size=+2>Back to Source Directory</font></a>';
1067:
1068: }
1069:
1070: # ================================================================ Main Handler
1071:
1072: sub handler {
1073: my $r=shift;
1074:
1075: if ($r->header_only) {
1076: $r->content_type('text/html');
1077: $r->send_http_header;
1078: return OK;
1079: }
1080:
1081: # Get query string for limited number of parameters
1082:
1083: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1084: ['filename']);
1085:
1086: # -------------------------------------------------------------- Check filename
1087:
1088: my $fn=$ENV{'form.filename'};
1089:
1090:
1091: unless ($fn) {
1092: $r->log_reason($cuname.' at '.$cudom.
1093: ' trying to publish empty filename', $r->filename);
1094: return HTTP_NOT_FOUND;
1095: }
1096:
1097: ($cuname,$cudom)=
1098: &Apache::loncacc::constructaccess($fn,$r->dir_config('lonDefDomain'));
1099: unless (($cuname) && ($cudom)) {
1100: $r->log_reason($cuname.' at '.$cudom.
1101: ' trying to publish file '.$ENV{'form.filename'}.
1102: ' ('.$fn.') - not authorized',
1103: $r->filename);
1104: return HTTP_NOT_ACCEPTABLE;
1105: }
1106:
1107: unless (&Apache::lonnet::homeserver($cuname,$cudom)
1108: eq $r->dir_config('lonHostID')) {
1109: $r->log_reason($cuname.' at '.$cudom.
1110: ' trying to publish file '.$ENV{'form.filename'}.
1111: ' ('.$fn.') - not homeserver ('.
1112: &Apache::lonnet::homeserver($cuname,$cudom).')',
1113: $r->filename);
1114: return HTTP_NOT_ACCEPTABLE;
1115: }
1116:
1117: $fn=~s/^http\:\/\/[^\/]+//;
1118: $fn=~s/^\/\~(\w+)/\/home\/$1\/public_html/;
1119:
1120: my $targetdir='';
1121: $docroot=$r->dir_config('lonDocRoot');
1122: if ($1 ne $cuname) {
1123: $r->log_reason($cuname.' at '.$cudom.
1124: ' trying to publish unowned file '.$ENV{'form.filename'}.
1125: ' ('.$fn.')',
1126: $r->filename);
1127: return HTTP_NOT_ACCEPTABLE;
1128: } else {
1129: $targetdir=$docroot.'/res/'.$cudom;
1130: }
1131:
1132:
1133: unless (-e $fn) {
1134: $r->log_reason($cuname.' at '.$cudom.
1135: ' trying to publish non-existing file '.$ENV{'form.filename'}.
1136: ' ('.$fn.')',
1137: $r->filename);
1138: return HTTP_NOT_FOUND;
1139: }
1140:
1141: unless ($ENV{'form.phase'} eq 'two') {
1142:
1143: # --------------------------------- File is there and owned, init lookup tables
1144:
1145: %addid=();
1146:
1147: {
1148: my $fh=Apache::File->new($r->dir_config('lonTabDir').'/addid.tab');
1149: while (<$fh>=~/(\w+)\s+(\w+)/) {
1150: $addid{$1}=$2;
1151: }
1152: }
1153:
1154: %nokey=();
1155:
1156: {
1157: my $fh=Apache::File->new($r->dir_config('lonIncludes').'/un_keyword.tab');
1158: while (<$fh>) {
1159: my $word=$_;
1160: chomp($word);
1161: $nokey{$word}=1;
1162: }
1163: }
1164:
1165: }
1166:
1167: # ----------------------------------------------------------- Start page output
1168:
1169: $r->content_type('text/html');
1170: $r->send_http_header;
1171:
1172: $r->print('<html><head><title>LON-CAPA Publishing</title></head>');
1173: $r->print(
1174: '<body bgcolor="#FFFFFF"><img align=right src=/adm/lonIcons/lonlogos.gif>');
1175: my $thisfn=$fn;
1176:
1177: # ------------------------------------------------------------- Individual file
1178: {
1179: $thisfn=~/\.(\w+)$/;
1180: my $thistype=$1;
1181: my $thisembstyle=&Apache::loncommon::fileembstyle($thistype);
1182:
1183: my $thistarget=$thisfn;
1184:
1185: $thistarget=~s/^\/home/$targetdir/;
1186: $thistarget=~s/\/public\_html//;
1187:
1188: my $thisdistarget=$thistarget;
1189: $thisdistarget=~s/^$docroot//;
1190:
1191: my $thisdisfn=$thisfn;
1192: $thisdisfn=~s/^\/home\/$cuname\/public_html\///;
1193:
1194: $r->print('<h2>Publishing '.
1195: &Apache::loncommon::filedescription($thistype).' <tt>'.
1196: $thisdisfn.'</tt></h2><b>Target:</b> <tt>'.$thisdistarget.'</tt><p>');
1197:
1198: if (($cuname ne $ENV{'user.name'}) || ($cudom ne $ENV{'user.domain'})) {
1199: $r->print('<h3><font color=red>Co-Author: '.$cuname.' at '.$cudom.
1200: '</font></h3>');
1201: }
1202:
1203: if (&Apache::loncommon::fileembstyle($thistype) eq 'ssi') {
1204: $r->print('<br><a href="/adm/diff?filename=/~'.$cuname.'/'.
1205: $thisdisfn.
1206: '&versionone=priv" target=cat>Diffs with Current Version</a><p>');
1207: }
1208:
1209: # ------------ We are publishing from $thisfn to $thistarget with $thisembstyle
1210:
1211: unless ($ENV{'form.phase'} eq 'two') {
1212: $r->print(
1213: '<hr>'.&publish($thisfn,$thistarget,$thisembstyle));
1214: } else {
1215: $r->print(
1216: '<hr>'.&phasetwo($thisfn,$thistarget,$thisembstyle,$thisdistarget));
1217: }
1218:
1219: }
1220: $r->print('</body></html>');
1221:
1222: return OK;
1223: }
1224:
1225: 1;
1226: __END__
1227:
1228: =pod
1229:
1230: =back
1231:
1232: =cut
1233:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>