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