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