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