Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.515
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.515 ! raeburn 4: # $Id: lonnet.pm,v 1.514 2004/06/28 15:59:50 albertel Exp $
1.178 www 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: #
1.169 harris41 28: ###
29:
1.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.15 www 34: use HTTP::Headers;
1.486 www 35: use HTTP::Date;
36: # use Date::Parse;
1.11 www 37: use vars
1.300 albertel 38: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom
1.440 www 39: %libserv %pr %prp %metacache %packagetab %titlecache %courseresversioncache %resversioncache
1.349 www 40: %courselogs %accesshash %userrolehash $processmarker $dumpcount
1.352 www 41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache
1.420 albertel 42: %userresdatacache %usectioncache %domaindescription %domain_auth_def %domain_auth_arg_def
1.403 www 43: %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir);
44:
1.1 albertel 45: use IO::Socket;
1.31 www 46: use GDBM_File;
1.8 www 47: use Apache::Constants qw(:common :http);
1.208 albertel 48: use HTML::LCParser;
1.88 www 49: use Fcntl qw(:flock);
1.294 matthew 50: use Apache::loncoursedata;
1.414 www 51: use Apache::lonlocal;
1.428 albertel 52: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw);
1.425 albertel 53: use Time::HiRes();
1.195 www 54: my $readit;
1.1 albertel 55:
1.449 matthew 56: =pod
57:
58: =head1 Package Variables
59:
60: These are largely undocumented, so if you decipher one please note it here.
61:
62: =over 4
63:
64: =item $processmarker
65:
66: Contains the time this process was started and this servers host id.
67:
68: =item $dumpcount
69:
70: Counts the number of times a message log flush has been attempted (regardless
71: of success) by this process. Used as part of the filename when messages are
72: delayed.
73:
74: =back
75:
76: =cut
77:
78:
1.1 albertel 79: # --------------------------------------------------------------------- Logging
80:
1.163 harris41 81: sub logtouch {
82: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 83: unless (-e "$execdir/logs/lonnet.log") {
84: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 85: close $fh;
86: }
87: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
88: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
89: }
90:
1.1 albertel 91: sub logthis {
92: my $message=shift;
93: my $execdir=$perlvar{'lonDaemons'};
94: my $now=time;
95: my $local=localtime($now);
1.448 albertel 96: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
97: print $fh "$local ($$): $message\n";
98: close($fh);
99: }
1.1 albertel 100: return 1;
101: }
102:
103: sub logperm {
104: my $message=shift;
105: my $execdir=$perlvar{'lonDaemons'};
106: my $now=time;
107: my $local=localtime($now);
1.448 albertel 108: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
109: print $fh "$now:$message:$local\n";
110: close($fh);
111: }
1.1 albertel 112: return 1;
113: }
114:
115: # -------------------------------------------------- Non-critical communication
116: sub subreply {
117: my ($cmd,$server)=@_;
118: my $peerfile="$perlvar{'lonSockDir'}/$server";
119: my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
120: Type => SOCK_STREAM,
121: Timeout => 10)
122: or return "con_lost";
123: print $client "$cmd\n";
124: my $answer=<$client>;
1.9 www 125: if (!$answer) { $answer="con_lost"; }
1.1 albertel 126: chomp($answer);
127: return $answer;
128: }
129:
130: sub reply {
131: my ($cmd,$server)=@_;
1.205 www 132: unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1 albertel 133: my $answer=subreply($cmd,$server);
1.203 www 134: if ($answer eq 'con_lost') {
1.311 matthew 135: #sleep 5;
136: #$answer=subreply($cmd,$server);
137: #if ($answer eq 'con_lost') {
1.233 albertel 138: # &logthis("Second attempt con_lost on $server");
139: # my $peerfile="$perlvar{'lonSockDir'}/$server";
140: # my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
141: # Type => SOCK_STREAM,
142: # Timeout => 10)
143: # or return "con_lost";
144: # &logthis("Killing socket");
145: # print $client "close_connection_exit\n";
146: #sleep 5;
147: # $answer=subreply($cmd,$server);
148: #}
1.203 www 149: }
1.65 www 150: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12 www 151: &logthis("<font color=blue>WARNING:".
152: " $cmd to $server returned $answer</font>");
153: }
1.1 albertel 154: return $answer;
155: }
156:
157: # ----------------------------------------------------------- Send USR1 to lonc
158:
159: sub reconlonc {
160: my $peerfile=shift;
161: &logthis("Trying to reconnect for $peerfile");
162: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 163: if (open(my $fh,"<$loncfile")) {
1.1 albertel 164: my $loncpid=<$fh>;
165: chomp($loncpid);
166: if (kill 0 => $loncpid) {
167: &logthis("lonc at pid $loncpid responding, sending USR1");
168: kill USR1 => $loncpid;
169: sleep 1;
170: if (-e "$peerfile") { return; }
171: &logthis("$peerfile still not there, give it another try");
172: sleep 5;
173: if (-e "$peerfile") { return; }
1.12 www 174: &logthis(
175: "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1 albertel 176: } else {
1.12 www 177: &logthis(
178: "<font color=blue>WARNING:".
179: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 180: }
181: } else {
1.12 www 182: &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1 albertel 183: }
184: }
185:
186: # ------------------------------------------------------ Critical communication
1.12 www 187:
1.1 albertel 188: sub critical {
189: my ($cmd,$server)=@_;
1.89 www 190: unless ($hostname{$server}) {
191: &logthis("<font color=blue>WARNING:".
192: " Critical message to unknown server ($server)</font>");
193: return 'no_such_host';
194: }
1.1 albertel 195: my $answer=reply($cmd,$server);
196: if ($answer eq 'con_lost') {
197: my $pingreply=reply('ping',$server);
198: &reconlonc("$perlvar{'lonSockDir'}/$server");
199: my $pongreply=reply('pong',$server);
200: &logthis("Ping/Pong for $server: $pingreply/$pongreply");
201: $answer=reply($cmd,$server);
202: if ($answer eq 'con_lost') {
203: my $now=time;
204: my $middlename=$cmd;
1.5 www 205: $middlename=substr($middlename,0,16);
1.1 albertel 206: $middlename=~s/\W//g;
207: my $dfilename=
1.305 www 208: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
209: $dumpcount++;
1.1 albertel 210: {
1.448 albertel 211: my $dfh;
212: if (open($dfh,">$dfilename")) {
213: print $dfh "$cmd\n";
214: close($dfh);
215: }
1.1 albertel 216: }
217: sleep 2;
218: my $wcmd='';
219: {
1.448 albertel 220: my $dfh;
221: if (open($dfh,"<$dfilename")) {
222: $wcmd=<$dfh>;
223: close($dfh);
224: }
1.1 albertel 225: }
226: chomp($wcmd);
1.7 www 227: if ($wcmd eq $cmd) {
1.12 www 228: &logthis("<font color=blue>WARNING: ".
229: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 230: &logperm("D:$server:$cmd");
231: return 'con_delayed';
232: } else {
1.12 www 233: &logthis("<font color=red>CRITICAL:"
234: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 235: &logperm("F:$server:$cmd");
236: return 'con_failed';
237: }
238: }
239: }
240: return $answer;
1.405 albertel 241: }
242:
1.412 www 243: #
1.405 albertel 244: # -------------- Remove all key from the env that start witha lowercase letter
1.412 www 245: # (Which is always a lon-capa value)
246:
1.405 albertel 247: sub cleanenv {
1.412 www 248: # unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; }
249: # unless (&Apache::exists_config_define("MODPERL2")) { return; }
1.405 albertel 250: foreach my $key (keys(%ENV)) {
251: if ($key =~ /^[a-z]/) {
252: delete($ENV{$key});
253: }
254: }
1.374 www 255: }
256:
257: # ------------------------------------------- Transfer profile into environment
258:
259: sub transfer_profile_to_env {
260: my ($lonidsdir,$handle)=@_;
261: my @profile;
262: {
1.448 albertel 263: open(my $idf,"$lonidsdir/$handle.id");
1.374 www 264: flock($idf,LOCK_SH);
265: @profile=<$idf>;
1.448 albertel 266: close($idf);
1.374 www 267: }
268: my $envi;
1.433 matthew 269: my %Remove;
1.374 www 270: for ($envi=0;$envi<=$#profile;$envi++) {
271: chomp($profile[$envi]);
272: my ($envname,$envvalue)=split(/=/,$profile[$envi]);
273: $ENV{$envname} = $envvalue;
1.433 matthew 274: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
275: if ($time < time-300) {
276: $Remove{$key}++;
277: }
278: }
279: }
1.446 albertel 280: $ENV{'user.environment'} = "$lonidsdir/$handle.id";
1.433 matthew 281: foreach my $expired_key (keys(%Remove)) {
282: &delenv($expired_key);
1.374 www 283: }
1.1 albertel 284: }
285:
1.5 www 286: # ---------------------------------------------------------- Append Environment
287:
288: sub appenv {
1.6 www 289: my %newenv=@_;
1.191 harris41 290: foreach (keys %newenv) {
1.35 www 291: if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
292: &logthis("<font color=blue>WARNING: ".
1.151 www 293: "Attempt to modify environment ".$_." to ".$newenv{$_}
294: .'</font>');
1.35 www 295: delete($newenv{$_});
296: } else {
297: $ENV{$_}=$newenv{$_};
298: }
1.191 harris41 299: }
1.95 www 300:
301: my $lockfh;
1.448 albertel 302: unless (open($lockfh,"$ENV{'user.environment'}")) {
303: return 'error: '.$!;
1.95 www 304: }
305: unless (flock($lockfh,LOCK_EX)) {
306: &logthis("<font color=blue>WARNING: ".
307: 'Could not obtain exclusive lock in appenv: '.$!);
1.448 albertel 308: close($lockfh);
1.95 www 309: return 'error: '.$!;
310: }
311:
1.6 www 312: my @oldenv;
313: {
1.448 albertel 314: my $fh;
315: unless (open($fh,"$ENV{'user.environment'}")) {
316: return 'error: '.$!;
317: }
318: @oldenv=<$fh>;
319: close($fh);
1.6 www 320: }
321: for (my $i=0; $i<=$#oldenv; $i++) {
322: chomp($oldenv[$i]);
1.9 www 323: if ($oldenv[$i] ne '') {
1.448 albertel 324: my ($name,$value)=split(/=/,$oldenv[$i]);
325: unless (defined($newenv{$name})) {
326: $newenv{$name}=$value;
327: }
1.9 www 328: }
1.6 www 329: }
330: {
1.448 albertel 331: my $fh;
332: unless (open($fh,">$ENV{'user.environment'}")) {
333: return 'error';
334: }
335: my $newname;
336: foreach $newname (keys %newenv) {
337: print $fh "$newname=$newenv{$newname}\n";
338: }
339: close($fh);
1.56 www 340: }
1.448 albertel 341:
342: close($lockfh);
1.56 www 343: return 'ok';
344: }
345: # ----------------------------------------------------- Delete from Environment
346:
347: sub delenv {
348: my $delthis=shift;
349: my %newenv=();
350: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
351: &logthis("<font color=blue>WARNING: ".
352: "Attempt to delete from environment ".$delthis);
353: return 'error';
354: }
355: my @oldenv;
356: {
1.448 albertel 357: my $fh;
358: unless (open($fh,"$ENV{'user.environment'}")) {
359: return 'error';
360: }
361: unless (flock($fh,LOCK_SH)) {
362: &logthis("<font color=blue>WARNING: ".
363: 'Could not obtain shared lock in delenv: '.$!);
364: close($fh);
365: return 'error: '.$!;
366: }
367: @oldenv=<$fh>;
368: close($fh);
1.56 www 369: }
370: {
1.448 albertel 371: my $fh;
372: unless (open($fh,">$ENV{'user.environment'}")) {
373: return 'error';
374: }
375: unless (flock($fh,LOCK_EX)) {
376: &logthis("<font color=blue>WARNING: ".
377: 'Could not obtain exclusive lock in delenv: '.$!);
378: close($fh);
379: return 'error: '.$!;
380: }
381: foreach (@oldenv) {
1.473 matthew 382: if ($_=~/^$delthis/) {
383: my ($key,undef) = split('=',$_);
384: delete($ENV{$key});
385: } else {
386: print $fh $_;
387: }
1.448 albertel 388: }
389: close($fh);
1.5 www 390: }
391: return 'ok';
1.369 albertel 392: }
393:
394: # ------------------------------------------ Find out current server userload
395: # there is a copy in lond
396: sub userload {
397: my $numusers=0;
398: {
399: opendir(LONIDS,$perlvar{'lonIDsDir'});
400: my $filename;
401: my $curtime=time;
402: while ($filename=readdir(LONIDS)) {
403: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 404: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 405: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 406: }
407: closedir(LONIDS);
408: }
409: my $userloadpercent=0;
410: my $maxuserload=$perlvar{'lonUserLoadLim'};
411: if ($maxuserload) {
1.371 albertel 412: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 413: }
1.372 albertel 414: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 415: return $userloadpercent;
1.283 www 416: }
417:
418: # ------------------------------------------ Fight off request when overloaded
419:
420: sub overloaderror {
421: my ($r,$checkserver)=@_;
422: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
423: my $loadavg;
424: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 425: open(my $loadfile,'/proc/loadavg');
1.283 www 426: $loadavg=<$loadfile>;
427: $loadavg =~ s/\s.*//g;
1.285 matthew 428: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 429: close($loadfile);
1.283 www 430: } else {
431: $loadavg=&reply('load',$checkserver);
432: }
1.285 matthew 433: my $overload=$loadavg-100;
1.283 www 434: if ($overload>0) {
1.285 matthew 435: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 436: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.502 matthew 437: return 409;
1.283 www 438: }
439: return '';
1.5 www 440: }
1.1 albertel 441:
442: # ------------------------------ Find server with least workload from spare.tab
1.11 www 443:
1.1 albertel 444: sub spareserver {
1.370 albertel 445: my ($loadpercent,$userloadpercent) = @_;
1.1 albertel 446: my $tryserver;
447: my $spareserver='';
1.370 albertel 448: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
449: my $lowestserver=$loadpercent > $userloadpercent?
450: $loadpercent : $userloadpercent;
1.1 albertel 451: foreach $tryserver (keys %spareid) {
1.411 albertel 452: my $loadans=reply('load',$tryserver);
453: my $userloadans=reply('userload',$tryserver);
454: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
455: next; #didn't get a number from the server
456: }
457: my $answer;
458: if ($loadans =~ /\d/) {
459: if ($userloadans =~ /\d/) {
460: #both are numbers, pick the bigger one
461: $answer=$loadans > $userloadans?
462: $loadans : $userloadans;
463: } else {
464: $answer = $loadans;
465: }
466: } else {
467: $answer = $userloadans;
468: }
469: if (($answer =~ /\d/) && ($answer<$lowestserver)) {
470: $spareserver="http://$hostname{$tryserver}";
471: $lowestserver=$answer;
472: }
1.370 albertel 473: }
1.1 albertel 474: return $spareserver;
1.202 matthew 475: }
476:
477: # --------------------------------------------- Try to change a user's password
478:
479: sub changepass {
480: my ($uname,$udom,$currentpass,$newpass,$server)=@_;
481: $currentpass = &escape($currentpass);
482: $newpass = &escape($newpass);
483: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
484: $server);
485: if (! $answer) {
486: &logthis("No reply on password change request to $server ".
487: "by $uname in domain $udom.");
488: } elsif ($answer =~ "^ok") {
489: &logthis("$uname in $udom successfully changed their password ".
490: "on $server.");
491: } elsif ($answer =~ "^pwchange_failure") {
492: &logthis("$uname in $udom was unable to change their password ".
493: "on $server. The action was blocked by either lcpasswd ".
494: "or pwchange");
495: } elsif ($answer =~ "^non_authorized") {
496: &logthis("$uname in $udom did not get their password correct when ".
497: "attempting to change it on $server.");
498: } elsif ($answer =~ "^auth_mode_error") {
499: &logthis("$uname in $udom attempted to change their password despite ".
500: "not being locally or internally authenticated on $server.");
501: } elsif ($answer =~ "^unknown_user") {
502: &logthis("$uname in $udom attempted to change their password ".
503: "on $server but were unable to because $server is not ".
504: "their home server.");
505: } elsif ($answer =~ "^refused") {
506: &logthis("$server refused to change $uname in $udom password because ".
507: "it was sent an unencrypted request to change the password.");
508: }
509: return $answer;
1.1 albertel 510: }
511:
1.169 harris41 512: # ----------------------- Try to determine user's current authentication scheme
513:
514: sub queryauthenticate {
515: my ($uname,$udom)=@_;
1.456 albertel 516: my $uhome=&homeserver($uname,$udom);
517: if (!$uhome) {
518: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
519: return 'no_host';
520: }
521: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
522: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
523: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 524: }
1.456 albertel 525: return $answer;
1.169 harris41 526: }
527:
1.1 albertel 528: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 529:
1.1 albertel 530: sub authenticate {
531: my ($uname,$upass,$udom)=@_;
1.12 www 532: $upass=escape($upass);
1.199 www 533: $uname=~s/\W//g;
1.471 albertel 534: my $uhome=&homeserver($uname,$udom);
535: if (!$uhome) {
536: &logthis("User $uname at $udom is unknown in authenticate");
537: return 'no_host';
1.1 albertel 538: }
1.471 albertel 539: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
540: if ($answer eq 'authorized') {
541: &logthis("User $uname at $udom authorized by $uhome");
542: return $uhome;
543: }
544: if ($answer eq 'non_authorized') {
545: &logthis("User $uname at $udom rejected by $uhome");
546: return 'no_host';
1.9 www 547: }
1.471 albertel 548: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 549: return 'no_host';
550: }
551:
552: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 553:
1.1 albertel 554: sub homeserver {
1.230 stredwic 555: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 556: my $index="$uname:$udom";
1.426 albertel 557:
558: my ($result,$cached)=&is_cached(\%homecache,$index,'home',86400);
559: if (defined($cached)) { return $result; }
1.1 albertel 560: my $tryserver;
561: foreach $tryserver (keys %libserv) {
1.230 stredwic 562: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 563: exists($badServerCache{$tryserver}));
1.1 albertel 564: if ($hostdom{$tryserver} eq $udom) {
565: my $answer=reply("home:$udom:$uname",$tryserver);
566: if ($answer eq 'found') {
1.426 albertel 567: return &do_cache(\%homecache,$index,$tryserver,'home');
1.231 stredwic 568: } elsif ($answer eq 'no_host') {
569: $badServerCache{$tryserver}=1;
1.221 matthew 570: }
1.1 albertel 571: }
572: }
573: return 'no_host';
1.70 www 574: }
575:
576: # ------------------------------------- Find the usernames behind a list of IDs
577:
578: sub idget {
579: my ($udom,@ids)=@_;
580: my %returnhash=();
581:
582: my $tryserver;
583: foreach $tryserver (keys %libserv) {
584: if ($hostdom{$tryserver} eq $udom) {
585: my $idlist=join('&',@ids);
586: $idlist=~tr/A-Z/a-z/;
587: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
588: my @answer=();
1.76 www 589: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70 www 590: @answer=split(/\&/,$reply);
591: } ;
592: my $i;
593: for ($i=0;$i<=$#ids;$i++) {
594: if ($answer[$i]) {
595: $returnhash{$ids[$i]}=$answer[$i];
596: }
597: }
598: }
599: }
600: return %returnhash;
601: }
602:
603: # ------------------------------------- Find the IDs behind a list of usernames
604:
605: sub idrget {
606: my ($udom,@unames)=@_;
607: my %returnhash=();
1.191 harris41 608: foreach (@unames) {
1.70 www 609: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191 harris41 610: }
1.70 www 611: return %returnhash;
612: }
613:
614: # ------------------------------- Store away a list of names and associated IDs
615:
616: sub idput {
617: my ($udom,%ids)=@_;
618: my %servers=();
1.191 harris41 619: foreach (keys %ids) {
1.487 albertel 620: &cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70 www 621: my $uhom=&homeserver($_,$udom);
622: if ($uhom ne 'no_host') {
623: my $id=&escape($ids{$_});
624: $id=~tr/A-Z/a-z/;
625: my $unam=&escape($_);
626: if ($servers{$uhom}) {
627: $servers{$uhom}.='&'.$id.'='.$unam;
628: } else {
629: $servers{$uhom}=$id.'='.$unam;
630: }
631: }
1.191 harris41 632: }
633: foreach (keys %servers) {
1.70 www 634: &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191 harris41 635: }
1.344 www 636: }
637:
638: # --------------------------------------------------- Assign a key to a student
639:
640: sub assign_access_key {
1.364 www 641: #
642: # a valid key looks like uname:udom#comments
643: # comments are being appended
644: #
1.498 www 645: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
646: $kdom=
647: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($kdom));
648: $knum=
649: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 650: $cdom=
651: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
652: $cnum=
653: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
654: $udom=$ENV{'user.name'} unless (defined($udom));
655: $uname=$ENV{'user.domain'} unless (defined($uname));
1.498 www 656: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 657: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 658: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 659: # assigned to this person
660: # - this should not happen,
1.345 www 661: # unless something went wrong
662: # the first time around
663: # ready to assign
1.364 www 664: $logentry=$1.'; '.$logentry;
1.496 www 665: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 666: $kdom,$knum) eq 'ok') {
1.345 www 667: # key now belongs to user
1.346 www 668: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 669: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
670: &appenv('environment.'.$envkey => $ckey);
671: return 'ok';
672: } else {
673: return
674: 'error: Count not permanently assign key, will need to be re-entered later.';
675: }
676: } else {
677: return 'error: Could not assign key, try again later.';
678: }
1.364 www 679: } elsif (!$existing{$ckey}) {
1.345 www 680: # the key does not exist
681: return 'error: The key does not exist';
682: } else {
683: # the key is somebody else's
684: return 'error: The key is already in use';
685: }
1.344 www 686: }
687:
1.364 www 688: # ------------------------------------------ put an additional comment on a key
689:
690: sub comment_access_key {
691: #
692: # a valid key looks like uname:udom#comments
693: # comments are being appended
694: #
695: my ($ckey,$cdom,$cnum,$logentry)=@_;
696: $cdom=
697: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
698: $cnum=
699: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
700: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
701: if ($existing{$ckey}) {
702: $existing{$ckey}.='; '.$logentry;
703: # ready to assign
1.367 www 704: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 705: $cdom,$cnum) eq 'ok') {
706: return 'ok';
707: } else {
708: return 'error: Count not store comment.';
709: }
710: } else {
711: # the key does not exist
712: return 'error: The key does not exist';
713: }
714: }
715:
1.344 www 716: # ------------------------------------------------------ Generate a set of keys
717:
718: sub generate_access_keys {
1.364 www 719: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 720: $cdom=
721: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
722: $cnum=
723: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 724: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 725: unless (($cdom) && ($cnum)) { return 0; }
726: if ($number>10000) { return 0; }
727: sleep(2); # make sure don't get same seed twice
728: srand(time()^($$+($$<<15))); # from "Programming Perl"
729: my $total=0;
730: for (my $i=1;$i<=$number;$i++) {
731: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
732: sprintf("%lx",int(100000*rand)).'-'.
733: sprintf("%lx",int(100000*rand));
734: $newkey=~s/1/g/g; # folks mix up 1 and l
735: $newkey=~s/0/h/g; # and also 0 and O
736: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
737: if ($existing{$newkey}) {
738: $i--;
739: } else {
1.364 www 740: if (&put('accesskeys',
741: { $newkey => '# generated '.localtime().
742: ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
743: '; '.$logentry },
744: $cdom,$cnum) eq 'ok') {
1.344 www 745: $total++;
746: }
747: }
748: }
749: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
750: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
751: return $total;
752: }
753:
754: # ------------------------------------------------------- Validate an accesskey
755:
756: sub validate_access_key {
757: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
758: $cdom=
759: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
760: $cnum=
761: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.497 www 762: $udom=$ENV{'user.domain'} unless (defined($udom));
763: $uname=$ENV{'user.name'} unless (defined($uname));
1.345 www 764: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 765: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 766: }
767:
768: # ------------------------------------- Find the section of student in a course
1.298 matthew 769:
770: sub getsection {
771: my ($udom,$unam,$courseid)=@_;
772: $courseid=~s/\_/\//g;
773: $courseid=~s/^(\w)/\/$1/;
774: my %Pending;
775: my %Expired;
776: #
777: # Each role can either have not started yet (pending), be active,
778: # or have expired.
779: #
780: # If there is an active role, we are done.
781: #
782: # If there is more than one role which has not started yet,
783: # choose the one which will start sooner
784: # If there is one role which has not started yet, return it.
785: #
786: # If there is more than one expired role, choose the one which ended last.
787: # If there is a role which has expired, return it.
788: #
789: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
790: &homeserver($unam,$udom)))) {
791: my ($key,$value)=split(/\=/,$_);
792: $key=&unescape($key);
1.479 albertel 793: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 794: my $section=$1;
795: if ($key eq $courseid.'_st') { $section=''; }
796: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
797: my $now=time;
798: if (defined($end) && ($now > $end)) {
799: $Expired{$end}=$section;
800: next;
801: }
802: if (defined($start) && ($now < $start)) {
803: $Pending{$start}=$section;
804: next;
805: }
806: return $section;
807: }
808: #
809: # Presumedly there will be few matching roles from the above
810: # loop and the sorting time will be negligible.
811: if (scalar(keys(%Pending))) {
812: my ($time) = sort {$a <=> $b} keys(%Pending);
813: return $Pending{$time};
814: }
815: if (scalar(keys(%Expired))) {
816: my @sorted = sort {$a <=> $b} keys(%Expired);
817: my $time = pop(@sorted);
818: return $Expired{$time};
819: }
820: return '-1';
821: }
1.70 www 822:
1.452 albertel 823:
824: my $disk_caching_disabled=1;
825:
1.416 albertel 826: sub devalidate_cache {
1.428 albertel 827: my ($cache,$id,$name) = @_;
1.417 albertel 828: delete $$cache{$id.'.time'};
829: delete $$cache{$id};
1.452 albertel 830: if ($disk_caching_disabled) { return; }
1.442 albertel 831: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428 albertel 832: open(DB,"$filename.lock");
833: flock(DB,LOCK_EX);
834: my %hash;
835: if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
1.442 albertel 836: eval <<'EVALBLOCK';
837: delete($hash{$id});
838: delete($hash{$id.'.time'});
839: EVALBLOCK
840: if ($@) {
841: &logthis("<font color='red'>devalidate_cache blew up :$@:$name</font>");
842: unlink($filename);
843: }
1.428 albertel 844: } else {
1.442 albertel 845: if (-e $filename) {
846: &logthis("Unable to tie hash (devalidate cache): $name");
847: unlink($filename);
848: }
1.428 albertel 849: }
850: untie(%hash);
851: flock(DB,LOCK_UN);
852: close(DB);
1.416 albertel 853: }
854:
855: sub is_cached {
1.425 albertel 856: my ($cache,$id,$name,$time) = @_;
1.420 albertel 857: if (!$time) { $time=300; }
1.416 albertel 858: if (!exists($$cache{$id.'.time'})) {
1.428 albertel 859: &load_cache_item($cache,$name,$id);
1.425 albertel 860: }
861: if (!exists($$cache{$id.'.time'})) {
862: # &logthis("Didn't find $id");
1.417 albertel 863: return (undef,undef);
1.416 albertel 864: } else {
1.425 albertel 865: if (time-($$cache{$id.'.time'})>$time) {
1.435 www 866: # &logthis("Devalidating $id - ".time-($$cache{$id.'.time'}));
1.428 albertel 867: &devalidate_cache($cache,$id,$name);
1.417 albertel 868: return (undef,undef);
1.416 albertel 869: }
870: }
1.417 albertel 871: return ($$cache{$id},1);
1.416 albertel 872: }
873:
874: sub do_cache {
1.425 albertel 875: my ($cache,$id,$value,$name) = @_;
1.416 albertel 876: $$cache{$id.'.time'}=time;
1.425 albertel 877: $$cache{$id}=$value;
1.428 albertel 878: # &logthis("Caching $id as :$value:");
879: &save_cache_item($cache,$name,$id);
1.416 albertel 880: # do_cache implictly return the set value
1.425 albertel 881: $$cache{$id};
882: }
883:
1.428 albertel 884: sub save_cache_item {
885: my ($cache,$name,$id)=@_;
1.452 albertel 886: if ($disk_caching_disabled) { return; }
1.428 albertel 887: my $starttime=&Time::HiRes::time();
1.442 albertel 888: # &logthis("Saving :$name:$id");
1.428 albertel 889: my %hash;
1.442 albertel 890: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428 albertel 891: open(DB,"$filename.lock");
892: flock(DB,LOCK_EX);
893: if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
1.442 albertel 894: eval <<'EVALBLOCK';
895: $hash{$id.'.time'}=$$cache{$id.'.time'};
896: $hash{$id}=freeze({'item'=>$$cache{$id}});
897: EVALBLOCK
898: if ($@) {
899: &logthis("<font color='red'>save_cache blew up :$@:$name</font>");
900: unlink($filename);
901: }
1.428 albertel 902: } else {
1.442 albertel 903: if (-e $filename) {
1.445 www 904: &logthis("Unable to tie hash (save cache item): $name ($!)");
1.442 albertel 905: unlink($filename);
906: }
1.428 albertel 907: }
908: untie(%hash);
909: flock(DB,LOCK_UN);
910: close(DB);
911: # &logthis("save_cache_item $name took ".(&Time::HiRes::time()-$starttime));
912: }
913:
914: sub load_cache_item {
915: my ($cache,$name,$id)=@_;
1.452 albertel 916: if ($disk_caching_disabled) { return; }
1.428 albertel 917: my $starttime=&Time::HiRes::time();
918: # &logthis("Before Loading $name for $id size is ".scalar(%$cache));
919: my %hash;
1.442 albertel 920: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428 albertel 921: open(DB,"$filename.lock");
922: flock(DB,LOCK_SH);
923: if (tie(%hash,'GDBM_File',$filename,&GDBM_READER(),0640)) {
1.442 albertel 924: eval <<'EVALBLOCK';
925: if (!%$cache) {
926: my $count;
927: while (my ($key,$value)=each(%hash)) {
928: $count++;
929: if ($key =~ /\.time$/) {
930: $$cache{$key}=$value;
931: } else {
932: my $hashref=thaw($value);
933: $$cache{$key}=$hashref->{'item'};
934: }
1.428 albertel 935: }
1.442 albertel 936: # &logthis("Initial load: $count");
937: } else {
938: my $hashref=thaw($hash{$id});
939: $$cache{$id}=$hashref->{'item'};
940: $$cache{$id.'.time'}=$hash{$id.'.time'};
1.428 albertel 941: }
1.442 albertel 942: EVALBLOCK
943: if ($@) {
944: &logthis("<font color='red'>load_cache blew up :$@:$name</font>");
945: unlink($filename);
946: }
947: } else {
948: if (-e $filename) {
1.445 www 949: &logthis("Unable to tie hash (load cache item): $name ($!)");
1.442 albertel 950: unlink($filename);
1.428 albertel 951: }
952: }
953: untie(%hash);
954: flock(DB,LOCK_UN);
955: close(DB);
956: # &logthis("After Loading $name size is ".scalar(%$cache));
957: # &logthis("load_cache_item $name took ".(&Time::HiRes::time()-$starttime));
958: }
959:
1.70 www 960: sub usection {
961: my ($udom,$unam,$courseid)=@_;
1.416 albertel 962: my $hashid="$udom:$unam:$courseid";
963:
1.425 albertel 964: my ($result,$cached)=&is_cached(\%usectioncache,$hashid,'usection');
1.417 albertel 965: if (defined($cached)) { return $result; }
1.70 www 966: $courseid=~s/\_/\//g;
967: $courseid=~s/^(\w)/\/$1/;
1.191 harris41 968: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
969: &homeserver($unam,$udom)))) {
1.70 www 970: my ($key,$value)=split(/\=/,$_);
971: $key=&unescape($key);
1.479 albertel 972: if ($key=~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/) {
1.70 www 973: my $section=$1;
974: if ($key eq $courseid.'_st') { $section=''; }
975: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
976: my $now=time;
977: my $notactive=0;
978: if ($start) {
979: if ($now<$start) { $notactive=1; }
980: }
981: if ($end) {
982: if ($now>$end) { $notactive=1; }
983: }
1.416 albertel 984: unless ($notactive) {
1.425 albertel 985: return &do_cache(\%usectioncache,$hashid,$section,'usection');
1.416 albertel 986: }
1.70 www 987: }
1.191 harris41 988: }
1.425 albertel 989: return &do_cache(\%usectioncache,$hashid,'-1','usection');
1.70 www 990: }
991:
992: # ------------------------------------- Read an entry from a user's environment
993:
994: sub userenvironment {
995: my ($udom,$unam,@what)=@_;
996: my %returnhash=();
997: my @answer=split(/\&/,
998: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
999: &homeserver($unam,$udom)));
1000: my $i;
1001: for ($i=0;$i<=$#what;$i++) {
1002: $returnhash{$what[$i]}=&unescape($answer[$i]);
1003: }
1004: return %returnhash;
1.1 albertel 1005: }
1006:
1.263 www 1007: # -------------------------------------------------------------------- New chat
1008:
1009: sub chatsend {
1010: my ($newentry,$anon)=@_;
1011: my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1012: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1013: my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1014: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1015: &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
1016: &escape($newentry)),$chome);
1.292 www 1017: }
1018:
1019: # ------------------------------------------ Find current version of a resource
1020:
1021: sub getversion {
1022: my $fname=&clutter(shift);
1023: unless ($fname=~/^\/res\//) { return -1; }
1024: return ¤tversion(&filelocation('',$fname));
1025: }
1026:
1027: sub currentversion {
1028: my $fname=shift;
1.440 www 1029: my ($result,$cached)=&is_cached(\%resversioncache,$fname,'resversion',600);
1030: if (defined($cached)) { return $result; }
1.292 www 1031: my $author=$fname;
1032: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1033: my ($udom,$uname)=split(/\//,$author);
1034: my $home=homeserver($uname,$udom);
1035: if ($home eq 'no_host') {
1036: return -1;
1037: }
1038: my $answer=reply("currentversion:$fname",$home);
1039: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1040: return -1;
1041: }
1.440 www 1042: return &do_cache(\%resversioncache,$fname,$answer,'resversion');
1.263 www 1043: }
1044:
1.1 albertel 1045: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1046:
1.1 albertel 1047: sub subscribe {
1048: my $fname=shift;
1.312 www 1049: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.1 albertel 1050: my $author=$fname;
1051: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1052: my ($udom,$uname)=split(/\//,$author);
1053: my $home=homeserver($uname,$udom);
1.335 albertel 1054: if ($home eq 'no_host') {
1055: return 'not_found';
1.1 albertel 1056: }
1057: my $answer=reply("sub:$fname",$home);
1.64 www 1058: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1059: $answer.=' by '.$home;
1060: }
1.1 albertel 1061: return $answer;
1062: }
1063:
1.8 www 1064: # -------------------------------------------------------------- Replicate file
1065:
1066: sub repcopy {
1067: my $filename=shift;
1.23 www 1068: $filename=~s/\/+/\//g;
1.214 www 1069: if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8 www 1070: my $transname="$filename.in.transfer";
1.17 www 1071: if ((-e $filename) || (-e $transname)) { return OK; }
1.8 www 1072: my $remoteurl=subscribe($filename);
1.64 www 1073: if ($remoteurl =~ /^con_lost by/) {
1074: &logthis("Subscribe returned $remoteurl: $filename");
1.8 www 1075: return HTTP_SERVICE_UNAVAILABLE;
1076: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1077: #&logthis("Subscribe returned not_found: $filename");
1.8 www 1078: return HTTP_NOT_FOUND;
1.64 www 1079: } elsif ($remoteurl =~ /^rejected by/) {
1080: &logthis("Subscribe returned $remoteurl: $filename");
1.8 www 1081: return FORBIDDEN;
1.20 www 1082: } elsif ($remoteurl eq 'directory') {
1083: return OK;
1.8 www 1084: } else {
1.290 www 1085: my $author=$filename;
1086: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1087: my ($udom,$uname)=split(/\//,$author);
1088: my $home=homeserver($uname,$udom);
1089: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1090: my @parts=split(/\//,$filename);
1091: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1092: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1093: &logthis("Malconfiguration for replication: $filename");
1094: return HTTP_BAD_REQUEST;
1095: }
1096: my $count;
1097: for ($count=5;$count<$#parts;$count++) {
1098: $path.="/$parts[$count]";
1099: if ((-e $path)!=1) {
1100: mkdir($path,0777);
1101: }
1102: }
1103: my $ua=new LWP::UserAgent;
1104: my $request=new HTTP::Request('GET',"$remoteurl");
1105: my $response=$ua->request($request,$transname);
1106: if ($response->is_error()) {
1107: unlink($transname);
1108: my $message=$response->status_line;
1.12 www 1109: &logthis("<font color=blue>WARNING:"
1110: ." LWP get: $message: $filename</font>");
1.8 www 1111: return HTTP_SERVICE_UNAVAILABLE;
1112: } else {
1.16 www 1113: if ($remoteurl!~/\.meta$/) {
1114: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1115: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1116: if ($mresponse->is_error()) {
1117: unlink($filename.'.meta');
1118: &logthis(
1119: "<font color=yellow>INFO: No metadata: $filename</font>");
1120: }
1121: }
1.8 www 1122: rename($transname,$filename);
1123: return OK;
1124: }
1.290 www 1125: }
1.8 www 1126: }
1.330 www 1127: }
1128:
1129: # ------------------------------------------------ Get server side include body
1130: sub ssi_body {
1.381 albertel 1131: my ($filelink,%form)=@_;
1.330 www 1132: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1133: &ssi($filelink,%form));
1.451 albertel 1134: $output=~s/^.*?\<body[^\>]*\>//si;
1135: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.331 www 1136: $output=~
1137: s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
1.330 www 1138: return $output;
1.8 www 1139: }
1140:
1.15 www 1141: # --------------------------------------------------------- Server Side Include
1142:
1143: sub ssi {
1144:
1.23 www 1145: my ($fn,%form)=@_;
1.15 www 1146:
1147: my $ua=new LWP::UserAgent;
1.23 www 1148:
1149: my $request;
1150:
1151: if (%form) {
1152: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201 albertel 1153: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1154: } else {
1155: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
1156: }
1157:
1.15 www 1158: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1159: my $response=$ua->request($request);
1160:
1.324 www 1161: return $response->content;
1162: }
1163:
1164: sub externalssi {
1165: my ($url)=@_;
1166: my $ua=new LWP::UserAgent;
1167: my $request=new HTTP::Request('GET',$url);
1168: my $response=$ua->request($request);
1.15 www 1169: return $response->content;
1170: }
1.254 www 1171:
1.492 albertel 1172: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1173:
1174: sub allowuploaded {
1175: my ($srcurl,$url)=@_;
1176: $url=&clutter(&declutter($url));
1177: my $dir=$url;
1178: $dir=~s/\/[^\/]+$//;
1179: my %httpref=();
1180: my $httpurl=&hreflocation('',$url);
1181: $httpref{'httpref.'.$httpurl}=$srcurl;
1182: &Apache::lonnet::appenv(%httpref);
1.254 www 1183: }
1.477 raeburn 1184:
1.478 albertel 1185: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1186: # input: action, courseID, current domain, home server for course, intended
1187: # path to file, source of file.
1.485 raeburn 1188: # output: url to file (if action was uploaddoc),
1189: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1190: #
1.478 albertel 1191: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1192: # course.
1.477 raeburn 1193: #
1.478 albertel 1194: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1195: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1196: # course's home server.
1.477 raeburn 1197: #
1.478 albertel 1198: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1199: # be copied from $source (current location) to
1200: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1201: # and will then be copied to
1202: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1203: # course's home server.
1.485 raeburn 1204: #
1.481 raeburn 1205: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.485 raeburn 1206: # will be retrived from $ENV{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1207: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1208: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1209: # in course's home server.
1210:
1.477 raeburn 1211:
1212: sub process_coursefile {
1213: my ($action,$docuname,$docudom,$docuhome,$file,$source)=@_;
1214: my $fetchresult;
1215: if ($action eq 'propagate') {
1216: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file
1217: ,$docuhome);
1.481 raeburn 1218: } else {
1.477 raeburn 1219: my $fetchresult = '';
1220: my $fpath = '';
1221: my $fname = $file;
1.478 albertel 1222: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1223: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1224: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1225: unless ($fpath eq '') {
1.478 albertel 1226: my @parts=split('/',$fpath);
1.477 raeburn 1227: foreach my $part (@parts) {
1228: $filepath.= '/'.$part;
1229: if ((-e $filepath)!=1) {
1230: mkdir($filepath,0777);
1231: }
1232: }
1233: }
1.481 raeburn 1234: if ($action eq 'copy') {
1235: if ($source eq '') {
1236: $fetchresult = 'no source file';
1237: return $fetchresult;
1238: } else {
1239: my $destination = $filepath.'/'.$fname;
1240: rename($source,$destination);
1241: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1242: $docuhome);
1243: }
1244: } elsif ($action eq 'uploaddoc') {
1245: open(my $fh,'>'.$filepath.'/'.$fname);
1246: print $fh $ENV{'form.'.$source};
1247: close($fh);
1.477 raeburn 1248: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1249: $docuhome);
1.481 raeburn 1250: if ($fetchresult eq 'ok') {
1251: return '/uploaded/'.$fpath.'/'.$fname;
1252: } else {
1253: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1254: ' to host '.$docuhome.': '.$fetchresult);
1255: return '/adm/notfound.html';
1256: }
1.477 raeburn 1257: }
1258: }
1.485 raeburn 1259: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1260: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1261: ' to host '.$docuhome.': '.$fetchresult);
1262: }
1263: return $fetchresult;
1264: }
1265:
1.257 www 1266: # --------------- Take an uploaded file and put it into the userfiles directory
1.259 www 1267: # input: name of form element, coursedoc=1 means this is for the course
1.257 www 1268: # output: url of file in userspace
1269:
1270: sub userfileupload {
1.493 albertel 1271: my ($formname,$coursedoc,$subdir)=@_;
1272: if (!defined($subdir)) { $subdir='unknown'; }
1.477 raeburn 1273: my $fname=$ENV{'form.'.$formname.'.filename'};
1.315 www 1274: # Replace Windows backslashes by forward slashes
1.257 www 1275: $fname=~s/\\/\//g;
1.315 www 1276: # Get rid of everything but the actual filename
1.257 www 1277: $fname=~s/^.*\/([^\/]+)$/$1/;
1.315 www 1278: # Replace spaces by underscores
1279: $fname=~s/\s+/\_/g;
1280: # Replace all other weird characters by nothing
1.317 www 1281: $fname=~s/[^\w\.\-]//g;
1.315 www 1282: # See if there is anything left
1.257 www 1283: unless ($fname) { return 'error: no uploaded file'; }
1.477 raeburn 1284: chop($ENV{'form.'.$formname});
1.258 www 1285: # Create the directory if not present
1.259 www 1286: my $docuname='';
1287: my $docudom='';
1288: my $docuhome='';
1.493 albertel 1289: $fname="$subdir/$fname";
1.259 www 1290: if ($coursedoc) {
1291: $docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1292: $docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1293: $docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.481 raeburn 1294: if ($ENV{'form.folder'} =~ m/^default/) {
1.485 raeburn 1295: return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1.481 raeburn 1296: } else {
1297: $fname=$ENV{'form.folder'}.'/'.$fname;
1.485 raeburn 1298: return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname);
1.481 raeburn 1299: }
1.259 www 1300: } else {
1301: $docuname=$ENV{'user.name'};
1302: $docudom=$ENV{'user.domain'};
1303: $docuhome=$ENV{'user.home'};
1.485 raeburn 1304: return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1.259 www 1305: }
1.271 www 1306: }
1307:
1308: sub finishuserfileupload {
1.477 raeburn 1309: my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1310: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1311: my $filepath=$perlvar{'lonDocRoot'};
1.494 albertel 1312: my ($fnamepath,$file);
1313: $file=$fname;
1314: if ($fname=~m|/|) {
1315: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1316: $path.=$fnamepath.'/';
1317: }
1.259 www 1318: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1319: my $count;
1320: for ($count=4;$count<=$#parts;$count++) {
1321: $filepath.="/$parts[$count]";
1322: if ((-e $filepath)!=1) {
1323: mkdir($filepath,0777);
1324: }
1325: }
1326: # Save the file
1327: {
1.500 albertel 1328: #&Apache::lonnet::logthis("Saving to $filepath $file");
1.494 albertel 1329: open(my $fh,'>'.$filepath.'/'.$file);
1.477 raeburn 1330: print $fh $ENV{'form.'.$formname};
1331: close($fh);
1.258 www 1332: }
1.259 www 1333: # Notify homeserver to grep it
1334: #
1.494 albertel 1335: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1336: if ($fetchresult eq 'ok') {
1.259 www 1337: #
1.258 www 1338: # Return the URL to it
1.494 albertel 1339: return '/uploaded/'.$path.$file;
1.263 www 1340: } else {
1.494 albertel 1341: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1342: ': '.$fetchresult);
1.263 www 1343: return '/adm/notfound.html';
1344: }
1.493 albertel 1345: }
1346:
1347: sub removeuploadedurl {
1348: my ($url)=@_;
1349: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1350: return &Apache::lonnet::removeuserfile($uname,$udom,$fname);
1.490 albertel 1351: }
1352:
1353: sub removeuserfile {
1354: my ($docuname,$docudom,$fname)=@_;
1355: my $home=&homeserver($docuname,$docudom);
1356: return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257 www 1357: }
1.15 www 1358:
1.14 www 1359: # ------------------------------------------------------------------------- Log
1360:
1361: sub log {
1362: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1363: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1364: }
1365:
1366: # ------------------------------------------------------------------ Course Log
1.352 www 1367: #
1368: # This routine flushes several buffers of non-mission-critical nature
1369: #
1.157 www 1370:
1371: sub flushcourselogs {
1.352 www 1372: &logthis('Flushing log buffers');
1373: #
1374: # course logs
1375: # This is a log of all transactions in a course, which can be used
1376: # for data mining purposes
1377: #
1378: # It also collects the courseid database, which lists last transaction
1379: # times and course titles for all courseids
1380: #
1381: my %courseidbuffer=();
1.191 harris41 1382: foreach (keys %courselogs) {
1.157 www 1383: my $crsid=$_;
1.352 www 1384: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1385: &escape($courselogs{$crsid}),
1386: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1387: delete $courselogs{$crsid};
1388: } else {
1389: &logthis('Failed to flush log buffer for '.$crsid);
1390: if (length($courselogs{$crsid})>40000) {
1391: &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
1392: " exceeded maximum size, deleting.</font>");
1393: delete $courselogs{$crsid};
1394: }
1.352 www 1395: }
1396: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1397: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1398: &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
1399: } else {
1400: $courseidbuffer{$coursehombuf{$crsid}}=
1401: &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
1402: }
1.191 harris41 1403: }
1.352 www 1404: #
1405: # Write course id database (reverse lookup) to homeserver of courses
1406: # Is used in pickcourse
1407: #
1408: foreach (keys %courseidbuffer) {
1.353 www 1409: &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352 www 1410: }
1411: #
1412: # File accesses
1413: # Writes to the dynamic metadata of resources to get hit counts, etc.
1414: #
1.449 matthew 1415: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1416: if ($entry =~ /___count$/) {
1417: my ($dom,$name);
1418: ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
1419: if (! defined($dom) || $dom eq '' ||
1420: ! defined($name) || $name eq '') {
1421: my $cid = $ENV{'request.course.id'};
1422: $dom = $ENV{'request.'.$cid.'.domain'};
1423: $name = $ENV{'request.'.$cid.'.num'};
1424: }
1.450 matthew 1425: my $value = $accesshash{$entry};
1426: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1427: my %temphash=($url => $value);
1.449 matthew 1428: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1429: if ($result eq 'ok') {
1430: delete $accesshash{$entry};
1431: } elsif ($result eq 'unknown_cmd') {
1432: # Target server has old code running on it.
1.450 matthew 1433: my %temphash=($entry => $value);
1.449 matthew 1434: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1435: delete $accesshash{$entry};
1436: }
1437: }
1438: } else {
1.458 matthew 1439: my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450 matthew 1440: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1441: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1442: delete $accesshash{$entry};
1443: }
1.185 www 1444: }
1.191 harris41 1445: }
1.352 www 1446: #
1447: # Roles
1448: # Reverse lookup of user roles for course faculty/staff and co-authorship
1449: #
1.349 www 1450: foreach (keys %userrolehash) {
1451: my $entry=$_;
1.351 www 1452: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1453: split(/\:/,$entry);
1454: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1455: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1456: $rudom,$runame) eq 'ok') {
1457: delete $userrolehash{$entry};
1458: }
1459: }
1.186 www 1460: $dumpcount++;
1.157 www 1461: }
1462:
1463: sub courselog {
1464: my $what=shift;
1.158 www 1465: $what=time.':'.$what;
1.157 www 1466: unless ($ENV{'request.course.id'}) { return ''; }
1.188 www 1467: $coursedombuf{$ENV{'request.course.id'}}=
1.352 www 1468: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1469: $coursenumbuf{$ENV{'request.course.id'}}=
1.188 www 1470: $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1471: $coursehombuf{$ENV{'request.course.id'}}=
1472: $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.352 www 1473: $coursedescrbuf{$ENV{'request.course.id'}}=
1474: $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.157 www 1475: if (defined $courselogs{$ENV{'request.course.id'}}) {
1476: $courselogs{$ENV{'request.course.id'}}.='&'.$what;
1477: } else {
1478: $courselogs{$ENV{'request.course.id'}}.=$what;
1479: }
1.458 matthew 1480: if (length($courselogs{$ENV{'request.course.id'}})>4048) {
1.157 www 1481: &flushcourselogs();
1482: }
1.158 www 1483: }
1484:
1485: sub courseacclog {
1486: my $fnsymb=shift;
1487: unless ($ENV{'request.course.id'}) { return ''; }
1488: my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.408 www 1489: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187 www 1490: $what.=':POST';
1.191 harris41 1491: foreach (keys %ENV) {
1.158 www 1492: if ($_=~/^form\.(.*)/) {
1493: $what.=':'.$1.'='.$ENV{$_};
1494: }
1.191 harris41 1495: }
1.158 www 1496: }
1497: &courselog($what);
1.149 www 1498: }
1499:
1.185 www 1500: sub countacc {
1501: my $url=&declutter(shift);
1.458 matthew 1502: return if (! defined($url) || $url eq '');
1.185 www 1503: unless ($ENV{'request.course.id'}) { return ''; }
1504: $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 1505: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 1506: $accesshash{$key}++;
1.185 www 1507: }
1.349 www 1508:
1.361 www 1509: sub linklog {
1510: my ($from,$to)=@_;
1511: $from=&declutter($from);
1512: $to=&declutter($to);
1513: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1514: $accesshash{$to.'___'.$from.'___goto'}=1;
1515: }
1516:
1.349 www 1517: sub userrolelog {
1518: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1519: if (($trole=~/^ca/) || ($trole=~/^in/) ||
1520: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.469 www 1521: ($trole=~/^cr/) || ($trole=~/^ta/)) {
1.350 www 1522: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1523: $userrolehash
1524: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 1525: =$tend.':'.$tstart;
1526: }
1.351 www 1527: }
1528:
1529: sub get_course_adv_roles {
1530: my $cid=shift;
1531: $cid=$ENV{'request.course.id'} unless (defined($cid));
1532: my %coursehash=&coursedescription($cid);
1.470 www 1533: my %nothide=();
1534: foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1535: $nothide{join(':',split(/[\@\:]/,$_))}=1;
1536: }
1.351 www 1537: my %returnhash=();
1538: my %dumphash=
1539: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1540: my $now=time;
1541: foreach (keys %dumphash) {
1542: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1543: if (($tstart) && ($tstart<0)) { next; }
1544: if (($tend) && ($tend<$now)) { next; }
1545: if (($tstart) && ($now<$tstart)) { next; }
1546: my ($role,$username,$domain,$section)=split(/\:/,$_);
1.470 www 1547: if ((&privileged($username,$domain)) &&
1548: (!$nothide{$username.':'.$domain})) { next; }
1.351 www 1549: my $key=&plaintext($role);
1550: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1551: if ($returnhash{$key}) {
1552: $returnhash{$key}.=','.$username.':'.$domain;
1553: } else {
1554: $returnhash{$key}=$username.':'.$domain;
1555: }
1.400 www 1556: }
1557: return %returnhash;
1558: }
1559:
1560: sub get_my_roles {
1561: my ($uname,$udom)=@_;
1562: unless (defined($uname)) { $uname=$ENV{'user.name'}; }
1563: unless (defined($udom)) { $udom=$ENV{'user.domain'}; }
1564: my %dumphash=
1565: &dump('nohist_userroles',$udom,$uname);
1566: my %returnhash=();
1567: my $now=time;
1568: foreach (keys %dumphash) {
1569: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1570: if (($tstart) && ($tstart<0)) { next; }
1571: if (($tend) && ($tend<$now)) { next; }
1572: if (($tstart) && ($now<$tstart)) { next; }
1573: my ($role,$username,$domain,$section)=split(/\:/,$_);
1574: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373 www 1575: }
1576: return %returnhash;
1.399 www 1577: }
1578:
1579: # ----------------------------------------------------- Frontpage Announcements
1580: #
1581: #
1582:
1583: sub postannounce {
1584: my ($server,$text)=@_;
1585: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1586: unless ($text=~/\w/) { $text=''; }
1587: return &reply('setannounce:'.&escape($text),$server);
1588: }
1589:
1590: sub getannounce {
1.448 albertel 1591:
1592: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 1593: my $announcement='';
1594: while (<$fh>) { $announcement .=$_; }
1.448 albertel 1595: close($fh);
1.399 www 1596: if ($announcement=~/\w/) {
1597: return
1598: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1599: '<tr><td bgcolor="#FFFFFF"><pre>'.$announcement.'</pre></td></tr></table>';
1600: } else {
1601: return '';
1602: }
1603: } else {
1604: return '';
1605: }
1.351 www 1606: }
1.353 www 1607:
1608: # ---------------------------------------------------------- Course ID routines
1609: # Deal with domain's nohist_courseid.db files
1610: #
1611:
1612: sub courseidput {
1613: my ($domain,$what,$coursehome)=@_;
1614: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
1615: }
1616:
1617: sub courseiddump {
1.511 raeburn 1618: my ($domfilter,$descfilter,$sincefilter,$hostidflag,$hostidref)=@_;
1.353 www 1619: my %returnhash=();
1.355 www 1620: unless ($domfilter) { $domfilter=''; }
1.353 www 1621: foreach my $tryserver (keys %libserv) {
1.511 raeburn 1622: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506 raeburn 1623: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1624: foreach (
1625: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.354 www 1626: $sincefilter.':'.&escape($descfilter),
1627: $tryserver))) {
1.506 raeburn 1628: my ($key,$value)=split(/\=/,$_);
1629: if (($key) && ($value)) {
1630: $returnhash{&unescape($key)}=&unescape($value);
1631: }
1.353 www 1632: }
1633: }
1634: }
1635: }
1636: return %returnhash;
1637: }
1638:
1639: #
1.149 www 1640: # ----------------------------------------------------------- Check out an item
1641:
1.504 albertel 1642: sub get_first_access {
1643: my ($type,$argsymb)=@_;
1644: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
1645: if ($argsymb) { $symb=$argsymb; }
1646: my ($map,$id,$res)=&decode_symb($symb);
1647: if ($type eq 'map') { $res=$map; }
1648: my %times=&get('firstaccesstimes',[$res],$udom,$uname);
1649: return $times{$res};
1650: }
1651:
1652: sub set_first_access {
1653: my ($type)=@_;
1654: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
1655: my ($map,$id,$res)=&decode_symb($symb);
1656: if ($type eq 'map') { $res=$map; }
1.505 albertel 1657: my $firstaccess=&get_first_access($type);
1658: if (!$firstaccess) {
1659: return &put('firstaccesstimes',{$res=>time},$udom,$uname);
1660: }
1661: return 'already_set';
1.504 albertel 1662: }
1663:
1.149 www 1664: sub checkout {
1665: my ($symb,$tuname,$tudom,$tcrsid)=@_;
1666: my $now=time;
1667: my $lonhost=$perlvar{'lonHostID'};
1668: my $infostr=&escape(
1.234 www 1669: 'CHECKOUTTOKEN&'.
1.149 www 1670: $tuname.'&'.
1671: $tudom.'&'.
1672: $tcrsid.'&'.
1673: $symb.'&'.
1674: $now.'&'.$ENV{'REMOTE_ADDR'});
1675: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 1676: if ($token=~/^error\:/) {
1677: &logthis("<font color=blue>WARNING: ".
1678: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
1679: "</font>");
1680: return '';
1681: }
1682:
1.149 www 1683: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
1684: $token=~tr/a-z/A-Z/;
1685:
1.153 www 1686: my %infohash=('resource.0.outtoken' => $token,
1687: 'resource.0.checkouttime' => $now,
1688: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 1689:
1690: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1691: return '';
1.151 www 1692: } else {
1693: &logthis("<font color=blue>WARNING: ".
1694: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
1695: "</font>");
1.149 www 1696: }
1697:
1698: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1699: &escape('Checkout '.$infostr.' - '.
1700: $token)) ne 'ok') {
1701: return '';
1.151 www 1702: } else {
1703: &logthis("<font color=blue>WARNING: ".
1704: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
1705: "</font>");
1.149 www 1706: }
1.151 www 1707: return $token;
1.149 www 1708: }
1709:
1710: # ------------------------------------------------------------ Check in an item
1711:
1712: sub checkin {
1713: my $token=shift;
1.150 www 1714: my $now=time;
1715: my ($ta,$tb,$lonhost)=split(/\*/,$token);
1716: $lonhost=~tr/A-Z/a-z/;
1717: my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
1718: $dtoken=~s/\W/\_/g;
1.234 www 1719: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 1720: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
1721:
1.154 www 1722: unless (($tuname) && ($tudom)) {
1723: &logthis('Check in '.$token.' ('.$dtoken.') failed');
1724: return '';
1725: }
1726:
1727: unless (&allowed('mgr',$tcrsid)) {
1728: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1729: $ENV{'user.name'}.' - '.$ENV{'user.domain'});
1730: return '';
1731: }
1732:
1.153 www 1733: my %infohash=('resource.0.intoken' => $token,
1734: 'resource.0.checkintime' => $now,
1735: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 1736:
1737: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1738: return '';
1739: }
1740:
1741: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1742: &escape('Checkin - '.$token)) ne 'ok') {
1743: return '';
1744: }
1745:
1746: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 1747: }
1748:
1749: # --------------------------------------------- Set Expire Date for Spreadsheet
1750:
1751: sub expirespread {
1752: my ($uname,$udom,$stype,$usymb)=@_;
1753: my $cid=$ENV{'request.course.id'};
1754: if ($cid) {
1755: my $now=time;
1756: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1757: return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1758: $ENV{'course.'.$cid.'.num'}.
1759: ':nohist_expirationdates:'.
1760: &escape($key).'='.$now,
1761: $ENV{'course.'.$cid.'.home'})
1762: }
1763: return 'ok';
1.14 www 1764: }
1765:
1.109 www 1766: # ----------------------------------------------------- Devalidate Spreadsheets
1767:
1768: sub devalidate {
1.325 www 1769: my ($symb,$uname,$udom)=@_;
1.109 www 1770: my $cid=$ENV{'request.course.id'};
1771: if ($cid) {
1.391 matthew 1772: # delete the stored spreadsheets for
1773: # - the student level sheet of this user in course's homespace
1774: # - the assessment level sheet for this resource
1775: # for this user in user's homespace
1.325 www 1776: my $key=$uname.':'.$udom.':';
1.109 www 1777: my $status=
1.299 matthew 1778: &del('nohist_calculatedsheets',
1.391 matthew 1779: [$key.'studentcalc:'],
1.133 albertel 1780: $ENV{'course.'.$cid.'.domain'},
1781: $ENV{'course.'.$cid.'.num'})
1782: .' '.
1783: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 1784: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 1785: unless ($status eq 'ok ok') {
1786: &logthis('Could not devalidate spreadsheet '.
1.325 www 1787: $uname.' at '.$udom.' for '.
1.109 www 1788: $symb.': '.$status);
1.133 albertel 1789: }
1.109 www 1790: }
1791: }
1792:
1.265 albertel 1793: sub get_scalar {
1794: my ($string,$end) = @_;
1795: my $value;
1796: if ($$string =~ s/^([^&]*?)($end)/$2/) {
1797: $value = $1;
1798: } elsif ($$string =~ s/^([^&]*?)&//) {
1799: $value = $1;
1800: }
1801: return &unescape($value);
1802: }
1803:
1804: sub array2str {
1805: my (@array) = @_;
1806: my $result=&arrayref2str(\@array);
1807: $result=~s/^__ARRAY_REF__//;
1808: $result=~s/__END_ARRAY_REF__$//;
1809: return $result;
1810: }
1811:
1.204 albertel 1812: sub arrayref2str {
1813: my ($arrayref) = @_;
1.265 albertel 1814: my $result='__ARRAY_REF__';
1.204 albertel 1815: foreach my $elem (@$arrayref) {
1.265 albertel 1816: if(ref($elem) eq 'ARRAY') {
1817: $result.=&arrayref2str($elem).'&';
1818: } elsif(ref($elem) eq 'HASH') {
1819: $result.=&hashref2str($elem).'&';
1820: } elsif(ref($elem)) {
1821: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 1822: } else {
1823: $result.=&escape($elem).'&';
1824: }
1825: }
1826: $result=~s/\&$//;
1.265 albertel 1827: $result .= '__END_ARRAY_REF__';
1.204 albertel 1828: return $result;
1829: }
1830:
1.168 albertel 1831: sub hash2str {
1.204 albertel 1832: my (%hash) = @_;
1833: my $result=&hashref2str(\%hash);
1.265 albertel 1834: $result=~s/^__HASH_REF__//;
1835: $result=~s/__END_HASH_REF__$//;
1.204 albertel 1836: return $result;
1837: }
1838:
1839: sub hashref2str {
1840: my ($hashref)=@_;
1.265 albertel 1841: my $result='__HASH_REF__';
1.495 albertel 1842: foreach (sort(keys(%$hashref))) {
1.204 albertel 1843: if (ref($_) eq 'ARRAY') {
1.265 albertel 1844: $result.=&arrayref2str($_).'=';
1.204 albertel 1845: } elsif (ref($_) eq 'HASH') {
1.265 albertel 1846: $result.=&hashref2str($_).'=';
1.204 albertel 1847: } elsif (ref($_)) {
1.265 albertel 1848: $result.='=';
1849: #print("Got a ref of ".(ref($_))." skipping.");
1.204 albertel 1850: } else {
1.265 albertel 1851: if ($_) {$result.=&escape($_).'=';} else { last; }
1.204 albertel 1852: }
1853:
1.265 albertel 1854: if(ref($hashref->{$_}) eq 'ARRAY') {
1855: $result.=&arrayref2str($hashref->{$_}).'&';
1856: } elsif(ref($hashref->{$_}) eq 'HASH') {
1857: $result.=&hashref2str($hashref->{$_}).'&';
1858: } elsif(ref($hashref->{$_})) {
1859: $result.='&';
1860: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204 albertel 1861: } else {
1.265 albertel 1862: $result.=&escape($hashref->{$_}).'&';
1.204 albertel 1863: }
1864: }
1.168 albertel 1865: $result=~s/\&$//;
1.265 albertel 1866: $result .= '__END_HASH_REF__';
1.168 albertel 1867: return $result;
1868: }
1869:
1870: sub str2hash {
1.265 albertel 1871: my ($string)=@_;
1872: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
1873: return %$hash;
1874: }
1875:
1876: sub str2hashref {
1.168 albertel 1877: my ($string) = @_;
1.265 albertel 1878:
1879: my %hash;
1880:
1881: if($string !~ /^__HASH_REF__/) {
1882: if (! ($string eq '' || !defined($string))) {
1883: $hash{'error'}='Not hash reference';
1884: }
1885: return (\%hash, $string);
1886: }
1887:
1888: $string =~ s/^__HASH_REF__//;
1889:
1890: while($string !~ /^__END_HASH_REF__/) {
1891: #key
1892: my $key='';
1893: if($string =~ /^__HASH_REF__/) {
1894: ($key, $string)=&str2hashref($string);
1895: if(defined($key->{'error'})) {
1896: $hash{'error'}='Bad data';
1897: return (\%hash, $string);
1898: }
1899: } elsif($string =~ /^__ARRAY_REF__/) {
1900: ($key, $string)=&str2arrayref($string);
1901: if($key->[0] eq 'Array reference error') {
1902: $hash{'error'}='Bad data';
1903: return (\%hash, $string);
1904: }
1905: } else {
1906: $string =~ s/^(.*?)=//;
1.267 albertel 1907: $key=&unescape($1);
1.265 albertel 1908: }
1909: $string =~ s/^=//;
1910:
1911: #value
1912: my $value='';
1913: if($string =~ /^__HASH_REF__/) {
1914: ($value, $string)=&str2hashref($string);
1915: if(defined($value->{'error'})) {
1916: $hash{'error'}='Bad data';
1917: return (\%hash, $string);
1918: }
1919: } elsif($string =~ /^__ARRAY_REF__/) {
1920: ($value, $string)=&str2arrayref($string);
1921: if($value->[0] eq 'Array reference error') {
1922: $hash{'error'}='Bad data';
1923: return (\%hash, $string);
1924: }
1925: } else {
1926: $value=&get_scalar(\$string,'__END_HASH_REF__');
1927: }
1928: $string =~ s/^&//;
1929:
1930: $hash{$key}=$value;
1.204 albertel 1931: }
1.265 albertel 1932:
1933: $string =~ s/^__END_HASH_REF__//;
1934:
1935: return (\%hash, $string);
1.204 albertel 1936: }
1937:
1938: sub str2array {
1.265 albertel 1939: my ($string)=@_;
1940: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
1941: return @$array;
1942: }
1943:
1944: sub str2arrayref {
1.204 albertel 1945: my ($string) = @_;
1.265 albertel 1946: my @array;
1947:
1948: if($string !~ /^__ARRAY_REF__/) {
1949: if (! ($string eq '' || !defined($string))) {
1950: $array[0]='Array reference error';
1951: }
1952: return (\@array, $string);
1953: }
1954:
1955: $string =~ s/^__ARRAY_REF__//;
1956:
1957: while($string !~ /^__END_ARRAY_REF__/) {
1958: my $value='';
1959: if($string =~ /^__HASH_REF__/) {
1960: ($value, $string)=&str2hashref($string);
1961: if(defined($value->{'error'})) {
1962: $array[0] ='Array reference error';
1963: return (\@array, $string);
1964: }
1965: } elsif($string =~ /^__ARRAY_REF__/) {
1966: ($value, $string)=&str2arrayref($string);
1967: if($value->[0] eq 'Array reference error') {
1968: $array[0] ='Array reference error';
1969: return (\@array, $string);
1970: }
1971: } else {
1972: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
1973: }
1974: $string =~ s/^&//;
1975:
1976: push(@array, $value);
1.191 harris41 1977: }
1.265 albertel 1978:
1979: $string =~ s/^__END_ARRAY_REF__//;
1980:
1981: return (\@array, $string);
1.168 albertel 1982: }
1983:
1.167 albertel 1984: # -------------------------------------------------------------------Temp Store
1985:
1.168 albertel 1986: sub tmpreset {
1987: my ($symb,$namespace,$domain,$stuname) = @_;
1988: if (!$symb) {
1989: $symb=&symbread();
1.380 albertel 1990: if (!$symb) { $symb= $ENV{'request.url'}; }
1.168 albertel 1991: }
1992: $symb=escape($symb);
1993:
1994: if (!$namespace) { $namespace=$ENV{'request.state'}; }
1995: $namespace=~s/\//\_/g;
1996: $namespace=~s/\W//g;
1997:
1998: #FIXME needs to do something for /pub resources
1999: if (!$domain) { $domain=$ENV{'user.domain'}; }
2000: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2001: my $path=$perlvar{'lonDaemons'}.'/tmp';
2002: my %hash;
2003: if (tie(%hash,'GDBM_File',
2004: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2005: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2006: foreach my $key (keys %hash) {
1.180 albertel 2007: if ($key=~ /:$symb/) {
1.168 albertel 2008: delete($hash{$key});
2009: }
2010: }
2011: }
2012: }
2013:
1.167 albertel 2014: sub tmpstore {
1.168 albertel 2015: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2016:
2017: if (!$symb) {
2018: $symb=&symbread();
2019: if (!$symb) { $symb= $ENV{'request.url'}; }
2020: }
2021: $symb=escape($symb);
2022:
2023: if (!$namespace) {
2024: # I don't think we would ever want to store this for a course.
2025: # it seems this will only be used if we don't have a course.
2026: #$namespace=$ENV{'request.course.id'};
2027: #if (!$namespace) {
2028: $namespace=$ENV{'request.state'};
2029: #}
2030: }
2031: $namespace=~s/\//\_/g;
2032: $namespace=~s/\W//g;
2033: #FIXME needs to do something for /pub resources
2034: if (!$domain) { $domain=$ENV{'user.domain'}; }
2035: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2036: my $now=time;
2037: my %hash;
2038: my $path=$perlvar{'lonDaemons'}.'/tmp';
2039: if (tie(%hash,'GDBM_File',
2040: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2041: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2042: $hash{"version:$symb"}++;
2043: my $version=$hash{"version:$symb"};
2044: my $allkeys='';
2045: foreach my $key (keys(%$storehash)) {
2046: $allkeys.=$key.':';
2047: $hash{"$version:$symb:$key"}=$$storehash{$key};
2048: }
2049: $hash{"$version:$symb:timestamp"}=$now;
2050: $allkeys.='timestamp';
2051: $hash{"$version:keys:$symb"}=$allkeys;
2052: if (untie(%hash)) {
2053: return 'ok';
2054: } else {
2055: return "error:$!";
2056: }
2057: } else {
2058: return "error:$!";
2059: }
2060: }
1.167 albertel 2061:
1.168 albertel 2062: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2063:
1.168 albertel 2064: sub tmprestore {
2065: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2066:
1.168 albertel 2067: if (!$symb) {
2068: $symb=&symbread();
2069: if (!$symb) { $symb= $ENV{'request.url'}; }
2070: }
2071: $symb=escape($symb);
2072:
2073: if (!$namespace) { $namespace=$ENV{'request.state'}; }
2074: #FIXME needs to do something for /pub resources
2075: if (!$domain) { $domain=$ENV{'user.domain'}; }
2076: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2077:
2078: my %returnhash;
2079: $namespace=~s/\//\_/g;
2080: $namespace=~s/\W//g;
2081: my %hash;
2082: my $path=$perlvar{'lonDaemons'}.'/tmp';
2083: if (tie(%hash,'GDBM_File',
2084: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2085: &GDBM_READER(),0640)) {
1.168 albertel 2086: my $version=$hash{"version:$symb"};
2087: $returnhash{'version'}=$version;
2088: my $scope;
2089: for ($scope=1;$scope<=$version;$scope++) {
2090: my $vkeys=$hash{"$scope:keys:$symb"};
2091: my @keys=split(/:/,$vkeys);
2092: my $key;
2093: $returnhash{"$scope:keys"}=$vkeys;
2094: foreach $key (@keys) {
2095: $returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
2096: $returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167 albertel 2097: }
2098: }
1.168 albertel 2099: if (!(untie(%hash))) {
2100: return "error:$!";
2101: }
2102: } else {
2103: return "error:$!";
2104: }
2105: return %returnhash;
1.167 albertel 2106: }
2107:
1.9 www 2108: # ----------------------------------------------------------------------- Store
2109:
2110: sub store {
1.124 www 2111: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2112: my $home='';
2113:
1.168 albertel 2114: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2115:
1.213 www 2116: $symb=&symbclean($symb);
1.122 albertel 2117: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2118:
1.325 www 2119: if (!$domain) { $domain=$ENV{'user.domain'}; }
2120: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2121:
2122: &devalidate($symb,$stuname,$domain);
1.109 www 2123:
2124: $symb=escape($symb);
1.187 www 2125: if (!$namespace) {
2126: unless ($namespace=$ENV{'request.course.id'}) {
2127: return '';
2128: }
2129: }
1.122 albertel 2130: if (!$home) { $home=$ENV{'user.home'}; }
1.447 www 2131:
2132: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2133: $$storehash{'host'}=$perlvar{'lonHostID'};
2134:
1.12 www 2135: my $namevalue='';
1.191 harris41 2136: foreach (keys %$storehash) {
1.122 albertel 2137: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191 harris41 2138: }
1.12 www 2139: $namevalue=~s/\&$//;
1.187 www 2140: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2141: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2142: }
2143:
1.47 www 2144: # -------------------------------------------------------------- Critical Store
2145:
2146: sub cstore {
1.124 www 2147: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2148: my $home='';
2149:
1.168 albertel 2150: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2151:
1.213 www 2152: $symb=&symbclean($symb);
1.122 albertel 2153: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2154:
1.325 www 2155: if (!$domain) { $domain=$ENV{'user.domain'}; }
2156: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2157:
2158: &devalidate($symb,$stuname,$domain);
1.109 www 2159:
2160: $symb=escape($symb);
1.187 www 2161: if (!$namespace) {
2162: unless ($namespace=$ENV{'request.course.id'}) {
2163: return '';
2164: }
2165: }
1.122 albertel 2166: if (!$home) { $home=$ENV{'user.home'}; }
1.447 www 2167:
2168: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2169: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2170:
1.47 www 2171: my $namevalue='';
1.191 harris41 2172: foreach (keys %$storehash) {
1.122 albertel 2173: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191 harris41 2174: }
1.47 www 2175: $namevalue=~s/\&$//;
1.187 www 2176: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2177: return critical
2178: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2179: }
2180:
1.9 www 2181: # --------------------------------------------------------------------- Restore
2182:
2183: sub restore {
1.124 www 2184: my ($symb,$namespace,$domain,$stuname) = @_;
2185: my $home='';
2186:
1.168 albertel 2187: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2188:
1.122 albertel 2189: if (!$symb) {
2190: unless ($symb=escape(&symbread())) { return ''; }
2191: } else {
1.213 www 2192: $symb=&escape(&symbclean($symb));
1.122 albertel 2193: }
1.188 www 2194: if (!$namespace) {
2195: unless ($namespace=$ENV{'request.course.id'}) {
2196: return '';
2197: }
2198: }
1.122 albertel 2199: if (!$domain) { $domain=$ENV{'user.domain'}; }
2200: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2201: if (!$home) { $home=$ENV{'user.home'}; }
2202: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2203:
1.12 www 2204: my %returnhash=();
1.191 harris41 2205: foreach (split(/\&/,$answer)) {
1.12 www 2206: my ($name,$value)=split(/\=/,$_);
2207: $returnhash{&unescape($name)}=&unescape($value);
1.191 harris41 2208: }
1.75 www 2209: my $version;
2210: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191 harris41 2211: foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75 www 2212: $returnhash{$_}=$returnhash{$version.':'.$_};
1.191 harris41 2213: }
1.75 www 2214: }
1.13 www 2215: return %returnhash;
1.34 www 2216: }
2217:
2218: # ---------------------------------------------------------- Course Description
2219:
2220: sub coursedescription {
2221: my $courseid=shift;
2222: $courseid=~s/^\///;
1.49 www 2223: $courseid=~s/\_/\//g;
1.34 www 2224: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2225: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2226: my $normalid=$cdomain.'_'.$cnum;
2227: # need to always cache even if we get errors otherwise we keep
2228: # trying and trying and trying to get the course description.
2229: my %envhash=();
2230: my %returnhash=();
2231: $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34 www 2232: if ($chome ne 'no_host') {
1.302 albertel 2233: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2234: if (!exists($returnhash{'con_lost'})) {
2235: $returnhash{'home'}= $chome;
2236: $returnhash{'domain'} = $cdomain;
2237: $returnhash{'num'} = $cnum;
1.130 albertel 2238: while (my ($name,$value) = each %returnhash) {
1.53 www 2239: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2240: }
1.270 www 2241: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2242: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38 www 2243: $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2244: $envhash{'course.'.$normalid.'.home'}=$chome;
2245: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2246: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2247: }
2248: }
1.302 albertel 2249: &appenv(%envhash);
2250: return %returnhash;
1.461 www 2251: }
2252:
2253: # -------------------------------------------------See if a user is privileged
2254:
2255: sub privileged {
2256: my ($username,$domain)=@_;
2257: my $rolesdump=&reply("dump:$domain:$username:roles",
2258: &homeserver($username,$domain));
2259: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2260: my $now=time;
2261: if ($rolesdump ne '') {
2262: foreach (split(/&/,$rolesdump)) {
2263: if ($_!~/^rolesdef\&/) {
2264: my ($area,$role)=split(/=/,$_);
2265: $area=~s/\_\w\w$//;
2266: my ($trole,$tend,$tstart)=split(/_/,$role);
2267: if (($trole eq 'dc') || ($trole eq 'su')) {
2268: my $active=1;
2269: if ($tend) {
2270: if ($tend<$now) { $active=0; }
2271: }
2272: if ($tstart) {
2273: if ($tstart>$now) { $active=0; }
2274: }
2275: if ($active) { return 1; }
2276: }
2277: }
2278: }
2279: }
2280: return 0;
1.9 www 2281: }
1.1 albertel 2282:
1.103 harris41 2283: # -------------------------------------------------------- Get user privileges
1.11 www 2284:
2285: sub rolesinit {
2286: my ($domain,$username,$authhost)=@_;
2287: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 2288: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 2289: my %allroles=();
2290: my %thesepriv=();
2291: my $now=time;
1.21 www 2292: my $userroles="user.login.time=$now\n";
1.11 www 2293: my $thesestr;
2294:
2295: if ($rolesdump ne '') {
1.191 harris41 2296: foreach (split(/&/,$rolesdump)) {
1.21 www 2297: if ($_!~/^rolesdef\&/) {
1.11 www 2298: my ($area,$role)=split(/=/,$_);
1.21 www 2299: $area=~s/\_\w\w$//;
1.11 www 2300: my ($trole,$tend,$tstart)=split(/_/,$role);
1.21 www 2301: $userroles.='user.role.'.$trole.'.'.$area.'='.
2302: $tstart.'.'.$tend."\n";
1.349 www 2303: # log the associated role with the area
2304: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.11 www 2305: if ($tend!=0) {
2306: if ($tend<$now) {
2307: $trole='';
2308: }
2309: }
2310: if ($tstart!=0) {
2311: if ($tstart>$now) {
2312: $trole='';
2313: }
2314: }
2315: if (($area ne '') && ($trole ne '')) {
1.347 albertel 2316: my $spec=$trole.'.'.$area;
2317: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2318: if ($trole =~ /^cr\//) {
2319: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.392 www 2320: my $homsvr=homeserver($rauthor,$rdomain);
1.347 albertel 2321: if ($hostname{$homsvr} ne '') {
1.392 www 2322: my ($rdummy,$roledef)=
2323: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2324:
2325: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.347 albertel 2326: my ($syspriv,$dompriv,$coursepriv)=
1.392 www 2327: split(/\_/,$roledef);
1.347 albertel 2328: if (defined($syspriv)) {
2329: $allroles{'cm./'}.=':'.$syspriv;
2330: $allroles{$spec.'./'}.=':'.$syspriv;
2331: }
2332: if ($tdomain ne '') {
2333: if (defined($dompriv)) {
2334: $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2335: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2336: }
2337: if ($trest ne '') {
2338: if (defined($coursepriv)) {
2339: $allroles{'cm.'.$area}.=':'.$coursepriv;
2340: $allroles{$spec.'.'.$area}.=':'.$coursepriv;
2341: }
2342: }
2343: }
2344: }
2345: }
2346: } else {
2347: if (defined($pr{$trole.':s'})) {
2348: $allroles{'cm./'}.=':'.$pr{$trole.':s'};
2349: $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2350: }
2351: if ($tdomain ne '') {
2352: if (defined($pr{$trole.':d'})) {
2353: $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2354: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2355: }
2356: if ($trest ne '') {
2357: if (defined($pr{$trole.':c'})) {
2358: $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2359: $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2360: }
2361: }
2362: }
2363: }
1.12 www 2364: }
2365: }
1.191 harris41 2366: }
1.125 www 2367: my $adv=0;
1.128 www 2368: my $author=0;
1.191 harris41 2369: foreach (keys %allroles) {
1.11 www 2370: %thesepriv=();
1.146 www 2371: if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128 www 2372: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191 harris41 2373: foreach (split(/:/,$allroles{$_})) {
1.11 www 2374: if ($_ ne '') {
1.103 harris41 2375: my ($privilege,$restrictions)=split(/&/,$_);
1.11 www 2376: if ($restrictions eq '') {
1.103 harris41 2377: $thesepriv{$privilege}='F';
1.11 www 2378: } else {
1.103 harris41 2379: if ($thesepriv{$privilege} ne 'F') {
2380: $thesepriv{$privilege}.=$restrictions;
1.11 www 2381: }
2382: }
2383: }
1.191 harris41 2384: }
1.11 www 2385: $thesestr='';
1.191 harris41 2386: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11 www 2387: $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191 harris41 2388: }
1.128 www 2389: $userroles.='user.adv='.$adv."\n".
2390: 'user.author='.$author."\n";
1.126 www 2391: $ENV{'user.adv'}=$adv;
1.11 www 2392: }
2393: return $userroles;
2394: }
2395:
1.12 www 2396: # --------------------------------------------------------------- get interface
2397:
2398: sub get {
1.131 albertel 2399: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2400: my $items='';
1.191 harris41 2401: foreach (@$storearr) {
1.12 www 2402: $items.=escape($_).'&';
1.191 harris41 2403: }
1.12 www 2404: $items=~s/\&$//;
1.131 albertel 2405: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2406: if (!$uname) { $uname=$ENV{'user.name'}; }
2407: my $uhome=&homeserver($uname,$udomain);
2408:
1.133 albertel 2409: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2410: my @pairs=split(/\&/,$rep);
1.273 albertel 2411: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2412: return @pairs;
2413: }
1.15 www 2414: my %returnhash=();
1.42 www 2415: my $i=0;
1.191 harris41 2416: foreach (@$storearr) {
1.42 www 2417: $returnhash{$_}=unescape($pairs[$i]);
2418: $i++;
1.191 harris41 2419: }
1.15 www 2420: return %returnhash;
1.27 www 2421: }
2422:
2423: # --------------------------------------------------------------- del interface
2424:
2425: sub del {
1.133 albertel 2426: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 2427: my $items='';
1.191 harris41 2428: foreach (@$storearr) {
1.27 www 2429: $items.=escape($_).'&';
1.191 harris41 2430: }
1.27 www 2431: $items=~s/\&$//;
1.133 albertel 2432: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2433: if (!$uname) { $uname=$ENV{'user.name'}; }
2434: my $uhome=&homeserver($uname,$udomain);
2435:
2436: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2437: }
2438:
2439: # -------------------------------------------------------------- dump interface
2440:
2441: sub dump {
1.193 www 2442: my ($namespace,$udomain,$uname,$regexp)=@_;
1.129 albertel 2443: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2444: if (!$uname) { $uname=$ENV{'user.name'}; }
2445: my $uhome=&homeserver($uname,$udomain);
1.193 www 2446: if ($regexp) {
2447: $regexp=&escape($regexp);
2448: } else {
2449: $regexp='.';
2450: }
2451: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12 www 2452: my @pairs=split(/\&/,$rep);
2453: my %returnhash=();
1.191 harris41 2454: foreach (@pairs) {
1.12 www 2455: my ($key,$value)=split(/=/,$_);
1.29 www 2456: $returnhash{unescape($key)}=unescape($value);
1.318 matthew 2457: }
2458: return %returnhash;
1.407 www 2459: }
2460:
2461: # -------------------------------------------------------------- keys interface
2462:
2463: sub getkeys {
2464: my ($namespace,$udomain,$uname)=@_;
2465: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2466: if (!$uname) { $uname=$ENV{'user.name'}; }
2467: my $uhome=&homeserver($uname,$udomain);
2468: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2469: my @keyarray=();
2470: foreach (split(/\&/,$rep)) {
2471: push (@keyarray,&unescape($_));
2472: }
2473: return @keyarray;
1.318 matthew 2474: }
2475:
1.319 matthew 2476: # --------------------------------------------------------------- currentdump
2477: sub currentdump {
1.328 matthew 2478: my ($courseid,$sdom,$sname)=@_;
1.326 matthew 2479: $courseid = $ENV{'request.course.id'} if (! defined($courseid));
2480: $sdom = $ENV{'user.domain'} if (! defined($sdom));
2481: $sname = $ENV{'user.name'} if (! defined($sname));
2482: my $uhome = &homeserver($sname,$sdom);
2483: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 2484: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 2485: #
1.318 matthew 2486: my %returnhash=();
1.319 matthew 2487: #
2488: if ($rep eq "unknown_cmd") {
2489: # an old lond will not know currentdump
2490: # Do a dump and make it look like a currentdump
1.326 matthew 2491: my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319 matthew 2492: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2493: my %hash = @tmp;
2494: @tmp=();
1.424 matthew 2495: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 2496: } else {
2497: my @pairs=split(/\&/,$rep);
2498: foreach (@pairs) {
2499: my ($key,$value)=split(/=/,$_);
2500: my ($symb,$param) = split(/:/,$key);
2501: $returnhash{&unescape($symb)}->{&unescape($param)} =
2502: &unescape($value);
2503: }
1.191 harris41 2504: }
1.12 www 2505: return %returnhash;
1.424 matthew 2506: }
2507:
2508: sub convert_dump_to_currentdump{
2509: my %hash = %{shift()};
2510: my %returnhash;
2511: # Code ripped from lond, essentially. The only difference
2512: # here is the unescaping done by lonnet::dump(). Conceivably
2513: # we might run in to problems with parameter names =~ /^v\./
2514: while (my ($key,$value) = each(%hash)) {
2515: my ($v,$symb,$param) = split(/:/,$key);
2516: next if ($v eq 'version' || $symb eq 'keys');
2517: next if (exists($returnhash{$symb}) &&
2518: exists($returnhash{$symb}->{$param}) &&
2519: $returnhash{$symb}->{'v.'.$param} > $v);
2520: $returnhash{$symb}->{$param}=$value;
2521: $returnhash{$symb}->{'v.'.$param}=$v;
2522: }
2523: #
2524: # Remove all of the keys in the hashes which keep track of
2525: # the version of the parameter.
2526: while (my ($symb,$param_hash) = each(%returnhash)) {
2527: # use a foreach because we are going to delete from the hash.
2528: foreach my $key (keys(%$param_hash)) {
2529: delete($param_hash->{$key}) if ($key =~ /^v\./);
2530: }
2531: }
2532: return \%returnhash;
1.12 www 2533: }
2534:
1.449 matthew 2535: # --------------------------------------------------------------- inc interface
2536:
2537: sub inc {
2538: my ($namespace,$store,$udomain,$uname) = @_;
2539: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2540: if (!$uname) { $uname=$ENV{'user.name'}; }
2541: my $uhome=&homeserver($uname,$udomain);
2542: my $items='';
2543: if (! ref($store)) {
2544: # got a single value, so use that instead
2545: $items = &escape($store).'=&';
2546: } elsif (ref($store) eq 'SCALAR') {
2547: $items = &escape($$store).'=&';
2548: } elsif (ref($store) eq 'ARRAY') {
2549: $items = join('=&',map {&escape($_);} @{$store});
2550: } elsif (ref($store) eq 'HASH') {
2551: while (my($key,$value) = each(%{$store})) {
2552: $items.= &escape($key).'='.&escape($value).'&';
2553: }
2554: }
2555: $items=~s/\&$//;
2556: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
2557: }
2558:
1.12 www 2559: # --------------------------------------------------------------- put interface
2560:
2561: sub put {
1.134 albertel 2562: my ($namespace,$storehash,$udomain,$uname)=@_;
2563: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2564: if (!$uname) { $uname=$ENV{'user.name'}; }
2565: my $uhome=&homeserver($uname,$udomain);
1.12 www 2566: my $items='';
1.191 harris41 2567: foreach (keys %$storehash) {
1.134 albertel 2568: $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191 harris41 2569: }
1.12 www 2570: $items=~s/\&$//;
1.134 albertel 2571: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 2572: }
2573:
2574: # ------------------------------------------------------ critical put interface
2575:
2576: sub cput {
1.134 albertel 2577: my ($namespace,$storehash,$udomain,$uname)=@_;
2578: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2579: if (!$uname) { $uname=$ENV{'user.name'}; }
2580: my $uhome=&homeserver($uname,$udomain);
1.47 www 2581: my $items='';
1.191 harris41 2582: foreach (keys %$storehash) {
1.134 albertel 2583: $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191 harris41 2584: }
1.47 www 2585: $items=~s/\&$//;
1.134 albertel 2586: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2587: }
2588:
2589: # -------------------------------------------------------------- eget interface
2590:
2591: sub eget {
1.133 albertel 2592: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2593: my $items='';
1.191 harris41 2594: foreach (@$storearr) {
1.12 www 2595: $items.=escape($_).'&';
1.191 harris41 2596: }
1.12 www 2597: $items=~s/\&$//;
1.133 albertel 2598: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2599: if (!$uname) { $uname=$ENV{'user.name'}; }
2600: my $uhome=&homeserver($uname,$udomain);
2601: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2602: my @pairs=split(/\&/,$rep);
2603: my %returnhash=();
1.42 www 2604: my $i=0;
1.191 harris41 2605: foreach (@$storearr) {
1.42 www 2606: $returnhash{$_}=unescape($pairs[$i]);
2607: $i++;
1.191 harris41 2608: }
1.12 www 2609: return %returnhash;
2610: }
2611:
1.341 www 2612: # ---------------------------------------------- Custom access rule evaluation
2613:
2614: sub customaccess {
2615: my ($priv,$uri)=@_;
1.342 www 2616: my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343 www 2617: $urealm=~s/^\W//;
2618: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341 www 2619: my $access=0;
2620: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342 www 2621: my ($effect,$realm,$role)=split(/\:/,$_);
1.343 www 2622: if ($role) {
2623: if ($role ne $urole) { next; }
2624: }
2625: foreach (split(/\s*\,\s*/,$realm)) {
2626: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
2627: if ($tdom) {
2628: if ($tdom ne $udom) { next; }
2629: }
2630: if ($tcrs) {
2631: if ($tcrs ne $ucrs) { next; }
2632: }
2633: if ($tsec) {
2634: if ($tsec ne $usec) { next; }
2635: }
2636: $access=($effect eq 'allow');
2637: last;
1.342 www 2638: }
1.402 bowersj2 2639: if ($realm eq '' && $role eq '') {
2640: $access=($effect eq 'allow');
2641: }
1.341 www 2642: }
2643: return $access;
2644: }
2645:
1.103 harris41 2646: # ------------------------------------------------- Check for a user privilege
1.12 www 2647:
2648: sub allowed {
2649: my ($priv,$uri)=@_;
1.439 www 2650: $uri=&deversion($uri);
1.152 www 2651: my $orguri=$uri;
1.52 www 2652: $uri=&declutter($uri);
1.29 www 2653:
1.398 albertel 2654: if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
1.54 www 2655: # Free bre access to adm and meta resources
1.29 www 2656:
1.54 www 2657: if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14 www 2658: return 'F';
1.159 www 2659: }
2660:
2661: # Free bre to public access
2662:
2663: if ($priv eq 'bre') {
1.238 www 2664: my $copyright=&metadata($uri,'copyright');
1.301 www 2665: if (($copyright eq 'public') && (!$ENV{'request.course.id'})) {
2666: return 'F';
2667: }
1.238 www 2668: if ($copyright eq 'priv') {
2669: $uri=~/([^\/]+)\/([^\/]+)\//;
2670: unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
2671: return '';
2672: }
2673: }
2674: if ($copyright eq 'domain') {
2675: $uri=~/([^\/]+)\/([^\/]+)\//;
2676: unless (($ENV{'user.domain'} eq $1) ||
2677: ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
2678: return '';
2679: }
1.262 matthew 2680: }
2681: if ($ENV{'request.role'}=~ /li\.\//) {
2682: # Library role, so allow browsing of resources in this domain.
2683: return 'F';
1.238 www 2684: }
1.341 www 2685: if ($copyright eq 'custom') {
2686: unless (&customaccess($priv,$uri)) { return ''; }
2687: }
1.14 www 2688: }
1.264 matthew 2689: # Domain coordinator is trying to create a course
2690: if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
2691: # uri is the requested domain in this case.
2692: # comparison to 'request.role.domain' shows if the user has selected
2693: # a role of dc for the domain in question.
2694: return 'F' if ($uri eq $ENV{'request.role.domain'});
2695: }
1.29 www 2696:
1.52 www 2697: my $thisallowed='';
2698: my $statecond=0;
2699: my $courseprivid='';
2700:
2701: # Course
2702:
1.479 albertel 2703: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2704: $thisallowed.=$1;
2705: }
1.29 www 2706:
1.52 www 2707: # Domain
2708:
2709: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 2710: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 2711: $thisallowed.=$1;
2712: }
1.52 www 2713:
2714: # Course: uri itself is a course
1.66 www 2715: my $courseuri=$uri;
2716: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 2717: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 2718:
1.83 www 2719: if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.479 albertel 2720: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 2721: $thisallowed.=$1;
2722: }
1.29 www 2723:
1.314 www 2724: # URI is an uploaded document for this course
2725:
1.492 albertel 2726: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
2727: my $refuri=$ENV{'httpref.'.$orguri};
2728: if ($refuri) {
2729: if ($refuri =~ m|^/adm/|) {
2730: $thisallowed='F';
2731: }
2732: }
1.314 www 2733: }
1.492 albertel 2734:
1.52 www 2735: # Full access at system, domain or course-wide level? Exit.
1.29 www 2736:
2737: if ($thisallowed=~/F/) {
2738: return 'F';
2739: }
2740:
1.52 www 2741: # If this is generating or modifying users, exit with special codes
1.29 www 2742:
1.479 albertel 2743: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
1.52 www 2744: return $thisallowed;
2745: }
2746: #
1.103 harris41 2747: # Gathered so far: system, domain and course wide privileges
1.52 www 2748: #
2749: # Course: See if uri or referer is an individual resource that is part of
2750: # the course
2751:
2752: if ($ENV{'request.course.id'}) {
1.232 www 2753:
1.52 www 2754: $courseprivid=$ENV{'request.course.id'};
2755: if ($ENV{'request.course.sec'}) {
2756: $courseprivid.='/'.$ENV{'request.course.sec'};
2757: }
2758: $courseprivid=~s/\_/\//;
2759: my $checkreferer=1;
1.232 www 2760: my ($match,$cond)=&is_on_map($uri);
2761: if ($match) {
2762: $statecond=$cond;
1.52 www 2763: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1.479 albertel 2764: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2765: $thisallowed.=$1;
2766: $checkreferer=0;
2767: }
1.29 www 2768: }
1.83 www 2769:
1.148 www 2770: if ($checkreferer) {
1.152 www 2771: my $refuri=$ENV{'httpref.'.$orguri};
1.148 www 2772: unless ($refuri) {
1.191 harris41 2773: foreach (keys %ENV) {
1.148 www 2774: if ($_=~/^httpref\..*\*/) {
2775: my $pattern=$_;
1.156 www 2776: $pattern=~s/^httpref\.\/res\///;
1.148 www 2777: $pattern=~s/\*/\[\^\/\]\+/g;
2778: $pattern=~s/\//\\\//g;
1.152 www 2779: if ($orguri=~/$pattern/) {
1.148 www 2780: $refuri=$ENV{$_};
2781: }
2782: }
1.191 harris41 2783: }
1.148 www 2784: }
1.232 www 2785:
1.148 www 2786: if ($refuri) {
1.152 www 2787: $refuri=&declutter($refuri);
1.232 www 2788: my ($match,$cond)=&is_on_map($refuri);
2789: if ($match) {
2790: my $refstatecond=$cond;
1.52 www 2791: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1.479 albertel 2792: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2793: $thisallowed.=$1;
1.53 www 2794: $uri=$refuri;
2795: $statecond=$refstatecond;
1.52 www 2796: }
2797: }
1.148 www 2798: }
1.29 www 2799: }
1.52 www 2800: }
1.29 www 2801:
1.52 www 2802: #
1.103 harris41 2803: # Gathered now: all privileges that could apply, and condition number
1.52 www 2804: #
2805: #
2806: # Full or no access?
2807: #
1.29 www 2808:
1.52 www 2809: if ($thisallowed=~/F/) {
2810: return 'F';
2811: }
1.29 www 2812:
1.52 www 2813: unless ($thisallowed) {
2814: return '';
2815: }
1.29 www 2816:
1.52 www 2817: # Restrictions exist, deal with them
2818: #
2819: # C:according to course preferences
2820: # R:according to resource settings
2821: # L:unless locked
2822: # X:according to user session state
2823: #
2824:
2825: # Possibly locked functionality, check all courses
1.54 www 2826: # Locks might take effect only after 10 minutes cache expiration for other
2827: # courses, and 2 minutes for current course
1.52 www 2828:
2829: my $envkey;
2830: if ($thisallowed=~/L/) {
2831: foreach $envkey (keys %ENV) {
1.54 www 2832: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
2833: my $courseid=$2;
2834: my $roleid=$1.'.'.$2;
1.92 www 2835: $courseid=~s/^\///;
1.54 www 2836: my $expiretime=600;
2837: if ($ENV{'request.role'} eq $roleid) {
2838: $expiretime=120;
2839: }
2840: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
2841: my $prefix='course.'.$cdom.'_'.$cnum.'.';
2842: if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
2843: &coursedescription($courseid);
2844: }
1.479 albertel 2845: if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
1.54 www 2846: || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
2847: if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57 www 2848: &log($ENV{'user.domain'},$ENV{'user.name'},
1.239 www 2849: $ENV{'user.home'},
1.57 www 2850: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 2851: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54 www 2852: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 2853: return '';
2854: }
2855: }
1.479 albertel 2856: if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
1.54 www 2857: || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
2858: if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57 www 2859: &log($ENV{'user.domain'},$ENV{'user.name'},
1.239 www 2860: $ENV{'user.home'},
1.57 www 2861: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 2862: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54 www 2863: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 2864: return '';
2865: }
2866: }
2867: }
1.29 www 2868: }
1.52 www 2869: }
2870:
2871: #
2872: # Rest of the restrictions depend on selected course
2873: #
2874:
2875: unless ($ENV{'request.course.id'}) {
2876: return '1';
2877: }
1.29 www 2878:
1.52 www 2879: #
2880: # Now user is definitely in a course
2881: #
1.53 www 2882:
2883:
2884: # Course preferences
2885:
2886: if ($thisallowed=~/C/) {
1.54 www 2887: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237 www 2888: my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54 www 2889: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 2890: =~/\Q$rolecode\E/) {
1.57 www 2891: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
2892: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237 www 2893: $ENV{'request.course.id'});
2894: return '';
2895: }
2896:
2897: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 2898: =~/\Q$unamedom\E/) {
1.237 www 2899: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
2900: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54 www 2901: $ENV{'request.course.id'});
2902: return '';
2903: }
1.53 www 2904: }
2905:
2906: # Resource preferences
2907:
2908: if ($thisallowed=~/R/) {
1.54 www 2909: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.479 albertel 2910: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.341 www 2911: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57 www 2912: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341 www 2913: return '';
1.54 www 2914: }
1.53 www 2915: }
1.30 www 2916:
1.246 www 2917: # Restricted by state or randomout?
1.30 www 2918:
1.52 www 2919: if ($thisallowed=~/X/) {
1.247 www 2920: if ($ENV{'acc.randomout'}) {
1.249 www 2921: my $symb=&symbread($uri,1);
1.479 albertel 2922: if (($symb) && ($ENV{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 2923: return '';
2924: }
1.247 www 2925: }
2926: if (&condval($statecond)) {
1.52 www 2927: return '2';
2928: } else {
2929: return '';
2930: }
2931: }
1.30 www 2932:
1.52 www 2933: return 'F';
1.232 www 2934: }
2935:
2936: # --------------------------------------------------- Is a resource on the map?
2937:
2938: sub is_on_map {
2939: my $uri=&declutter(shift);
1.435 www 2940: $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232 www 2941: my @uriparts=split(/\//,$uri);
2942: my $filename=$uriparts[$#uriparts];
2943: my $pathname=$uri;
1.289 bowersj2 2944: $pathname=~s|/\Q$filename\E$||;
1.332 www 2945: $pathname=~s/^adm\/wrapper\///;
1.289 bowersj2 2946: #Trying to find the conditional for the file
1.232 www 2947: my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 2948: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 2949: if ($match) {
1.289 bowersj2 2950: return (1,$1);
2951: } else {
1.434 www 2952: return (0,0);
1.289 bowersj2 2953: }
1.12 www 2954: }
2955:
1.427 www 2956: # --------------------------------------------------------- Get symb from alias
2957:
2958: sub get_symb_from_alias {
2959: my $symb=shift;
2960: my ($map,$resid,$url)=&decode_symb($symb);
2961: # Already is a symb
2962: if ($url) { return $symb; }
2963: # Must be an alias
2964: my $aliassymb='';
2965: my %bighash;
2966: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
2967: &GDBM_READER(),0640)) {
2968: my $rid=$bighash{'mapalias_'.$symb};
2969: if ($rid) {
2970: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 2971: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
2972: $resid,$bighash{'src_'.$rid});
1.427 www 2973: }
2974: untie %bighash;
2975: }
2976: return $aliassymb;
2977: }
2978:
1.12 www 2979: # ----------------------------------------------------------------- Define Role
2980:
2981: sub definerole {
2982: if (allowed('mcr','/')) {
2983: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392 www 2984: foreach (split(':',$sysrole)) {
1.21 www 2985: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 2986: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
2987: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
2988: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 2989: return "refused:s:$crole&$cqual";
2990: }
2991: }
1.191 harris41 2992: }
1.392 www 2993: foreach (split(':',$domrole)) {
1.21 www 2994: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 2995: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
2996: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
2997: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 2998: return "refused:d:$crole&$cqual";
2999: }
3000: }
1.191 harris41 3001: }
1.392 www 3002: foreach (split(':',$courole)) {
1.21 www 3003: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3004: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3005: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3006: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3007: return "refused:c:$crole&$cqual";
3008: }
3009: }
1.191 harris41 3010: }
1.12 www 3011: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
3012: "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21 www 3013: "rolesdef_$rolename=".
3014: escape($sysrole.'_'.$domrole.'_'.$courole);
1.12 www 3015: return reply($command,$ENV{'user.home'});
3016: } else {
3017: return 'refused';
3018: }
1.105 harris41 3019: }
3020:
3021: # ---------------- Make a metadata query against the network of library servers
3022:
3023: sub metadata_query {
1.244 matthew 3024: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 3025: my %rhash;
1.244 matthew 3026: my @server_list = (defined($server_array) ? @$server_array
3027: : keys(%libserv) );
3028: for my $server (@server_list) {
1.118 harris41 3029: unless ($custom or $customshow) {
3030: my $reply=&reply("querysend:".&escape($query),$server);
3031: $rhash{$server}=$reply;
3032: }
3033: else {
3034: my $reply=&reply("querysend:".&escape($query).':'.
3035: &escape($custom).':'.&escape($customshow),
3036: $server);
3037: $rhash{$server}=$reply;
3038: }
1.112 harris41 3039: }
1.118 harris41 3040: return \%rhash;
1.240 www 3041: }
3042:
3043: # ----------------------------------------- Send log queries and wait for reply
3044:
3045: sub log_query {
3046: my ($uname,$udom,$query,%filters)=@_;
3047: my $uhome=&homeserver($uname,$udom);
3048: if ($uhome eq 'no_host') { return 'error: no_host'; }
3049: my $uhost=$hostname{$uhome};
1.241 www 3050: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240 www 3051: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3052: $uhome);
1.479 albertel 3053: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 3054: return get_query_reply($queryid);
3055: }
3056:
1.508 raeburn 3057: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 3058:
3059: sub fetch_enrollment_query {
1.511 raeburn 3060: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 3061: my $homeserver;
3062: if ($context eq 'automated') {
3063: $homeserver = $perlvar{'lonHostID'};
3064: } else {
3065: $homeserver = &homeserver($cnum,$dom);
3066: }
1.506 raeburn 3067: my $host=$hostname{$homeserver};
3068: my $cmd = '';
3069: foreach (keys %{$affiliatesref}) {
1.508 raeburn 3070: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506 raeburn 3071: }
3072: $cmd =~ s/%%$//;
3073: $cmd = &escape($cmd);
3074: my $query = 'fetchenrollment';
3075: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$ENV{'user.name'}.':'.$cmd,$homeserver);
3076: unless ($queryid=~/^\Q$host\E\_/) { return 'error: '.$queryid; }
3077: my $reply = &get_query_reply($queryid);
3078: unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.515 ! raeburn 3079: my @responses = split/:/,$reply;
! 3080: if ($homeserver eq $perlvar{'lonHostID'}) {
! 3081: foreach (@responses) {
! 3082: my ($key,$value) = split/=/,$_;
! 3083: $$replyref{$key} = $value;
! 3084: }
! 3085: } else {
1.506 raeburn 3086: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
3087: foreach (@responses) {
3088: my ($key,$value) = split/=/,$_;
3089: $$replyref{$key} = $value;
3090: if ($value > 0) {
3091: foreach (@{$$affiliatesref{$key}}) {
3092: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
3093: my $destname = $pathname.'/'.$filename;
3094: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
3095: unless ($xml_classlist =~ /^error/) {
3096: if ( open(FILE,">$destname") ) {
3097: print FILE &unescape($xml_classlist);
3098: close(FILE);
3099: }
3100: }
3101: }
3102: }
3103: }
3104: }
3105: return 'ok';
3106: }
3107: return 'error';
3108: }
3109:
1.242 www 3110: sub get_query_reply {
3111: my $queryid=shift;
1.240 www 3112: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
3113: my $reply='';
3114: for (1..100) {
3115: sleep 2;
3116: if (-e $replyfile.'.end') {
1.448 albertel 3117: if (open(my $fh,$replyfile)) {
1.240 www 3118: $reply.=<$fh>;
1.448 albertel 3119: close($fh);
1.240 www 3120: } else { return 'error: reply_file_error'; }
1.242 www 3121: return &unescape($reply);
3122: }
1.240 www 3123: }
1.242 www 3124: return 'timeout:'.$queryid;
1.240 www 3125: }
3126:
3127: sub courselog_query {
1.241 www 3128: #
3129: # possible filters:
3130: # url: url or symb
3131: # username
3132: # domain
3133: # action: view, submit, grade
3134: # start: timestamp
3135: # end: timestamp
3136: #
1.240 www 3137: my (%filters)=@_;
3138: unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241 www 3139: if ($filters{'url'}) {
3140: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
3141: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
3142: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
3143: }
1.240 www 3144: my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
3145: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
3146: return &log_query($cname,$cdom,'courselog',%filters);
3147: }
3148:
3149: sub userlog_query {
3150: my ($uname,$udom,%filters)=@_;
3151: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 3152: }
3153:
1.506 raeburn 3154: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
3155:
3156: sub auto_run {
1.508 raeburn 3157: my ($cnum,$cdom) = @_;
3158: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 3159: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 3160: return $response;
3161: }
3162:
3163: sub auto_get_sections {
1.508 raeburn 3164: my ($cnum,$cdom,$inst_coursecode) = @_;
3165: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 3166: my @secs = ();
1.511 raeburn 3167: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 3168: unless ($response eq 'refused') {
3169: @secs = split/:/,$response;
3170: }
3171: return @secs;
3172: }
3173:
3174: sub auto_new_course {
1.508 raeburn 3175: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
3176: my $homeserver = &homeserver($cnum,$cdom);
1.515 ! raeburn 3177: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 3178: return $response;
3179: }
3180:
3181: sub auto_validate_courseID {
1.508 raeburn 3182: my ($cnum,$cdom,$inst_course_id) = @_;
3183: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 3184: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 3185: return $response;
3186: }
3187:
3188: sub auto_create_password {
1.508 raeburn 3189: my ($cnum,$cdom,$authparam) = @_;
3190: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 3191: my $create_passwd = 0;
3192: my $authchk = '';
1.511 raeburn 3193: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 3194: if ($response eq 'refused') {
3195: $authchk = 'refused';
3196: } else {
3197: ($authparam,$create_passwd,$authchk) = split/:/,$response;
3198: }
3199: return ($authparam,$create_passwd,$authchk);
3200: }
3201:
1.12 www 3202: # ------------------------------------------------------------------ Plain Text
3203:
3204: sub plaintext {
1.22 www 3205: my $short=shift;
1.414 www 3206: return &mt($prp{$short});
1.12 www 3207: }
3208:
3209: # ----------------------------------------------------------------- Assign Role
3210:
3211: sub assignrole {
1.357 www 3212: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 3213: my $mrole;
3214: if ($role =~ /^cr\//) {
1.393 www 3215: my $cwosec=$url;
3216: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
3217: unless (&allowed('ccr',$cwosec)) {
1.104 www 3218: &logthis('Refused custom assignrole: '.
3219: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
3220: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
3221: return 'refused';
3222: }
1.21 www 3223: $mrole='cr';
3224: } else {
1.82 www 3225: my $cwosec=$url;
1.83 www 3226: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373 www 3227: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 3228: &logthis('Refused assignrole: '.
3229: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
3230: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
3231: return 'refused';
3232: }
1.21 www 3233: $mrole=$role;
3234: }
3235: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
3236: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 3237: if ($end) { $command.='_'.$end; }
1.21 www 3238: if ($start) {
3239: if ($end) {
1.81 www 3240: $command.='_'.$start;
1.21 www 3241: } else {
1.81 www 3242: $command.='_0_'.$start;
1.21 www 3243: }
3244: }
1.357 www 3245: # actually delete
3246: if ($deleteflag) {
1.373 www 3247: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 3248: # modify command to delete the role
3249: $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
3250: "$udom:$uname:$url".'_'."$mrole";
1.373 www 3251: &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 3252: # set start and finish to negative values for userrolelog
3253: $start=-1;
3254: $end=-1;
3255: }
3256: }
3257: # send command
1.349 www 3258: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 3259: # log new user role if status is ok
1.349 www 3260: if ($answer eq 'ok') {
3261: &userrolelog($mrole,$uname,$udom,$url,$start,$end);
3262: }
3263: return $answer;
1.169 harris41 3264: }
3265:
3266: # -------------------------------------------------- Modify user authentication
1.197 www 3267: # Overrides without validation
3268:
1.169 harris41 3269: sub modifyuserauth {
3270: my ($udom,$uname,$umode,$upass)=@_;
3271: my $uhome=&homeserver($uname,$udom);
1.197 www 3272: unless (&allowed('mau',$udom)) { return 'refused'; }
3273: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272 matthew 3274: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
3275: ' in domain '.$ENV{'request.role.domain'});
1.169 harris41 3276: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
3277: &escape($upass),$uhome);
1.197 www 3278: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
3279: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
3280: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
3281: &log($udom,,$uname,$uhome,
3282: 'Authentication changed by '.$ENV{'user.domain'}.', '.
3283: $ENV{'user.name'}.', '.$umode.
3284: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 3285: unless ($reply eq 'ok') {
1.197 www 3286: &logthis('Authentication mode error: '.$reply);
1.169 harris41 3287: return 'error: '.$reply;
3288: }
1.170 harris41 3289: return 'ok';
1.80 www 3290: }
3291:
1.81 www 3292: # --------------------------------------------------------------- Modify a user
1.80 www 3293:
1.81 www 3294: sub modifyuser {
1.206 matthew 3295: my ($udom, $uname, $uid,
3296: $umode, $upass, $first,
3297: $middle, $last, $gene,
1.387 www 3298: $forceid, $desiredhome, $email)=@_;
1.198 www 3299: $udom=~s/\W//g;
3300: $uname=~s/\W//g;
1.81 www 3301: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3302: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 3303: $last.', '.$gene.'(forceid: '.$forceid.')'.
3304: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
3305: ' desiredhome not specified').
1.272 matthew 3306: ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
3307: ' in domain '.$ENV{'request.role.domain'});
1.230 stredwic 3308: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 3309: # ----------------------------------------------------------------- Create User
1.406 albertel 3310: if (($uhome eq 'no_host') &&
3311: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 3312: my $unhome='';
1.209 matthew 3313: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
3314: $unhome = $desiredhome;
3315: } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80 www 3316: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209 matthew 3317: } else { # load balancing routine for determining $unhome
1.80 www 3318: my $tryserver;
1.81 www 3319: my $loadm=10000000;
1.80 www 3320: foreach $tryserver (keys %libserv) {
3321: if ($hostdom{$tryserver} eq $udom) {
3322: my $answer=reply('load',$tryserver);
3323: if (($answer=~/\d+/) && ($answer<$loadm)) {
3324: $loadm=$answer;
3325: $unhome=$tryserver;
3326: }
3327: }
3328: }
3329: }
3330: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 3331: return 'error: unable to find a home server for '.$uname.
3332: ' in domain '.$udom;
1.80 www 3333: }
3334: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
3335: &escape($upass),$unhome);
3336: unless ($reply eq 'ok') {
3337: return 'error: '.$reply;
3338: }
1.230 stredwic 3339: $uhome=&homeserver($uname,$udom,'true');
1.80 www 3340: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 3341: return 'error: unable verify users home machine.';
1.80 www 3342: }
1.209 matthew 3343: } # End of creation of new user
1.80 www 3344: # ---------------------------------------------------------------------- Add ID
3345: if ($uid) {
3346: $uid=~tr/A-Z/a-z/;
3347: my %uidhash=&idrget($udom,$uname);
1.196 www 3348: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
3349: && (!$forceid)) {
1.80 www 3350: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 3351: return 'error: user id "'.$uid.'" does not match '.
3352: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 3353: }
3354: } else {
3355: &idput($udom,($uname => $uid));
3356: }
3357: }
3358: # -------------------------------------------------------------- Add names, etc
1.313 matthew 3359: my @tmp=&get('environment',
1.134 albertel 3360: ['firstname','middlename','lastname','generation'],
3361: $udom,$uname);
1.313 matthew 3362: my %names;
3363: if ($tmp[0] =~ m/^error:.*/) {
3364: %names=();
3365: } else {
3366: %names = @tmp;
3367: }
1.388 www 3368: #
3369: # Make sure to not trash student environment if instructor does not bother
3370: # to supply name and email information
3371: #
3372: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 3373: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 3374: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 3375: if (defined($gene)) { $names{'generation'} = $gene; }
1.388 www 3376: if ($email) { $names{'notification'} = $email;
3377: $names{'critnotification'} = $email; }
1.387 www 3378:
1.134 albertel 3379: my $reply = &put('environment', \%names, $udom,$uname);
3380: if ($reply ne 'ok') { return 'error: '.$reply; }
1.81 www 3381: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3382: $umode.', '.$first.', '.$middle.', '.
3383: $last.', '.$gene.' by '.
3384: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134 albertel 3385: return 'ok';
1.80 www 3386: }
3387:
1.81 www 3388: # -------------------------------------------------------------- Modify student
1.80 www 3389:
1.81 www 3390: sub modifystudent {
3391: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 ! raeburn 3392: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 3393: if (!$cid) {
3394: unless ($cid=$ENV{'request.course.id'}) {
3395: return 'not_in_class';
3396: }
1.80 www 3397: }
3398: # --------------------------------------------------------------- Make the user
1.81 www 3399: my $reply=&modifyuser
1.209 matthew 3400: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 3401: $desiredhome,$email);
1.80 www 3402: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 3403: # This will cause &modify_student_enrollment to get the uid from the
3404: # students environment
3405: $uid = undef if (!$forceid);
1.455 albertel 3406: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 ! raeburn 3407: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 3408: return $reply;
3409: }
3410:
3411: sub modify_student_enrollment {
1.515 ! raeburn 3412: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 3413: my ($cdom,$cnum,$chome);
3414: if (!$cid) {
3415: unless ($cid=$ENV{'request.course.id'}) {
3416: return 'not_in_class';
3417: }
3418: $cdom=$ENV{'course.'.$cid.'.domain'};
3419: $cnum=$ENV{'course.'.$cid.'.num'};
3420: } else {
3421: ($cdom,$cnum)=split(/_/,$cid);
3422: }
3423: $chome=$ENV{'course.'.$cid.'.home'};
3424: if (!$chome) {
1.457 raeburn 3425: $chome=&homeserver($cnum,$cdom);
1.297 matthew 3426: }
1.455 albertel 3427: if (!$chome) { return 'unknown_course'; }
1.297 matthew 3428: # Make sure the user exists
1.81 www 3429: my $uhome=&homeserver($uname,$udom);
3430: if (($uhome eq '') || ($uhome eq 'no_host')) {
3431: return 'error: no such user';
3432: }
1.297 matthew 3433: # Get student data if we were not given enough information
3434: if (!defined($first) || $first eq '' ||
3435: !defined($last) || $last eq '' ||
3436: !defined($uid) || $uid eq '' ||
3437: !defined($middle) || $middle eq '' ||
3438: !defined($gene) || $gene eq '') {
1.294 matthew 3439: # They did not supply us with enough data to enroll the student, so
3440: # we need to pick up more information.
1.297 matthew 3441: my %tmp = &get('environment',
1.294 matthew 3442: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 3443: ,$udom,$uname);
3444:
1.455 albertel 3445: #foreach (keys(%tmp)) {
3446: # &logthis("key $_ = ".$tmp{$_});
3447: #}
1.294 matthew 3448: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
3449: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
3450: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 3451: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 3452: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
3453: }
3454: my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
3455: $first,$middle);
1.487 albertel 3456: my $reply=cput('classlist',
3457: {"$uname:$udom" =>
1.515 ! raeburn 3458: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 3459: $cdom,$cnum);
1.81 www 3460: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
3461: return 'error: '.$reply;
3462: }
1.297 matthew 3463: # Add student role to user
1.83 www 3464: my $uurl='/'.$cid;
1.81 www 3465: $uurl=~s/\_/\//g;
3466: if ($usec) {
3467: $uurl.='/'.$usec;
3468: }
3469: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 3470: }
3471:
1.84 www 3472: # ------------------------------------------------- Write to course preferences
3473:
3474: sub writecoursepref {
3475: my ($courseid,%prefs)=@_;
3476: $courseid=~s/^\///;
3477: $courseid=~s/\_/\//g;
3478: my ($cdomain,$cnum)=split(/\//,$courseid);
3479: my $chome=homeserver($cnum,$cdomain);
3480: if (($chome eq '') || ($chome eq 'no_host')) {
3481: return 'error: no such course';
3482: }
3483: my $cstring='';
1.191 harris41 3484: foreach (keys %prefs) {
1.84 www 3485: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191 harris41 3486: }
1.84 www 3487: $cstring=~s/\&$//;
3488: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
3489: }
3490:
3491: # ---------------------------------------------------------- Make/modify course
3492:
3493: sub createcourse {
1.271 www 3494: my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84 www 3495: $url=&declutter($url);
3496: my $cid='';
1.264 matthew 3497: unless (&allowed('ccc',$udom)) {
1.84 www 3498: return 'refused';
3499: }
3500: # ------------------------------------------------------------------- Create ID
3501: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3502: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3503: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 3504: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 3505: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3506: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3507: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 3508: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3509: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3510: return 'error: unable to generate unique course-ID';
3511: }
3512: }
1.264 matthew 3513: # ------------------------------------------------ Check supplied server name
3514: $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
3515: if (! exists($libserv{$course_server})) {
3516: return 'error:bad server name '.$course_server;
3517: }
1.84 www 3518: # ------------------------------------------------------------- Make the course
3519: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 3520: $course_server);
1.84 www 3521: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 3522: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3523: if (($uhome eq '') || ($uhome eq 'no_host')) {
3524: return 'error: no such course';
3525: }
1.271 www 3526: # ----------------------------------------------------------------- Course made
1.358 www 3527: # log existance
3528: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
3529: $uhome);
3530: &flushcourselogs();
3531: # set toplevel url
1.271 www 3532: my $topurl=$url;
3533: unless ($nonstandard) {
3534: # ------------------------------------------ For standard courses, make top url
3535: my $mapurl=&clutter($url);
1.278 www 3536: if ($mapurl eq '/res/') { $mapurl=''; }
1.271 www 3537: $ENV{'form.initmap'}=(<<ENDINITMAP);
3538: <map>
3539: <resource id="1" type="start"></resource>
3540: <resource id="2" src="$mapurl"></resource>
3541: <resource id="3" type="finish"></resource>
3542: <link index="1" from="1" to="2"></link>
3543: <link index="2" from="2" to="3"></link>
3544: </map>
3545: ENDINITMAP
3546: $topurl=&declutter(
3547: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
3548: );
3549: }
3550: # ----------------------------------------------------------- Write preferences
1.84 www 3551: &writecoursepref($udom.'_'.$uname,
3552: ('description' => $description,
1.271 www 3553: 'url' => $topurl));
1.84 www 3554: return '/'.$udom.'/'.$uname;
3555: }
3556:
1.21 www 3557: # ---------------------------------------------------------- Assign Custom Role
3558:
3559: sub assigncustomrole {
1.357 www 3560: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 3561: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 3562: $end,$start,$deleteflag);
1.21 www 3563: }
3564:
3565: # ----------------------------------------------------------------- Revoke Role
3566:
3567: sub revokerole {
1.357 www 3568: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 3569: my $now=time;
1.357 www 3570: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 3571: }
3572:
3573: # ---------------------------------------------------------- Revoke Custom Role
3574:
3575: sub revokecustomrole {
1.357 www 3576: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 3577: my $now=time;
1.357 www 3578: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
3579: $deleteflag);
1.17 www 3580: }
3581:
1.512 banghart 3582:
3583: # ------------------------------------------------------------ Portfolio Director Lister
3584: sub portfoliolist {
1.514 albertel 3585: #FIXME us the ls: command instead please
3586: #FIXME uhome should never be an argument to any lonnet functions
3587: # returns listing of contents of user's /userfiles/portfolio/ directory
3588: #
3589: my ($udom,$uname,$uhome);
3590: $uname=$ENV{'user.name'};
3591: $udom=$ENV{'user.domain'};
3592: $uhome=$ENV{'user.home'};
3593: my $listing = &reply('portls:'.$uname.':'.$udom, $uhome);
3594: return $listing;
1.513 banghart 3595: }
1.514 albertel 3596:
1.513 banghart 3597: sub portfoliomanage {
1.514 albertel 3598:
3599: #FIXME please user the existing remove userfile function instead and
3600: #add a userfilerename functions.
3601: #FIXME uhome should never be an argument to any lonnet functions
3602:
3603: # handles deleting and renaming files in user's userfiles/portfolio/ directory
3604: #
3605: my ($filename, $fileaction, $filenewname) = @_;
3606: my ($udom, $uname, $uhome);
3607: $uname=$ENV{'user.name'};
3608: $udom=$ENV{'user.domain'};
3609: $uhome=$ENV{'user.home'};
3610: my $listing = reply('portfoliomanage:'.$uname.':'.$udom.':'.$filename.':'.$fileaction.':'.$filenewname, $uhome);
3611: return $listing;
1.512 banghart 3612: }
3613:
3614:
1.17 www 3615: # ------------------------------------------------------------ Directory lister
3616:
3617: sub dirlist {
1.253 stredwic 3618: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
3619:
1.18 www 3620: $uri=~s/^\///;
3621: $uri=~s/\/$//;
1.253 stredwic 3622: my ($udom, $uname);
3623: (undef,$udom,$uname)=split(/\//,$uri);
3624: if(defined($userdomain)) {
3625: $udom = $userdomain;
3626: }
3627: if(defined($username)) {
3628: $uname = $username;
3629: }
3630:
3631: my $dirRoot = $perlvar{'lonDocRoot'};
3632: if(defined($alternateDirectoryRoot)) {
3633: $dirRoot = $alternateDirectoryRoot;
3634: $dirRoot =~ s/\/$//;
3635: }
3636:
3637: if($udom) {
3638: if($uname) {
3639: my $listing=reply('ls:'.$dirRoot.'/'.$uri,
3640: homeserver($uname,$udom));
3641: return split(/:/,$listing);
3642: } elsif(!defined($alternateDirectoryRoot)) {
3643: my $tryserver;
3644: my %allusers=();
3645: foreach $tryserver (keys %libserv) {
3646: if($hostdom{$tryserver} eq $udom) {
3647: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
3648: $udom, $tryserver);
3649: if (($listing ne 'no_such_dir') && ($listing ne 'empty')
3650: && ($listing ne 'con_lost')) {
3651: foreach (split(/:/,$listing)) {
3652: my ($entry,@stat)=split(/&/,$_);
3653: $allusers{$entry}=1;
3654: }
3655: }
1.191 harris41 3656: }
1.253 stredwic 3657: }
3658: my $alluserstr='';
3659: foreach (sort keys %allusers) {
3660: $alluserstr.=$_.'&user:';
3661: }
3662: $alluserstr=~s/:$//;
3663: return split(/:/,$alluserstr);
3664: } else {
3665: my @emptyResults = ();
3666: push(@emptyResults, 'missing user name');
3667: return split(':',@emptyResults);
3668: }
3669: } elsif(!defined($alternateDirectoryRoot)) {
3670: my $tryserver;
3671: my %alldom=();
3672: foreach $tryserver (keys %libserv) {
3673: $alldom{$hostdom{$tryserver}}=1;
3674: }
3675: my $alldomstr='';
3676: foreach (sort keys %alldom) {
1.397 albertel 3677: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253 stredwic 3678: }
3679: $alldomstr=~s/:$//;
3680: return split(/:/,$alldomstr);
3681: } else {
3682: my @emptyResults = ();
3683: push(@emptyResults, 'missing domain');
3684: return split(':',@emptyResults);
1.275 stredwic 3685: }
3686: }
3687:
3688: # --------------------------------------------- GetFileTimestamp
3689: # This function utilizes dirlist and returns the date stamp for
3690: # when it was last modified. It will also return an error of -1
3691: # if an error occurs
3692:
1.410 matthew 3693: ##
3694: ## FIXME: This subroutine assumes its caller knows something about the
3695: ## directory structure of the home server for the student ($root).
3696: ## Not a good assumption to make. Since this is for looking up files
3697: ## in user directories, the full path should be constructed by lond, not
3698: ## whatever machine we request data from.
3699: ##
1.275 stredwic 3700: sub GetFileTimestamp {
3701: my ($studentDomain,$studentName,$filename,$root)=@_;
3702: $studentDomain=~s/\W//g;
3703: $studentName=~s/\W//g;
3704: my $subdir=$studentName.'__';
3705: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3706: my $proname="$studentDomain/$subdir/$studentName";
3707: $proname .= '/'.$filename;
1.375 matthew 3708: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
3709: $studentName, $root);
1.275 stredwic 3710: my @stats = split('&', $fileStat);
3711: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 3712: # @stats contains first the filename, then the stat output
3713: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 3714: } else {
3715: return -1;
1.253 stredwic 3716: }
1.26 www 3717: }
3718:
3719: # -------------------------------------------------------- Value of a Condition
3720:
1.40 www 3721: sub directcondval {
3722: my $number=shift;
3723: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
3724: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
3725: } else {
3726: return 2;
3727: }
3728: }
3729:
1.26 www 3730: sub condval {
3731: my $condidx=shift;
3732: my $result=0;
1.54 www 3733: my $allpathcond='';
1.191 harris41 3734: foreach (split(/\|/,$condidx)) {
1.54 www 3735: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
3736: $allpathcond.=
3737: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
3738: }
1.191 harris41 3739: }
1.54 www 3740: $allpathcond=~s/\|$//;
1.33 www 3741: if ($ENV{'request.course.id'}) {
1.54 www 3742: if ($allpathcond) {
1.26 www 3743: my $operand='|';
3744: my @stack;
1.191 harris41 3745: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26 www 3746: if ($_ eq '(') {
3747: push @stack,($operand,$result)
3748: } elsif ($_ eq ')') {
3749: my $before=pop @stack;
3750: if (pop @stack eq '&') {
3751: $result=$result>$before?$before:$result;
3752: } else {
3753: $result=$result>$before?$result:$before;
3754: }
3755: } elsif (($_ eq '&') || ($_ eq '|')) {
3756: $operand=$_;
3757: } else {
1.40 www 3758: my $new=directcondval($_);
1.26 www 3759: if ($operand eq '&') {
3760: $result=$result>$new?$new:$result;
3761: } else {
3762: $result=$result>$new?$result:$new;
1.191 harris41 3763: }
1.26 www 3764: }
1.191 harris41 3765: }
1.26 www 3766: }
3767: }
3768: return $result;
1.421 albertel 3769: }
3770:
3771: # ---------------------------------------------------- Devalidate courseresdata
3772:
3773: sub devalidatecourseresdata {
3774: my ($coursenum,$coursedomain)=@_;
3775: my $hashid=$coursenum.':'.$coursedomain;
1.428 albertel 3776: &devalidate_cache(\%courseresdatacache,$hashid,'courseres');
1.28 www 3777: }
3778:
1.200 www 3779: # --------------------------------------------------- Course Resourcedata Query
3780:
3781: sub courseresdata {
3782: my ($coursenum,$coursedomain,@which)=@_;
3783: my $coursehom=&homeserver($coursenum,$coursedomain);
3784: my $hashid=$coursenum.':'.$coursedomain;
1.425 albertel 3785: my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres');
1.417 albertel 3786: unless (defined($cached)) {
1.251 albertel 3787: my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 3788: $result=\%dumpreply;
1.251 albertel 3789: my ($tmp) = keys(%dumpreply);
3790: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.425 albertel 3791: &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.306 albertel 3792: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
3793: return $tmp;
1.416 albertel 3794: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 3795: $result=undef;
1.425 albertel 3796: &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.250 albertel 3797: }
3798: }
1.251 albertel 3799: foreach my $item (@which) {
1.417 albertel 3800: if (defined($result->{$item})) {
3801: return $result->{$item};
1.251 albertel 3802: }
1.250 albertel 3803: }
1.291 albertel 3804: return undef;
1.200 www 3805: }
3806:
1.379 matthew 3807: #
3808: # EXT resource caching routines
3809: #
3810:
3811: sub clear_EXT_cache_status {
1.383 albertel 3812: &delenv('cache.EXT.');
1.379 matthew 3813: }
3814:
3815: sub EXT_cache_status {
3816: my ($target_domain,$target_user) = @_;
1.383 albertel 3817: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389 www 3818: if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379 matthew 3819: # We know already the user has no data
3820: return 1;
3821: } else {
3822: return 0;
3823: }
3824: }
3825:
3826: sub EXT_cache_set {
3827: my ($target_domain,$target_user) = @_;
1.383 albertel 3828: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379 matthew 3829: &appenv($cachename => time);
3830: }
3831:
1.28 www 3832: # --------------------------------------------------------- Value of a Variable
1.58 www 3833: sub EXT {
1.395 albertel 3834: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218 albertel 3835:
1.68 www 3836: unless ($varname) { return ''; }
1.218 albertel 3837: #get real user name/domain, courseid and symb
3838: my $courseid;
1.359 albertel 3839: my $publicuser;
1.427 www 3840: if ($symbparm) {
3841: $symbparm=&get_symb_from_alias($symbparm);
3842: }
1.218 albertel 3843: if (!($uname && $udom)) {
1.360 albertel 3844: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378 matthew 3845: &Apache::lonxml::whichuser($symbparm);
1.218 albertel 3846: if (!$symbparm) { $symbparm=$cursymb; }
3847: } else {
3848: $courseid=$ENV{'request.course.id'};
3849: }
1.48 www 3850: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
3851: my $rest;
1.320 albertel 3852: if (defined($therest[0])) {
1.48 www 3853: $rest=join('.',@therest);
3854: } else {
3855: $rest='';
3856: }
1.320 albertel 3857:
1.57 www 3858: my $qualifierrest=$qualifier;
3859: if ($rest) { $qualifierrest.='.'.$rest; }
3860: my $spacequalifierrest=$space;
3861: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 3862: if ($realm eq 'user') {
1.48 www 3863: # --------------------------------------------------------------- user.resource
3864: if ($space eq 'resource') {
1.335 albertel 3865: if (defined($Apache::lonhomework::parsing_a_problem)) {
3866: return $Apache::lonhomework::history{$qualifierrest};
3867: } else {
1.359 albertel 3868: my %restored;
3869: if ($publicuser || $ENV{'request.state'} eq 'construct') {
3870: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
3871: } else {
3872: %restored=&restore($symbparm,$courseid,$udom,$uname);
3873: }
1.335 albertel 3874: return $restored{$qualifierrest};
3875: }
1.48 www 3876: # ----------------------------------------------------------------- user.access
3877: } elsif ($space eq 'access') {
1.218 albertel 3878: # FIXME - not supporting calls for a specific user
1.48 www 3879: return &allowed($qualifier,$rest);
3880: # ------------------------------------------ user.preferences, user.environment
3881: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218 albertel 3882: if (($uname eq $ENV{'user.name'}) &&
3883: ($udom eq $ENV{'user.domain'})) {
3884: return $ENV{join('.',('environment',$qualifierrest))};
3885: } else {
1.359 albertel 3886: my %returnhash;
3887: if (!$publicuser) {
3888: %returnhash=&userenvironment($udom,$uname,
3889: $qualifierrest);
3890: }
1.218 albertel 3891: return $returnhash{$qualifierrest};
3892: }
1.48 www 3893: # ----------------------------------------------------------------- user.course
3894: } elsif ($space eq 'course') {
1.218 albertel 3895: # FIXME - not supporting calls for a specific user
1.48 www 3896: return $ENV{join('.',('request.course',$qualifier))};
3897: # ------------------------------------------------------------------- user.role
3898: } elsif ($space eq 'role') {
1.218 albertel 3899: # FIXME - not supporting calls for a specific user
1.48 www 3900: my ($role,$where)=split(/\./,$ENV{'request.role'});
3901: if ($qualifier eq 'value') {
3902: return $role;
3903: } elsif ($qualifier eq 'extent') {
3904: return $where;
3905: }
3906: # ----------------------------------------------------------------- user.domain
3907: } elsif ($space eq 'domain') {
1.218 albertel 3908: return $udom;
1.48 www 3909: # ------------------------------------------------------------------- user.name
3910: } elsif ($space eq 'name') {
1.218 albertel 3911: return $uname;
1.48 www 3912: # ---------------------------------------------------- Any other user namespace
1.29 www 3913: } else {
1.359 albertel 3914: my %reply;
3915: if (!$publicuser) {
3916: %reply=&get($space,[$qualifierrest],$udom,$uname);
3917: }
3918: return $reply{$qualifierrest};
1.48 www 3919: }
1.236 www 3920: } elsif ($realm eq 'query') {
3921: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 3922: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
3923: [$spacequalifierrest]);
1.376 albertel 3924: return $ENV{'form.'.$spacequalifierrest};
1.236 www 3925: } elsif ($realm eq 'request') {
1.48 www 3926: # ------------------------------------------------------------- request.browser
3927: if ($space eq 'browser') {
1.430 www 3928: if ($qualifier eq 'textremote') {
3929: if (&mt('textual_remote_display') eq 'on') {
3930: return 1;
3931: } else {
3932: return 0;
3933: }
3934: } else {
3935: return $ENV{'browser.'.$qualifier};
3936: }
1.57 www 3937: # ------------------------------------------------------------ request.filename
3938: } else {
3939: return $ENV{'request.'.$spacequalifierrest};
1.29 www 3940: }
1.28 www 3941: } elsif ($realm eq 'course') {
1.48 www 3942: # ---------------------------------------------------------- course.description
1.218 albertel 3943: return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 3944: } elsif ($realm eq 'resource') {
1.165 www 3945:
1.395 albertel 3946: my $section;
1.359 albertel 3947: if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.165 www 3948:
1.218 albertel 3949: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 3950:
1.60 www 3951: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 3952: if (!$symbparm) { $symbparm=&symbread(); }
3953: my $symbp=$symbparm;
1.409 www 3954: my $mapp=(&decode_symb($symbp))[0];
1.218 albertel 3955:
3956: my $symbparm=$symbp.'.'.$spacequalifierrest;
3957: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
3958:
3959: if (($ENV{'user.name'} eq $uname) &&
3960: ($ENV{'user.domain'} eq $udom)) {
1.255 albertel 3961: $section=$ENV{'request.course.sec'};
1.218 albertel 3962: } else {
1.377 matthew 3963: if (! defined($usection)) {
3964: $section=&usection($udom,$uname,$courseid);
3965: } else {
3966: $section = $usection;
3967: }
1.218 albertel 3968: }
3969:
3970: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
3971: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
3972: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
3973:
3974: my $courselevel=$courseid.'.'.$spacequalifierrest;
3975: my $courselevelr=$courseid.'.'.$symbparm;
3976: my $courselevelm=$courseid.'.'.$mapparm;
1.69 www 3977:
1.60 www 3978: # ----------------------------------------------------------- first, check user
1.379 matthew 3979: #most student don\'t have any data set, check if there is some data
3980: if (! &EXT_cache_status($udom,$uname)) {
1.420 albertel 3981: my $hashid="$udom:$uname";
1.425 albertel 3982: my ($result,$cached)=&is_cached(\%userresdatacache,$hashid,
3983: 'userres');
1.454 albertel 3984: if (!defined($cached)) {
3985: my %resourcedata=&dump('resourcedata',$udom,$uname);
1.420 albertel 3986: $result=\%resourcedata;
1.425 albertel 3987: &do_cache(\%userresdatacache,$hashid,$result,'userres');
1.420 albertel 3988: }
3989: my ($tmp)=keys(%$result);
1.308 albertel 3990: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
1.420 albertel 3991: if ($$result{$courselevelr}) {
3992: return $$result{$courselevelr}; }
3993: if ($$result{$courselevelm}) {
3994: return $$result{$courselevelm}; }
3995: if ($$result{$courselevel}) {
3996: return $$result{$courselevel}; }
1.308 albertel 3997: } else {
1.459 albertel 3998: #error 2 occurs when the .db doesn't exist
3999: if ($tmp!~/error: 2 /) {
1.308 albertel 4000: &logthis("<font color=blue>WARNING:".
4001: " Trying to get resource data for ".
4002: $uname." at ".$udom.": ".
4003: $tmp."</font>");
1.459 albertel 4004: } elsif ($tmp=~/error: 2 /) {
1.379 matthew 4005: &EXT_cache_set($udom,$uname);
1.308 albertel 4006: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
4007: return $tmp;
4008: }
1.218 albertel 4009: }
4010: }
1.95 www 4011:
1.60 www 4012: # -------------------------------------------------------- second, check course
1.96 www 4013:
1.218 albertel 4014: my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
4015: $ENV{'course.'.$courseid.'.domain'},
4016: ($seclevelr,$seclevelm,$seclevel,
4017: $courselevelr,$courselevelm,
4018: $courselevel));
1.287 albertel 4019: if (defined($coursereply)) { return $coursereply; }
1.200 www 4020:
1.60 www 4021: # ------------------------------------------------------ third, check map parms
1.218 albertel 4022: my %parmhash=();
4023: my $thisparm='';
4024: if (tie(%parmhash,'GDBM_File',
4025: $ENV{'request.course.fn'}.'_parms.db',
1.256 albertel 4026: &GDBM_READER(),0640)) {
1.218 albertel 4027: $thisparm=$parmhash{$symbparm};
4028: untie(%parmhash);
4029: }
4030: if ($thisparm) { return $thisparm; }
4031: }
1.60 www 4032: # --------------------------------------------- last, look in resource metadata
1.71 www 4033:
1.218 albertel 4034: $spacequalifierrest=~s/\./\_/;
1.282 albertel 4035: my $filename;
4036: if (!$symbparm) { $symbparm=&symbread(); }
4037: if ($symbparm) {
1.409 www 4038: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 4039: } else {
4040: $filename=$ENV{'request.filename'};
4041: }
4042: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 4043: if (defined($metadata)) { return $metadata; }
1.282 albertel 4044: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 4045: if (defined($metadata)) { return $metadata; }
1.142 www 4046:
1.145 www 4047: # ------------------------------------------------------------------ Cascade up
1.218 albertel 4048: unless ($space eq '0') {
1.336 albertel 4049: my @parts=split(/_/,$space);
4050: my $id=pop(@parts);
4051: my $part=join('_',@parts);
4052: if ($part eq '') { $part='0'; }
4053: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 4054: $symbparm,$udom,$uname,$section,1);
1.337 albertel 4055: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 4056: }
1.395 albertel 4057: if ($recurse) { return undef; }
4058: my $pack_def=&packages_tab_default($filename,$varname);
4059: if (defined($pack_def)) { return $pack_def; }
1.71 www 4060:
1.48 www 4061: # ---------------------------------------------------- Any other user namespace
4062: } elsif ($realm eq 'environment') {
4063: # ----------------------------------------------------------------- environment
1.219 albertel 4064: if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
4065: return $ENV{'environment.'.$spacequalifierrest};
4066: } else {
4067: my %returnhash=&userenvironment($udom,$uname,
4068: $spacequalifierrest);
4069: return $returnhash{$spacequalifierrest};
4070: }
1.28 www 4071: } elsif ($realm eq 'system') {
1.48 www 4072: # ----------------------------------------------------------------- system.time
4073: if ($space eq 'time') {
4074: return time;
4075: }
1.28 www 4076: }
1.48 www 4077: return '';
1.61 www 4078: }
4079:
1.395 albertel 4080: sub packages_tab_default {
4081: my ($uri,$varname)=@_;
4082: my (undef,$part,$name)=split(/\./,$varname);
4083: my $packages=&metadata($uri,'packages');
4084: foreach my $package (split(/,/,$packages)) {
4085: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468 albertel 4086: if (defined($packagetab{"$pack_type&$name&default"})) {
4087: return $packagetab{"$pack_type&$name&default"};
4088: }
4089: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
4090: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 4091: }
4092: }
4093: return undef;
4094: }
4095:
1.334 albertel 4096: sub add_prefix_and_part {
4097: my ($prefix,$part)=@_;
4098: my $keyroot;
4099: if (defined($prefix) && $prefix !~ /^__/) {
4100: # prefix that has a part already
4101: $keyroot=$prefix;
4102: } elsif (defined($prefix)) {
4103: # prefix that is missing a part
4104: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
4105: } else {
4106: # no prefix at all
4107: if (defined($part)) { $keyroot='_'.$part; }
4108: }
4109: return $keyroot;
4110: }
4111:
1.71 www 4112: # ---------------------------------------------------------------- Get metadata
4113:
4114: sub metadata {
1.176 www 4115: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 4116: $uri=&declutter($uri);
1.288 albertel 4117: # if it is a non metadata possible uri return quickly
1.293 matthew 4118: if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
1.423 albertel 4119: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489 albertel 4120: ($uri =~ m|home/[^/]+/public_html/|)) {
1.468 albertel 4121: return undef;
1.288 albertel 4122: }
1.73 www 4123: my $filename=$uri;
4124: $uri=~s/\.meta$//;
1.172 www 4125: #
4126: # Is the metadata already cached?
1.177 www 4127: # Look at timestamp of caching
1.172 www 4128: # Everything is cached by the main uri, libraries are never directly cached
4129: #
1.428 albertel 4130: if (!defined($liburi)) {
4131: my ($result,$cached)=&is_cached(\%metacache,$uri,'meta');
4132: if (defined($cached)) { return $result->{':'.$what}; }
4133: }
4134: {
1.172 www 4135: #
4136: # Is this a recursive call for a library?
4137: #
1.453 albertel 4138: if (! exists($metacache{$uri})) {
4139: $metacache{$uri}={};
4140: }
1.171 www 4141: if ($liburi) {
4142: $liburi=&declutter($liburi);
4143: $filename=$liburi;
1.401 bowersj2 4144: } else {
1.428 albertel 4145: &devalidate_cache(\%metacache,$uri,'meta');
1.401 bowersj2 4146: }
1.140 www 4147: my %metathesekeys=();
1.73 www 4148: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 4149: my $metastring;
4150: if ($uri !~ m|^uploaded/|) {
4151: $metastring=&getfile(&filelocation('',&clutter($filename)));
4152: }
1.208 albertel 4153: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 4154: my $token;
1.140 www 4155: undef %metathesekeys;
1.71 www 4156: while ($token=$parser->get_token) {
1.339 albertel 4157: if ($token->[0] eq 'S') {
4158: if (defined($token->[2]->{'package'})) {
1.172 www 4159: #
4160: # This is a package - get package info
4161: #
1.339 albertel 4162: my $package=$token->[2]->{'package'};
4163: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4164: if (defined($token->[2]->{'id'})) {
4165: $keyroot.='_'.$token->[2]->{'id'};
4166: }
1.453 albertel 4167: if ($metacache{$uri}->{':packages'}) {
4168: $metacache{$uri}->{':packages'}.=','.$package.$keyroot;
1.339 albertel 4169: } else {
1.453 albertel 4170: $metacache{$uri}->{':packages'}=$package.$keyroot;
1.339 albertel 4171: }
4172: foreach (keys %packagetab) {
1.432 albertel 4173: my $part=$keyroot;
4174: $part=~s/^\_//;
4175: if ($_=~/^\Q$package\E\&/ ||
4176: $_=~/^\Q$package\E_0\&/) {
1.339 albertel 4177: my ($pack,$name,$subp)=split(/\&/,$_);
1.395 albertel 4178: # ignore package.tab specified default values
4179: # here &package_tab_default() will fetch those
4180: if ($subp eq 'default') { next; }
1.339 albertel 4181: my $value=$packagetab{$_};
1.432 albertel 4182: my $unikey;
4183: if ($pack =~ /_0$/) {
4184: $unikey='parameter_0_'.$name;
4185: $part=0;
4186: } else {
4187: $unikey='parameter'.$keyroot.'_'.$name;
4188: }
1.339 albertel 4189: if ($subp eq 'display') {
4190: $value.=' [Part: '.$part.']';
4191: }
1.453 albertel 4192: $metacache{$uri}->{':'.$unikey.'.part'}=$part;
1.395 albertel 4193: $metathesekeys{$unikey}=1;
1.453 albertel 4194: unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
4195: $metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 4196: }
1.453 albertel 4197: if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
4198: $metacache{$uri}->{':'.$unikey}=
4199: $metacache{$uri}->{':'.$unikey.'.default'};
1.356 albertel 4200: }
1.339 albertel 4201: }
4202: }
4203: } else {
1.172 www 4204: #
4205: # This is not a package - some other kind of start tag
1.339 albertel 4206: #
4207: my $entry=$token->[1];
4208: my $unikey;
4209: if ($entry eq 'import') {
4210: $unikey='';
4211: } else {
4212: $unikey=$entry;
4213: }
4214: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4215:
4216: if (defined($token->[2]->{'id'})) {
4217: $unikey.='_'.$token->[2]->{'id'};
4218: }
1.175 www 4219:
1.339 albertel 4220: if ($entry eq 'import') {
1.175 www 4221: #
4222: # Importing a library here
1.339 albertel 4223: #
4224: if ($depthcount<20) {
4225: my $location=$parser->get_text('/import');
4226: my $dir=$filename;
4227: $dir=~s|[^/]*$||;
4228: $location=&filelocation($dir,$location);
4229: foreach (sort(split(/\,/,&metadata($uri,'keys',
4230: $location,$unikey,
4231: $depthcount+1)))) {
1.453 albertel 4232: $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
1.339 albertel 4233: $metathesekeys{$_}=1;
4234: }
4235: }
4236: } else {
4237:
4238: if (defined($token->[2]->{'name'})) {
4239: $unikey.='_'.$token->[2]->{'name'};
4240: }
4241: $metathesekeys{$unikey}=1;
4242: foreach (@{$token->[3]}) {
1.453 albertel 4243: $metacache{$uri}->{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339 albertel 4244: }
4245: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.453 albertel 4246: my $default=$metacache{$uri}->{':'.$unikey.'.default'};
1.339 albertel 4247: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
4248: # only ws inside the tag, and not in default, so use default
4249: # as value
1.453 albertel 4250: $metacache{$uri}->{':'.$unikey}=$default;
1.339 albertel 4251: } else {
1.321 albertel 4252: # either something interesting inside the tag or default
4253: # uninteresting
1.453 albertel 4254: $metacache{$uri}->{':'.$unikey}=$internaltext;
1.339 albertel 4255: }
1.172 www 4256: # end of not-a-package not-a-library import
1.339 albertel 4257: }
1.172 www 4258: # end of not-a-package start tag
1.339 albertel 4259: }
1.172 www 4260: # the next is the end of "start tag"
1.339 albertel 4261: }
4262: }
1.483 albertel 4263: my ($extension) = ($uri =~ /\.(\w+)$/);
4264: foreach my $key (sort(keys(%packagetab))) {
4265: #&logthis("extsion1 $extension $key !!");
4266: #no specific packages #how's our extension
4267: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 4268: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 4269: \%metathesekeys);
4270: }
4271: if (!exists($metacache{$uri}->{':packages'})) {
4272: foreach my $key (sort(keys(%packagetab))) {
4273: #no specific packages well let's get default then
4274: if ($key!~/^default&/) { next; }
1.488 albertel 4275: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 4276: \%metathesekeys);
4277: }
4278: }
1.338 www 4279: # are there custom rights to evaluate
1.453 albertel 4280: if ($metacache{$uri}->{':copyright'} eq 'custom') {
1.339 albertel 4281:
1.338 www 4282: #
4283: # Importing a rights file here
1.339 albertel 4284: #
4285: unless ($depthcount) {
1.453 albertel 4286: my $location=$metacache{$uri}->{':customdistributionfile'};
1.339 albertel 4287: my $dir=$filename;
4288: $dir=~s|[^/]*$||;
4289: $location=&filelocation($dir,$location);
4290: foreach (sort(split(/\,/,&metadata($uri,'keys',
4291: $location,'_rights',
4292: $depthcount+1)))) {
1.453 albertel 4293: $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
1.339 albertel 4294: $metathesekeys{$_}=1;
4295: }
4296: }
4297: }
1.453 albertel 4298: $metacache{$uri}->{':keys'}=join(',',keys %metathesekeys);
4299: &metadata_generate_part0(\%metathesekeys,$metacache{$uri},$uri);
4300: $metacache{$uri}->{':allpossiblekeys'}=join(',',keys %metathesekeys);
4301: &do_cache(\%metacache,$uri,$metacache{$uri},'meta');
1.177 www 4302: # this is the end of "was not already recently cached
1.71 www 4303: }
1.428 albertel 4304: return $metacache{$uri}->{':'.$what};
1.261 albertel 4305: }
4306:
1.488 albertel 4307: sub metadata_create_package_def {
1.483 albertel 4308: my ($uri,$key,$package,$metathesekeys)=@_;
4309: my ($pack,$name,$subp)=split(/\&/,$key);
4310: if ($subp eq 'default') { next; }
4311:
4312: if (defined($metacache{$uri}->{':packages'})) {
4313: $metacache{$uri}->{':packages'}.=','.$package;
4314: } else {
4315: $metacache{$uri}->{':packages'}=$package;
4316: }
4317: my $value=$packagetab{$key};
4318: my $unikey;
4319: $unikey='parameter_0_'.$name;
4320: $metacache{$uri}->{':'.$unikey.'.part'}=0;
4321: $$metathesekeys{$unikey}=1;
4322: unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
4323: $metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
4324: }
4325: if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
4326: $metacache{$uri}->{':'.$unikey}=
4327: $metacache{$uri}->{':'.$unikey.'.default'};
4328: }
4329: }
4330:
1.261 albertel 4331: sub metadata_generate_part0 {
4332: my ($metadata,$metacache,$uri) = @_;
4333: my %allnames;
4334: foreach my $metakey (sort keys %$metadata) {
4335: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 4336: my $part=$$metacache{':'.$metakey.'.part'};
4337: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 4338: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 4339: $allnames{$name}=$part;
4340: }
4341: }
4342: }
4343: foreach my $name (keys(%allnames)) {
4344: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 4345: my $key=":parameter_0_$name";
1.261 albertel 4346: $$metacache{"$key.part"}='0';
4347: $$metacache{"$key.name"}=$name;
1.428 albertel 4348: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 4349: $allnames{$name}.'_'.$name.
4350: '.type'};
1.428 albertel 4351: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 4352: '.display'};
4353: my $expr='\\[Part: '.$allnames{$name}.'\\]';
1.479 albertel 4354: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 4355: $$metacache{"$key.display"}=$olddis;
4356: }
1.71 www 4357: }
4358:
1.301 www 4359: # ------------------------------------------------- Get the title of a resource
4360:
4361: sub gettitle {
4362: my $urlsymb=shift;
4363: my $symb=&symbread($urlsymb);
4364: unless ($symb) {
4365: unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
4366: return &metadata($urlsymb,'title');
4367: }
1.425 albertel 4368: my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600);
1.419 albertel 4369: if (defined($cached)) { return $result; }
1.409 www 4370: my ($map,$resid,$url)=&decode_symb($symb);
1.301 www 4371: my $title='';
4372: my %bighash;
4373: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
4374: &GDBM_READER(),0640)) {
4375: my $mapid=$bighash{'map_pc_'.&clutter($map)};
4376: $title=$bighash{'title_'.$mapid.'.'.$resid};
4377: untie %bighash;
4378: }
1.363 www 4379: $title=~s/\&colon\;/\:/gs;
1.301 www 4380: if ($title) {
1.425 albertel 4381: return &do_cache(\%titlecache,$symb,$title,'title');
1.301 www 4382: } else {
4383: return &metadata($urlsymb,'title');
4384: }
4385: }
4386:
1.31 www 4387: # ------------------------------------------------- Update symbolic store links
4388:
4389: sub symblist {
4390: my ($mapname,%newhash)=@_;
1.438 www 4391: $mapname=&deversion(&declutter($mapname));
1.31 www 4392: my %hash;
4393: if (($ENV{'request.course.fn'}) && (%newhash)) {
4394: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256 albertel 4395: &GDBM_WRCREAT(),0640)) {
1.191 harris41 4396: foreach (keys %newhash) {
1.438 www 4397: $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
1.191 harris41 4398: }
1.31 www 4399: if (untie(%hash)) {
4400: return 'ok';
4401: }
4402: }
4403: }
4404: return 'error';
1.212 www 4405: }
4406:
4407: # --------------------------------------------------------------- Verify a symb
4408:
4409: sub symbverify {
1.510 www 4410: my ($symb,$thisurl)=@_;
4411: my $thisfn=$thisurl;
4412: # wrapper not part of symbs
4413: $thisfn=~s/^\/adm\/wrapper//;
1.439 www 4414: $thisfn=&declutter($thisfn);
1.215 www 4415: # direct jump to resource in page or to a sequence - will construct own symbs
4416: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
4417: # check URL part
1.409 www 4418: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 4419:
1.431 www 4420: unless ($url eq $thisfn) { return 0; }
1.213 www 4421:
1.216 www 4422: $symb=&symbclean($symb);
1.510 www 4423: $thisurl=&deversion($thisurl);
1.439 www 4424: $thisfn=&deversion($thisfn);
1.213 www 4425:
4426: my %bighash;
4427: my $okay=0;
1.431 www 4428:
1.213 www 4429: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256 albertel 4430: &GDBM_READER(),0640)) {
1.510 www 4431: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 4432: unless ($ids) {
1.510 www 4433: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 4434: }
4435: if ($ids) {
4436: # ------------------------------------------------------------------- Has ID(s)
4437: foreach (split(/\,/,$ids)) {
4438: my ($mapid,$resid)=split(/\./,$_);
4439: if (
4440: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
4441: eq $symb) {
4442: $okay=1;
4443: }
4444: }
4445: }
1.213 www 4446: untie(%bighash);
4447: }
4448: return $okay;
1.31 www 4449: }
4450:
1.210 www 4451: # --------------------------------------------------------------- Clean-up symb
4452:
4453: sub symbclean {
4454: my $symb=shift;
1.213 www 4455:
1.210 www 4456: # remove version from map
4457: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 4458:
1.210 www 4459: # remove version from URL
4460: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 4461:
1.507 www 4462: # remove wrapper
4463:
1.510 www 4464: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210 www 4465: return $symb;
1.409 www 4466: }
4467:
4468: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 4469:
4470: sub encode_symb {
4471: my ($map,$resid,$url)=@_;
4472: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
4473: }
1.409 www 4474:
4475: sub decode_symb {
1.413 www 4476: my ($map,$resid,$url)=split(/\_\_\_/,shift);
4477: return (&fixversion($map),$resid,&fixversion($url));
4478: }
4479:
4480: sub fixversion {
4481: my $fn=shift;
4482: if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
1.435 www 4483: my %bighash;
4484: my $uri=&clutter($fn);
1.440 www 4485: my $key=$ENV{'request.course.id'}.'_'.$uri;
4486: # is this cached?
4487: my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
4488: 'courseresversion',600);
4489: if (defined($cached)) { return $result; }
4490: # unfortunately not cached, or expired
1.435 www 4491: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.440 www 4492: &GDBM_READER(),0640)) {
4493: if ($bighash{'version_'.$uri}) {
4494: my $version=$bighash{'version_'.$uri};
1.444 www 4495: unless (($version eq 'mostrecent') ||
4496: ($version==&getversion($uri))) {
1.440 www 4497: $uri=~s/\.(\w+)$/\.$version\.$1/;
4498: }
4499: }
4500: untie %bighash;
1.413 www 4501: }
1.440 www 4502: return &do_cache
4503: (\%courseresversioncache,$key,&declutter($uri),'courseresversion');
1.438 www 4504: }
4505:
4506: sub deversion {
4507: my $url=shift;
4508: $url=~s/\.\d+\.(\w+)$/\.$1/;
4509: return $url;
1.210 www 4510: }
4511:
1.31 www 4512: # ------------------------------------------------------ Return symb list entry
4513:
4514: sub symbread {
1.249 www 4515: my ($thisfn,$donotrecurse)=@_;
1.242 www 4516: # no filename provided? try from environment
1.44 www 4517: unless ($thisfn) {
1.210 www 4518: if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44 www 4519: $thisfn=$ENV{'request.filename'};
4520: }
1.242 www 4521: # is that filename actually a symb? Verify, clean, and return
4522: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
4523: if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
4524: }
1.44 www 4525: $thisfn=declutter($thisfn);
1.31 www 4526: my %hash;
1.37 www 4527: my %bighash;
4528: my $syval='';
1.45 www 4529: if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 4530: my $targetfn = $thisfn;
4531: if ( ($thisfn =~ m/^uploaded\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
4532: $targetfn = 'adm/wrapper/'.$thisfn;
4533: }
1.31 www 4534: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256 albertel 4535: &GDBM_READER(),0640)) {
1.481 raeburn 4536: $syval=$hash{$targetfn};
1.37 www 4537: untie(%hash);
4538: }
4539: # ---------------------------------------------------------- There was an entry
4540: if ($syval) {
4541: unless ($syval=~/\_\d+$/) {
4542: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44 www 4543: &appenv('request.ambiguous' => $thisfn);
1.37 www 4544: return '';
4545: }
4546: $syval.=$1;
4547: }
4548: } else {
4549: # ------------------------------------------------------- Was not in symb table
4550: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256 albertel 4551: &GDBM_READER(),0640)) {
1.37 www 4552: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 4553: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 4554: unless ($ids) {
4555: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 4556: }
4557: unless ($ids) {
4558: # alias?
4559: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 4560: }
1.37 www 4561: if ($ids) {
4562: # ------------------------------------------------------------------- Has ID(s)
4563: my @possibilities=split(/\,/,$ids);
1.39 www 4564: if ($#possibilities==0) {
4565: # ----------------------------------------------- There is only one possibility
1.37 www 4566: my ($mapid,$resid)=split(/\./,$ids);
4567: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249 www 4568: } elsif (!$donotrecurse) {
1.39 www 4569: # ------------------------------------------ There is more than one possibility
4570: my $realpossible=0;
1.191 harris41 4571: foreach (@possibilities) {
1.39 www 4572: my $file=$bighash{'src_'.$_};
4573: if (&allowed('bre',$file)) {
4574: my ($mapid,$resid)=split(/\./,$_);
4575: if ($bighash{'map_type_'.$mapid} ne 'page') {
4576: $realpossible++;
4577: $syval=declutter($bighash{'map_id_'.$mapid}).
4578: '___'.$resid;
4579: }
4580: }
1.191 harris41 4581: }
1.39 www 4582: if ($realpossible!=1) { $syval=''; }
1.249 www 4583: } else {
4584: $syval='';
1.37 www 4585: }
4586: }
4587: untie(%bighash)
1.481 raeburn 4588: }
1.31 www 4589: }
1.62 www 4590: if ($syval) {
1.210 www 4591: return &symbclean($syval.'___'.$thisfn);
1.62 www 4592: }
1.31 www 4593: }
1.44 www 4594: &appenv('request.ambiguous' => $thisfn);
1.31 www 4595: return '';
4596: }
4597:
4598: # ---------------------------------------------------------- Return random seed
4599:
1.32 www 4600: sub numval {
4601: my $txt=shift;
4602: $txt=~tr/A-J/0-9/;
4603: $txt=~tr/a-j/0-9/;
4604: $txt=~tr/K-T/0-9/;
4605: $txt=~tr/k-t/0-9/;
4606: $txt=~tr/U-Z/0-5/;
4607: $txt=~tr/u-z/0-5/;
4608: $txt=~s/\D//g;
4609: return int($txt);
1.368 albertel 4610: }
4611:
1.484 albertel 4612: sub numval2 {
4613: my $txt=shift;
4614: $txt=~tr/A-J/0-9/;
4615: $txt=~tr/a-j/0-9/;
4616: $txt=~tr/K-T/0-9/;
4617: $txt=~tr/k-t/0-9/;
4618: $txt=~tr/U-Z/0-5/;
4619: $txt=~tr/u-z/0-5/;
4620: $txt=~s/\D//g;
4621: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
4622: my $total;
4623: foreach my $val (@txts) { $total+=$val; }
4624: return int($total);
4625: }
4626:
1.368 albertel 4627: sub latest_rnd_algorithm_id {
1.501 albertel 4628: return '64bit3';
1.366 albertel 4629: }
1.32 www 4630:
1.503 albertel 4631: sub get_rand_alg {
4632: my ($courseid)=@_;
4633: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
4634: if ($courseid) {
4635: return $ENV{"course.$courseid.rndseed"};
4636: }
4637: return &latest_rnd_algorithm_id();
4638: }
4639:
1.491 albertel 4640: sub getCODE {
4641: if (defined($ENV{'form.CODE'})) { return $ENV{'form.CODE'}; }
4642: if (defined($Apache::lonhomework::parsing_a_problem) &&
4643: defined($Apache::lonhomework::history{'resource.CODE'})) {
4644: return $Apache::lonhomework::history{'resource.CODE'};
4645: }
4646: return undef;
4647: }
4648:
1.31 www 4649: sub rndseed {
1.155 albertel 4650: my ($symb,$courseid,$domain,$username)=@_;
1.366 albertel 4651:
4652: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155 albertel 4653: if (!$symb) {
1.366 albertel 4654: unless ($symb=$wsymb) { return time; }
4655: }
4656: if (!$courseid) { $courseid=$wcourseid; }
4657: if (!$domain) { $domain=$wdomain; }
4658: if (!$username) { $username=$wusername }
1.503 albertel 4659: my $which=&get_rand_alg();
1.491 albertel 4660: if (defined(&getCODE())) {
1.484 albertel 4661: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
1.501 albertel 4662: } elsif ($which eq '64bit3') {
4663: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 4664: } elsif ($which eq '64bit2') {
4665: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 4666: } elsif ($which eq '64bit') {
4667: return &rndseed_64bit($symb,$courseid,$domain,$username);
4668: }
4669: return &rndseed_32bit($symb,$courseid,$domain,$username);
4670: }
4671:
4672: sub rndseed_32bit {
4673: my ($symb,$courseid,$domain,$username)=@_;
4674: {
4675: use integer;
4676: my $symbchck=unpack("%32C*",$symb) << 27;
4677: my $symbseed=numval($symb) << 22;
4678: my $namechck=unpack("%32C*",$username) << 17;
4679: my $nameseed=numval($username) << 12;
4680: my $domainseed=unpack("%32C*",$domain) << 7;
4681: my $courseseed=unpack("%32C*",$courseid);
4682: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
4683: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4684: #&Apache::lonxml::debug("rndseed :$num:$symb");
4685: return $num;
4686: }
4687: }
4688:
4689: sub rndseed_64bit {
4690: my ($symb,$courseid,$domain,$username)=@_;
4691: {
4692: use integer;
4693: my $symbchck=unpack("%32S*",$symb) << 21;
4694: my $symbseed=numval($symb) << 10;
4695: my $namechck=unpack("%32S*",$username);
4696:
4697: my $nameseed=numval($username) << 21;
4698: my $domainseed=unpack("%32S*",$domain) << 10;
4699: my $courseseed=unpack("%32S*",$courseid);
4700:
4701: my $num1=$symbchck+$symbseed+$namechck;
4702: my $num2=$nameseed+$domainseed+$courseseed;
4703: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4704: #&Apache::lonxml::debug("rndseed :$num:$symb");
4705: return "$num1,$num2";
1.155 albertel 4706: }
1.366 albertel 4707: }
4708:
1.443 albertel 4709: sub rndseed_64bit2 {
4710: my ($symb,$courseid,$domain,$username)=@_;
4711: {
4712: use integer;
4713: # strings need to be an even # of cahracters long, it it is odd the
4714: # last characters gets thrown away
4715: my $symbchck=unpack("%32S*",$symb.' ') << 21;
4716: my $symbseed=numval($symb) << 10;
4717: my $namechck=unpack("%32S*",$username.' ');
4718:
4719: my $nameseed=numval($username) << 21;
1.501 albertel 4720: my $domainseed=unpack("%32S*",$domain.' ') << 10;
4721: my $courseseed=unpack("%32S*",$courseid.' ');
4722:
4723: my $num1=$symbchck+$symbseed+$namechck;
4724: my $num2=$nameseed+$domainseed+$courseseed;
4725: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4726: #&Apache::lonxml::debug("rndseed :$num:$symb");
4727: return "$num1,$num2";
4728: }
4729: }
4730:
4731: sub rndseed_64bit3 {
4732: my ($symb,$courseid,$domain,$username)=@_;
4733: {
4734: use integer;
4735: # strings need to be an even # of cahracters long, it it is odd the
4736: # last characters gets thrown away
4737: my $symbchck=unpack("%32S*",$symb.' ') << 21;
4738: my $symbseed=numval2($symb) << 10;
4739: my $namechck=unpack("%32S*",$username.' ');
4740:
4741: my $nameseed=numval2($username) << 21;
1.443 albertel 4742: my $domainseed=unpack("%32S*",$domain.' ') << 10;
4743: my $courseseed=unpack("%32S*",$courseid.' ');
4744:
4745: my $num1=$symbchck+$symbseed+$namechck;
4746: my $num2=$nameseed+$domainseed+$courseseed;
4747: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4748: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.503 albertel 4749: return "$num1:$num2";
1.443 albertel 4750: }
4751: }
4752:
1.366 albertel 4753: sub rndseed_CODE_64bit {
4754: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 4755: {
1.366 albertel 4756: use integer;
1.443 albertel 4757: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 4758: my $symbseed=numval2($symb);
1.491 albertel 4759: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
4760: my $CODEseed=numval(&getCODE());
1.443 albertel 4761: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 4762: my $num1=$symbseed+$CODEchck;
4763: my $num2=$CODEseed+$courseseed+$symbchck;
4764: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366 albertel 4765: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.503 albertel 4766: return "$num1:$num2";
1.366 albertel 4767: }
4768: }
4769:
4770: sub setup_random_from_rndseed {
4771: my ($rndseed)=@_;
1.503 albertel 4772: if ($rndseed =~/([,:])/) {
4773: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 4774: &Math::Random::random_set_seed(abs($num1),abs($num2));
4775: } else {
4776: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 4777: }
1.36 albertel 4778: }
4779:
1.474 albertel 4780: sub latest_receipt_algorithm_id {
4781: return 'receipt2';
4782: }
4783:
1.480 www 4784: sub recunique {
4785: my $fucourseid=shift;
4786: my $unique;
4787: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
4788: $unique=$ENV{"course.$fucourseid.internal.encseed"};
4789: } else {
4790: $unique=$perlvar{'lonReceipt'};
4791: }
4792: return unpack("%32C*",$unique);
4793: }
4794:
4795: sub recprefix {
4796: my $fucourseid=shift;
4797: my $prefix;
4798: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
4799: $prefix=$ENV{"course.$fucourseid.internal.encpref"};
4800: } else {
4801: $prefix=$perlvar{'lonHostID'};
4802: }
4803: return unpack("%32C*",$prefix);
4804: }
4805:
1.76 www 4806: sub ireceipt {
1.474 albertel 4807: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76 www 4808: my $cuname=unpack("%32C*",$funame);
4809: my $cudom=unpack("%32C*",$fudom);
4810: my $cucourseid=unpack("%32C*",$fucourseid);
4811: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 4812: my $cunique=&recunique($fucourseid);
1.474 albertel 4813: my $cpart=unpack("%32S*",$part);
1.480 www 4814: my $return =&recprefix($fucourseid).'-';
1.474 albertel 4815: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
4816: $ENV{'request.state'} eq 'construct') {
4817: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname).
4818: " and ".($cpart%$cudom));
4819:
4820: $return.= ($cunique%$cuname+
4821: $cunique%$cudom+
4822: $cusymb%$cuname+
4823: $cusymb%$cudom+
4824: $cucourseid%$cuname+
4825: $cucourseid%$cudom+
4826: $cpart%$cuname+
4827: $cpart%$cudom);
4828: } else {
4829: $return.= ($cunique%$cuname+
4830: $cunique%$cudom+
4831: $cusymb%$cuname+
4832: $cusymb%$cudom+
4833: $cucourseid%$cuname+
4834: $cucourseid%$cudom);
4835: }
4836: return $return;
1.76 www 4837: }
4838:
4839: sub receipt {
1.474 albertel 4840: my ($part)=@_;
4841: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
4842: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 4843: }
1.260 ng 4844:
1.36 albertel 4845: # ------------------------------------------------------------ Serves up a file
1.472 albertel 4846: # returns either the contents of the file or
4847: # -1 if the file doesn't exist
1.481 raeburn 4848: #
4849: # if the target is a file that was uploaded via DOCS,
4850: # a check will be made to see if a current copy exists on the local server,
4851: # if it does this will be served, otherwise a copy will be retrieved from
4852: # the home server for the course and stored in /home/httpd/html/userfiles on
4853: # the local server.
1.472 albertel 4854:
1.36 albertel 4855: sub getfile {
1.481 raeburn 4856: my ($file,$caller) = @_;
1.482 albertel 4857:
4858: if ($file !~ m|^/*uploaded/(\w+)/(\w+)/(.+)$|) {
4859: # normal file from res space
1.472 albertel 4860: &repcopy($file);
1.481 raeburn 4861: return &readfile($file);
4862: }
1.482 albertel 4863:
4864: my $info;
4865: my $cdom = $1;
4866: my $cnum = $2;
4867: my $filename = $3;
4868: my $path = $Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles';
4869: my ($lwpresp,$rtncode);
4870: my $localfile = $path.'/'.$cdom.'/'.$cnum.'/'.$filename;
4871: if (-e "$localfile") {
4872: my @fileinfo = stat($localfile);
4873: $lwpresp = &getuploaded('HEAD',$file,$cdom,$cnum,\$info,\$rtncode);
4874: if ($lwpresp ne 'ok') {
4875: if ($rtncode eq '404') {
4876: unlink($localfile);
4877: }
4878: return -1;
4879: }
4880: if ($info < $fileinfo[9]) {
4881: return &readfile($localfile);
4882: }
4883: $info = '';
4884: $lwpresp = &getuploaded('GET',$file,$cdom,$cnum,\$info,\$rtncode);
4885: if ($lwpresp ne 'ok') {
4886: return -1;
4887: }
4888: } else {
4889: $lwpresp = &getuploaded('GET',$file,$cdom,$cnum,\$info,\$rtncode);
4890: if ($lwpresp ne 'ok') {
4891: return -1;
4892: }
4893: my @parts = ($cdom,$cnum);
4894: if ($filename =~ m|^(.+)/[^/]+$|) {
4895: push @parts, split(/\//,$1);
4896: }
4897: foreach my $part (@parts) {
4898: $path .= '/'.$part;
4899: if (!-e $path) {
4900: mkdir($path,0770);
4901: }
4902: }
4903: }
4904: open (FILE,">$localfile");
4905: print FILE $info;
4906: close(FILE);
4907: if ($caller eq 'uploadrep') {
4908: return 'ok';
4909: }
4910: return $info;
1.481 raeburn 4911: }
4912:
4913: sub getuploaded {
4914: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
4915: $uri=~s/^\///;
4916: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
4917: my $ua=new LWP::UserAgent;
4918: my $request=new HTTP::Request($reqtype,$uri);
4919: my $response=$ua->request($request);
4920: $$rtncode = $response->code;
1.482 albertel 4921: if (! $response->is_success()) {
4922: return 'failed';
4923: }
4924: if ($reqtype eq 'HEAD') {
1.486 www 4925: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 4926: } elsif ($reqtype eq 'GET') {
4927: $$info = $response->content;
1.472 albertel 4928: }
1.482 albertel 4929: return 'ok';
1.36 albertel 4930: }
4931:
1.481 raeburn 4932: sub readfile {
4933: my $file = shift;
4934: if ( (! -e $file ) || ($file eq '') ) { return -1; };
4935: my $fh;
4936: open($fh,"<$file");
4937: my $a='';
4938: while (<$fh>) { $a .=$_; }
4939: return $a;
4940: }
4941:
1.36 albertel 4942: sub filelocation {
4943: my ($dir,$file) = @_;
4944: my $location;
4945: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59 albertel 4946: if ($file=~m:^/~:) { # is a contruction space reference
4947: $location = $file;
4948: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270 www 4949: } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
4950: $location=$file;
1.36 albertel 4951: } else {
1.479 albertel 4952: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.464 albertel 4953: $file=~s:^/res/:/:;
1.59 albertel 4954: if ( !( $file =~ m:^/:) ) {
4955: $location = $dir. '/'.$file;
4956: } else {
4957: $location = '/home/httpd/html/res'.$file;
4958: }
1.36 albertel 4959: }
4960: $location=~s://+:/:g; # remove duplicate /
1.46 www 4961: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
1.475 albertel 4962: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
1.46 www 4963: return $location;
4964: }
1.36 albertel 4965:
1.46 www 4966: sub hreflocation {
4967: my ($dir,$file)=@_;
1.460 albertel 4968: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
4969: my $finalpath=filelocation($dir,$file);
4970: $finalpath=~s-^/home/httpd/html--;
1.462 albertel 4971: $finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460 albertel 4972: return $finalpath;
4973: } elsif ($file=~m-^/home-) {
4974: $file=~s-^/home/httpd/html--;
1.462 albertel 4975: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460 albertel 4976: return $file;
1.46 www 4977: }
1.462 albertel 4978: return $file;
1.465 albertel 4979: }
4980:
4981: sub current_machine_domains {
4982: my $hostname=$hostname{$perlvar{'lonHostID'}};
4983: my @domains;
4984: while( my($id, $name) = each(%hostname)) {
1.467 matthew 4985: # &logthis("-$id-$name-$hostname-");
1.465 albertel 4986: if ($hostname eq $name) {
4987: push(@domains,$hostdom{$id});
4988: }
4989: }
4990: return @domains;
4991: }
4992:
4993: sub current_machine_ids {
4994: my $hostname=$hostname{$perlvar{'lonHostID'}};
4995: my @ids;
4996: while( my($id, $name) = each(%hostname)) {
1.467 matthew 4997: # &logthis("-$id-$name-$hostname-");
1.465 albertel 4998: if ($hostname eq $name) {
4999: push(@ids,$id);
5000: }
5001: }
5002: return @ids;
1.31 www 5003: }
5004:
5005: # ------------------------------------------------------------- Declutters URLs
5006:
5007: sub declutter {
5008: my $thisfn=shift;
1.479 albertel 5009: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 5010: $thisfn=~s/^\///;
5011: $thisfn=~s/^res\///;
1.235 www 5012: $thisfn=~s/\?.+$//;
1.268 www 5013: return $thisfn;
5014: }
5015:
5016: # ------------------------------------------------------------- Clutter up URLs
5017:
5018: sub clutter {
5019: my $thisfn='/'.&declutter(shift);
1.509 albertel 5020: unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 5021: $thisfn='/res'.$thisfn;
5022: }
1.31 www 5023: return $thisfn;
1.12 www 5024: }
5025:
5026: # -------------------------------------------------------- Escape Special Chars
5027:
5028: sub escape {
5029: my $str=shift;
5030: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
5031: return $str;
5032: }
5033:
5034: # ----------------------------------------------------- Un-Escape Special Chars
5035:
5036: sub unescape {
5037: my $str=shift;
5038: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
5039: return $str;
5040: }
1.11 www 5041:
1.415 albertel 5042: sub mod_perl_version {
5043: if (defined($perlvar{'MODPERL2'})) {
5044: return 2;
5045: }
5046: return 1;
1.436 albertel 5047: }
5048:
5049: sub correct_line_ends {
5050: my ($result)=@_;
5051: $$result =~s/\r\n/\n/mg;
5052: $$result =~s/\r/\n/mg;
1.415 albertel 5053: }
1.1 albertel 5054: # ================================================================ Main Program
5055:
1.184 www 5056: sub goodbye {
1.204 albertel 5057: &logthis("Starting Shut down");
1.443 albertel 5058: #not converted to using infrastruture and probably shouldn't be
1.425 albertel 5059: &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache)));
1.443 albertel 5060: #converted
1.425 albertel 5061: &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.443 albertel 5062: &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache)));
1.425 albertel 5063: &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache)));
5064: &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache)));
5065: #1.1 only
5066: &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache)));
5067: &logthis(sprintf("%-20s is %s",'%usectioncache',scalar(%usectioncache)));
1.440 www 5068: &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache)));
5069: &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache)));
1.184 www 5070: &flushcourselogs();
5071: &logthis("Shutting down");
1.362 albertel 5072: return DONE;
1.184 www 5073: }
5074:
1.179 www 5075: BEGIN {
1.228 harris41 5076: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 5077: unless ($readit) {
1.217 harris41 5078: {
1.448 albertel 5079: open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217 harris41 5080:
5081: while (my $configline=<$config>) {
1.484 albertel 5082: if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1 albertel 5083: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8 www 5084: chomp($varvalue);
1.1 albertel 5085: $perlvar{$varname}=$varvalue;
5086: }
5087: }
1.448 albertel 5088: close($config);
1.1 albertel 5089: }
1.227 harris41 5090: {
1.448 albertel 5091: open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227 harris41 5092:
5093: while (my $configline=<$config>) {
5094: if ($configline =~ /^[^\#]*PerlSetVar/) {
5095: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
5096: chomp($varvalue);
5097: $perlvar{$varname}=$varvalue;
5098: }
5099: }
1.448 albertel 5100: close($config);
1.227 harris41 5101: }
1.1 albertel 5102:
1.327 albertel 5103: # ------------------------------------------------------------ Read domain file
5104: {
5105: %domaindescription = ();
5106: %domain_auth_def = ();
5107: %domain_auth_arg_def = ();
1.448 albertel 5108: my $fh;
5109: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327 albertel 5110: while (<$fh>) {
1.390 matthew 5111: next if (/^(\#|\s*$)/);
5112: # next if /^\#/;
1.327 albertel 5113: chomp;
1.403 www 5114: my ($domain, $domain_description, $def_auth, $def_auth_arg,
5115: $def_lang, $city, $longi, $lati) = split(/:/,$_);
5116: $domain_auth_def{$domain}=$def_auth;
1.327 albertel 5117: $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403 www 5118: $domaindescription{$domain}=$domain_description;
5119: $domain_lang_def{$domain}=$def_lang;
5120: $domain_city{$domain}=$city;
5121: $domain_longi{$domain}=$longi;
5122: $domain_lati{$domain}=$lati;
5123:
1.448 albertel 5124: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327 albertel 5125: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448 albertel 5126: }
1.327 albertel 5127: }
1.448 albertel 5128: close ($fh);
1.327 albertel 5129: }
5130:
5131:
1.1 albertel 5132: # ------------------------------------------------------------- Read hosts file
5133: {
1.448 albertel 5134: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1 albertel 5135:
5136: while (my $configline=<$config>) {
1.303 matthew 5137: next if ($configline =~ /^(\#|\s*$)/);
1.154 www 5138: chomp($configline);
1.245 www 5139: my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252 albertel 5140: if ($id && $domain && $role && $name && $ip) {
5141: $hostname{$id}=$name;
5142: $hostdom{$id}=$domain;
5143: $hostip{$id}=$ip;
1.300 albertel 5144: $iphost{$ip}=$id;
1.252 albertel 5145: if ($role eq 'library') { $libserv{$id}=$name; }
5146: } else {
5147: if ($configline) {
5148: &logthis("Skipping hosts.tab line -$configline-");
5149: }
1.245 www 5150: }
1.1 albertel 5151: }
1.448 albertel 5152: close($config);
1.1 albertel 5153: }
5154:
5155: # ------------------------------------------------------ Read spare server file
5156: {
1.448 albertel 5157: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 5158:
5159: while (my $configline=<$config>) {
5160: chomp($configline);
1.284 matthew 5161: if ($configline) {
1.1 albertel 5162: $spareid{$configline}=1;
5163: }
5164: }
1.448 albertel 5165: close($config);
1.1 albertel 5166: }
1.11 www 5167: # ------------------------------------------------------------ Read permissions
5168: {
1.448 albertel 5169: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 5170:
5171: while (my $configline=<$config>) {
1.448 albertel 5172: chomp($configline);
5173: if ($configline) {
5174: my ($role,$perm)=split(/ /,$configline);
5175: if ($perm ne '') { $pr{$role}=$perm; }
5176: }
1.11 www 5177: }
1.448 albertel 5178: close($config);
1.11 www 5179: }
5180:
5181: # -------------------------------------------- Read plain texts for permissions
5182: {
1.448 albertel 5183: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 5184:
5185: while (my $configline=<$config>) {
1.448 albertel 5186: chomp($configline);
5187: if ($configline) {
5188: my ($short,$plain)=split(/:/,$configline);
5189: if ($plain ne '') { $prp{$short}=$plain; }
5190: }
1.135 www 5191: }
1.448 albertel 5192: close($config);
1.135 www 5193: }
5194:
5195: # ---------------------------------------------------------- Read package table
5196: {
1.448 albertel 5197: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 5198:
5199: while (my $configline=<$config>) {
1.483 albertel 5200: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 5201: chomp($configline);
5202: my ($short,$plain)=split(/:/,$configline);
5203: my ($pack,$name)=split(/\&/,$short);
5204: if ($plain ne '') {
5205: $packagetab{$pack.'&'.$name.'&name'}=$name;
5206: $packagetab{$short}=$plain;
5207: }
1.11 www 5208: }
1.448 albertel 5209: close($config);
1.329 matthew 5210: }
5211:
5212: # ------------- set up temporary directory
5213: {
5214: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
5215:
1.11 www 5216: }
5217:
1.71 www 5218: %metacache=();
1.185 www 5219:
1.281 www 5220: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 5221: $dumpcount=0;
1.22 www 5222:
1.163 harris41 5223: &logtouch();
1.12 www 5224: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195 www 5225: $readit=1;
5226: }
1.1 albertel 5227: }
1.179 www 5228:
1.1 albertel 5229: 1;
1.191 harris41 5230: __END__
5231:
1.243 albertel 5232: =pod
5233:
1.191 harris41 5234: =head1 NAME
5235:
1.243 albertel 5236: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 5237:
5238: =head1 SYNOPSIS
5239:
1.243 albertel 5240: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 5241:
5242: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
5243:
1.243 albertel 5244: Common parameters:
5245:
5246: =over 4
5247:
5248: =item *
5249:
5250: $uname : an internal username (if $cname expecting a course Id specifically)
5251:
5252: =item *
5253:
5254: $udom : a domain (if $cdom expecting a course's domain specifically)
5255:
5256: =item *
5257:
5258: $symb : a resource instance identifier
5259:
5260: =item *
5261:
5262: $namespace : the name of a .db file that contains the data needed or
5263: being set.
5264:
5265: =back
5266:
1.394 bowersj2 5267: =head1 OVERVIEW
1.191 harris41 5268:
1.394 bowersj2 5269: lonnet provides subroutines which interact with the
5270: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
5271: about classes, users, and resources.
1.243 albertel 5272:
5273: For many of these objects you can also use this to store data about
5274: them or modify them in various ways.
1.191 harris41 5275:
1.394 bowersj2 5276: =head2 Symbs
1.191 harris41 5277:
1.394 bowersj2 5278: To identify a specific instance of a resource, LON-CAPA uses symbols
5279: or "symbs"X<symb>. These identifiers are built from the URL of the
5280: map, the resource number of the resource in the map, and the URL of
5281: the resource itself. The latter is somewhat redundant, but might help
5282: if maps change.
5283:
5284: An example is
5285:
5286: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
5287:
5288: The respective map entry is
5289:
5290: <resource id="19" src="/res/msu/korte/tests/part12.problem"
5291: title="Problem 2">
5292: </resource>
5293:
5294: Symbs are used by the random number generator, as well as to store and
5295: restore data specific to a certain instance of for example a problem.
5296:
5297: =head2 Storing And Retrieving Data
5298:
5299: X<store()>X<cstore()>X<restore()>Three of the most important functions
5300: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
5301: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
5302: is is the non-critical message twin of cstore. These functions are for
5303: handlers to store a perl hash to a user's permanent data space in an
5304: easy manner, and to retrieve it again on another call. It is expected
5305: that a handler would use this once at the beginning to retrieve data,
5306: and then again once at the end to send only the new data back.
5307:
5308: The data is stored in the user's data directory on the user's
5309: homeserver under the ID of the course.
5310:
5311: The hash that is returned by restore will have all of the previous
5312: value for all of the elements of the hash.
5313:
5314: Example:
5315:
5316: #creating a hash
5317: my %hash;
5318: $hash{'foo'}='bar';
5319:
5320: #storing it
5321: &Apache::lonnet::cstore(\%hash);
5322:
5323: #changing a value
5324: $hash{'foo'}='notbar';
5325:
5326: #adding a new value
5327: $hash{'bar'}='foo';
5328: &Apache::lonnet::cstore(\%hash);
5329:
5330: #retrieving the hash
5331: my %history=&Apache::lonnet::restore();
5332:
5333: #print the hash
5334: foreach my $key (sort(keys(%history))) {
5335: print("\%history{$key} = $history{$key}");
5336: }
5337:
5338: Will print out:
1.191 harris41 5339:
1.394 bowersj2 5340: %history{1:foo} = bar
5341: %history{1:keys} = foo:timestamp
5342: %history{1:timestamp} = 990455579
5343: %history{2:bar} = foo
5344: %history{2:foo} = notbar
5345: %history{2:keys} = foo:bar:timestamp
5346: %history{2:timestamp} = 990455580
5347: %history{bar} = foo
5348: %history{foo} = notbar
5349: %history{timestamp} = 990455580
5350: %history{version} = 2
5351:
5352: Note that the special hash entries C<keys>, C<version> and
5353: C<timestamp> were added to the hash. C<version> will be equal to the
5354: total number of versions of the data that have been stored. The
5355: C<timestamp> attribute will be the UNIX time the hash was
5356: stored. C<keys> is available in every historical section to list which
5357: keys were added or changed at a specific historical revision of a
5358: hash.
5359:
5360: B<Warning>: do not store the hash that restore returns directly. This
5361: will cause a mess since it will restore the historical keys as if the
5362: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 5363:
1.394 bowersj2 5364: Calling convention:
1.191 harris41 5365:
1.394 bowersj2 5366: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
5367: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 5368:
1.394 bowersj2 5369: For more detailed information, see lonnet specific documentation.
1.191 harris41 5370:
1.394 bowersj2 5371: =head1 RETURN MESSAGES
1.191 harris41 5372:
1.394 bowersj2 5373: =over 4
1.191 harris41 5374:
1.394 bowersj2 5375: =item * B<con_lost>: unable to contact remote host
1.191 harris41 5376:
1.394 bowersj2 5377: =item * B<con_delayed>: unable to contact remote host, message will be delivered
5378: when the connection is brought back up
1.191 harris41 5379:
1.394 bowersj2 5380: =item * B<con_failed>: unable to contact remote host and unable to save message
5381: for later delivery
1.191 harris41 5382:
1.394 bowersj2 5383: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 5384:
1.394 bowersj2 5385: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 5386: that was requested
1.191 harris41 5387:
1.243 albertel 5388: =back
1.191 harris41 5389:
1.243 albertel 5390: =head1 PUBLIC SUBROUTINES
1.191 harris41 5391:
1.243 albertel 5392: =head2 Session Environment Functions
1.191 harris41 5393:
1.243 albertel 5394: =over 4
1.191 harris41 5395:
1.394 bowersj2 5396: =item *
5397: X<appenv()>
5398: B<appenv(%hash)>: the value of %hash is written to
5399: the user envirnoment file, and will be restored for each access this
5400: user makes during this session, also modifies the %ENV for the current
5401: process
1.191 harris41 5402:
5403: =item *
1.394 bowersj2 5404: X<delenv()>
5405: B<delenv($regexp)>: removes all items from the session
5406: environment file that matches the regular expression in $regexp. The
5407: values are also delted from the current processes %ENV.
1.191 harris41 5408:
1.243 albertel 5409: =back
5410:
5411: =head2 User Information
1.191 harris41 5412:
1.243 albertel 5413: =over 4
1.191 harris41 5414:
5415: =item *
1.394 bowersj2 5416: X<queryauthenticate()>
5417: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 5418: authentication scheme
5419:
5420: =item *
1.394 bowersj2 5421: X<authenticate()>
5422: B<authenticate($uname,$upass,$udom)>: try to
5423: authenticate user from domain's lib servers (first use the current
5424: one). C<$upass> should be the users password.
1.191 harris41 5425:
5426: =item *
1.394 bowersj2 5427: X<homeserver()>
5428: B<homeserver($uname,$udom)>: find the server which has
5429: the user's directory and files (there must be only one), this caches
5430: the answer, and also caches if there is a borken connection.
1.191 harris41 5431:
5432: =item *
1.394 bowersj2 5433: X<idget()>
5434: B<idget($udom,@ids)>: find the usernames behind a list of IDs
5435: (IDs are a unique resource in a domain, there must be only 1 ID per
5436: username, and only 1 username per ID in a specific domain) (returns
5437: hash: id=>name,id=>name)
1.191 harris41 5438:
5439: =item *
1.394 bowersj2 5440: X<idrget()>
5441: B<idrget($udom,@unames)>: find the IDs behind a list of
5442: usernames (returns hash: name=>id,name=>id)
1.191 harris41 5443:
5444: =item *
1.394 bowersj2 5445: X<idput()>
5446: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 5447:
5448: =item *
1.394 bowersj2 5449: X<rolesinit()>
5450: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 5451:
5452: =item *
1.394 bowersj2 5453: X<usection()>
5454: B<usection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 5455: course $cname, return section name/number or '' for "not in course"
5456: and '-1' for "no section"
5457:
5458: =item *
1.394 bowersj2 5459: X<userenvironment()>
5460: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 5461: passed in @what from the requested user's environment, returns a hash
5462:
5463: =back
5464:
5465: =head2 User Roles
5466:
5467: =over 4
5468:
5469: =item *
5470:
5471: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
5472: actions
5473: F: full access
5474: U,I,K: authentication modes (cxx only)
5475: '': forbidden
5476: 1: user needs to choose course
5477: 2: browse allowed
5478:
5479: =item *
5480:
5481: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
5482: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
5483: and course level
5484:
5485: =item *
5486:
5487: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
5488: explanation of a user role term
5489:
5490: =back
5491:
5492: =head2 User Modification
5493:
5494: =over 4
5495:
5496: =item *
5497:
5498: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
5499: user for the level given by URL. Optional start and end dates (leave empty
5500: string or zero for "no date")
1.191 harris41 5501:
5502: =item *
5503:
1.243 albertel 5504: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
5505: change a users, password, possible return values are: ok,
5506: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
5507: refused
1.191 harris41 5508:
5509: =item *
5510:
1.243 albertel 5511: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 5512:
5513: =item *
5514:
1.243 albertel 5515: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
5516: modify user
1.191 harris41 5517:
5518: =item *
5519:
1.286 matthew 5520: modifystudent
5521:
5522: modify a students enrollment and identification information.
5523: The course id is resolved based on the current users environment.
5524: This means the envoking user must be a course coordinator or otherwise
5525: associated with a course.
5526:
1.297 matthew 5527: This call is essentially a wrapper for lonnet::modifyuser and
5528: lonnet::modify_student_enrollment
1.286 matthew 5529:
5530: Inputs:
5531:
5532: =over 4
5533:
5534: =item B<$udom> Students loncapa domain
5535:
5536: =item B<$uname> Students loncapa login name
5537:
5538: =item B<$uid> Students id/student number
5539:
5540: =item B<$umode> Students authentication mode
5541:
5542: =item B<$upass> Students password
5543:
5544: =item B<$first> Students first name
5545:
5546: =item B<$middle> Students middle name
5547:
5548: =item B<$last> Students last name
5549:
5550: =item B<$gene> Students generation
5551:
5552: =item B<$usec> Students section in course
5553:
5554: =item B<$end> Unix time of the roles expiration
5555:
5556: =item B<$start> Unix time of the roles start date
5557:
5558: =item B<$forceid> If defined, allow $uid to be changed
5559:
5560: =item B<$desiredhome> server to use as home server for student
5561:
5562: =back
1.297 matthew 5563:
5564: =item *
5565:
5566: modify_student_enrollment
5567:
5568: Change a students enrollment status in a class. The environment variable
5569: 'role.request.course' must be defined for this function to proceed.
5570:
5571: Inputs:
5572:
5573: =over 4
5574:
5575: =item $udom, students domain
5576:
5577: =item $uname, students name
5578:
5579: =item $uid, students user id
5580:
5581: =item $first, students first name
5582:
5583: =item $middle
5584:
5585: =item $last
5586:
5587: =item $gene
5588:
5589: =item $usec
5590:
5591: =item $end
5592:
5593: =item $start
5594:
5595: =back
5596:
1.191 harris41 5597:
5598: =item *
5599:
1.243 albertel 5600: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
5601: custom role; give a custom role to a user for the level given by URL. Specify
5602: name and domain of role author, and role name
1.191 harris41 5603:
5604: =item *
5605:
1.243 albertel 5606: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 5607:
5608: =item *
5609:
1.243 albertel 5610: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
5611:
5612: =back
5613:
5614: =head2 Course Infomation
5615:
5616: =over 4
1.191 harris41 5617:
5618: =item *
5619:
1.243 albertel 5620: coursedescription($courseid) : course description
1.191 harris41 5621:
5622: =item *
5623:
1.243 albertel 5624: courseresdata($coursenum,$coursedomain,@which) : request for current
5625: parameter setting for a specific course, @what should be a list of
5626: parameters to ask about. This routine caches answers for 5 minutes.
5627:
5628: =back
5629:
5630: =head2 Course Modification
5631:
5632: =over 4
1.191 harris41 5633:
5634: =item *
5635:
1.243 albertel 5636: writecoursepref($courseid,%prefs) : write preferences (environment
5637: database) for a course
1.191 harris41 5638:
5639: =item *
5640:
1.243 albertel 5641: createcourse($udom,$description,$url) : make/modify course
5642:
5643: =back
5644:
5645: =head2 Resource Subroutines
5646:
5647: =over 4
1.191 harris41 5648:
5649: =item *
5650:
1.243 albertel 5651: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 5652:
5653: =item *
5654:
1.243 albertel 5655: repcopy($filename) : subscribes to the requested file, and attempts to
5656: replicate from the owning library server, Might return
5657: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
5658: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
5659: resource. Expects the local filesystem pathname
5660: (/home/httpd/html/res/....)
5661:
5662: =back
5663:
5664: =head2 Resource Information
5665:
5666: =over 4
1.191 harris41 5667:
5668: =item *
5669:
1.243 albertel 5670: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
5671: a vairety of different possible values, $varname should be a request
5672: string, and the other parameters can be used to specify who and what
5673: one is asking about.
5674:
5675: Possible values for $varname are environment.lastname (or other item
5676: from the envirnment hash), user.name (or someother aspect about the
5677: user), resource.0.maxtries (or some other part and parameter of a
5678: resource)
1.204 albertel 5679:
5680: =item *
5681:
1.243 albertel 5682: directcondval($number) : get current value of a condition; reads from a state
5683: string
1.204 albertel 5684:
5685: =item *
5686:
1.243 albertel 5687: condval($condidx) : value of condition index based on state
1.204 albertel 5688:
5689: =item *
5690:
1.243 albertel 5691: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
5692: resource's metadata, $what should be either a specific key, or either
5693: 'keys' (to get a list of possible keys) or 'packages' to get a list of
5694: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
5695:
5696: this function automatically caches all requests
1.191 harris41 5697:
5698: =item *
5699:
1.243 albertel 5700: metadata_query($query,$custom,$customshow) : make a metadata query against the
5701: network of library servers; returns file handle of where SQL and regex results
5702: will be stored for query
1.191 harris41 5703:
5704: =item *
5705:
1.243 albertel 5706: symbread($filename) : return symbolic list entry (filename argument optional);
5707: returns the data handle
1.191 harris41 5708:
5709: =item *
5710:
1.243 albertel 5711: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
5712: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
5713: failure, user must be in a course, as it assumes the existance of the
5714: course initi hash, and uses $ENV('request.course.id'}
5715:
1.191 harris41 5716:
5717: =item *
5718:
1.243 albertel 5719: symbclean($symb) : removes versions numbers from a symb, returns the
5720: cleaned symb
1.191 harris41 5721:
5722: =item *
5723:
1.243 albertel 5724: is_on_map($uri) : checks if the $uri is somewhere on the current
5725: course map, user must be in a course for it to work.
1.191 harris41 5726:
5727: =item *
5728:
1.243 albertel 5729: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 5730:
5731: =item *
5732:
1.243 albertel 5733: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
5734: a random seed, all arguments are optional, if they aren't sent it uses the
5735: environment to derive them. Note: if symb isn't sent and it can't get one
5736: from &symbread it will use the current time as its return value
1.191 harris41 5737:
5738: =item *
5739:
1.243 albertel 5740: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
5741: unfakeable, receipt
1.191 harris41 5742:
5743: =item *
5744:
1.243 albertel 5745: receipt() : API to ireceipt working off of ENV values; given out to users
1.191 harris41 5746:
5747: =item *
5748:
1.243 albertel 5749: countacc($url) : count the number of accesses to a given URL
1.191 harris41 5750:
5751: =item *
5752:
1.243 albertel 5753: checkout($symb,$tuname,$tudom,$tcrsid) : creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
1.191 harris41 5754:
5755: =item *
5756:
1.243 albertel 5757: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
1.191 harris41 5758:
5759: =item *
5760:
1.243 albertel 5761: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 5762:
5763: =item *
5764:
1.243 albertel 5765: devalidate($symb) : devalidate temporary spreadsheet calculations,
5766: forcing spreadsheet to reevaluate the resource scores next time.
5767:
5768: =back
5769:
5770: =head2 Storing/Retreiving Data
5771:
5772: =over 4
1.191 harris41 5773:
5774: =item *
5775:
1.243 albertel 5776: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
5777: for this url; hashref needs to be given and should be a \%hashname; the
5778: remaining args aren't required and if they aren't passed or are '' they will
5779: be derived from the ENV
1.191 harris41 5780:
5781: =item *
5782:
1.243 albertel 5783: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
5784: uses critical subroutine
1.191 harris41 5785:
5786: =item *
5787:
1.243 albertel 5788: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
5789: all args are optional
1.191 harris41 5790:
5791: =item *
5792:
1.243 albertel 5793: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
5794: works very similar to store/cstore, but all data is stored in a
5795: temporary location and can be reset using tmpreset, $storehash should
5796: be a hash reference, returns nothing on success
1.191 harris41 5797:
5798: =item *
5799:
1.243 albertel 5800: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
5801: similar to restore, but all data is stored in a temporary location and
5802: can be reset using tmpreset. Returns a hash of values on success,
5803: error string otherwise.
1.191 harris41 5804:
5805: =item *
5806:
1.243 albertel 5807: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
5808: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 5809:
5810: =item *
5811:
1.243 albertel 5812: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
5813: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 5814:
5815: =item *
5816:
1.243 albertel 5817: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
5818: namesp ($udom and $uname are optional)
1.191 harris41 5819:
5820: =item *
5821:
1.243 albertel 5822: dump($namespace,$udom,$uname,$regexp) :
5823: dumps the complete (or key matching regexp) namespace into a hash
5824: ($udom, $uname and $regexp are optional)
1.449 matthew 5825:
5826: =item *
5827:
5828: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
5829: $store can be a scalar, an array reference, or if the amount to be
5830: incremented is > 1, a hash reference.
5831:
5832: ($udom and $uname are optional)
1.191 harris41 5833:
5834: =item *
5835:
1.243 albertel 5836: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
5837: ($udom and $uname are optional)
1.191 harris41 5838:
5839: =item *
5840:
1.243 albertel 5841: cput($namespace,$storehash,$udom,$uname) : critical put
5842: ($udom and $uname are optional)
1.191 harris41 5843:
5844: =item *
5845:
1.243 albertel 5846: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
5847: reference filled in from namesp (encrypts the return communication)
5848: ($udom and $uname are optional)
1.191 harris41 5849:
5850: =item *
5851:
1.243 albertel 5852: log($udom,$name,$home,$message) : write to permanent log for user; use
5853: critical subroutine
5854:
5855: =back
5856:
5857: =head2 Network Status Functions
5858:
5859: =over 4
1.191 harris41 5860:
5861: =item *
5862:
5863: dirlist($uri) : return directory list based on URI
5864:
5865: =item *
5866:
1.243 albertel 5867: spareserver() : find server with least workload from spare.tab
5868:
5869: =back
5870:
5871: =head2 Apache Request
5872:
5873: =over 4
1.191 harris41 5874:
5875: =item *
5876:
1.243 albertel 5877: ssi($url,%hash) : server side include, does a complete request cycle on url to
5878: localhost, posts hash
5879:
5880: =back
5881:
5882: =head2 Data to String to Data
5883:
5884: =over 4
1.191 harris41 5885:
5886: =item *
5887:
1.243 albertel 5888: hash2str(%hash) : convert a hash into a string complete with escaping and '='
5889: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 5890:
5891: =item *
5892:
1.243 albertel 5893: hashref2str($hashref) : convert a hashref into a string complete with
5894: escaping and '=' and '&' separators, supports elements that are
5895: arrayrefs and hashrefs
1.191 harris41 5896:
5897: =item *
5898:
1.243 albertel 5899: arrayref2str($arrayref) : convert an arrayref into a string complete
5900: with escaping and '&' separators, supports elements that are arrayrefs
5901: and hashrefs
1.191 harris41 5902:
5903: =item *
5904:
1.243 albertel 5905: str2hash($string) : convert string to hash using unescaping and
5906: splitting on '=' and '&', supports elements that are arrayrefs and
5907: hashrefs
1.191 harris41 5908:
5909: =item *
5910:
1.243 albertel 5911: str2array($string) : convert string to hash using unescaping and
5912: splitting on '&', supports elements that are arrayrefs and hashrefs
5913:
5914: =back
5915:
5916: =head2 Logging Routines
5917:
5918: =over 4
5919:
5920: These routines allow one to make log messages in the lonnet.log and
5921: lonnet.perm logfiles.
1.191 harris41 5922:
5923: =item *
5924:
1.243 albertel 5925: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 5926:
5927: =item *
5928:
1.243 albertel 5929: logthis() : append message to the normal lonnet.log file, it gets
5930: preiodically rolled over and deleted.
1.191 harris41 5931:
5932: =item *
5933:
1.243 albertel 5934: logperm() : append a permanent message to lonnet.perm.log, this log
5935: file never gets deleted by any automated portion of the system, only
5936: messages of critical importance should go in here.
5937:
5938: =back
5939:
5940: =head2 General File Helper Routines
5941:
5942: =over 4
1.191 harris41 5943:
5944: =item *
5945:
1.481 raeburn 5946: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
5947: (a) files in /uploaded
5948: (i) If a local copy of the file exists -
5949: compares modification date of local copy with last-modified date for
5950: definitive version stored on home server for course. If local copy is
5951: stale, requests a new version from the home server and stores it.
5952: If the original has been removed from the home server, then local copy
5953: is unlinked.
5954: (ii) If local copy does not exist -
5955: requests the file from the home server and stores it.
5956:
5957: If $caller is 'uploadrep':
5958: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
5959: for request for files originally uploaded via DOCS.
5960: - returns 'ok' if fresh local copy now available, -1 otherwise.
5961:
5962: Otherwise:
5963: This indicates a call from the content generation phase of the request.
5964: - returns the entire contents of the file or -1.
5965:
5966: (b) files in /res
5967: - returns the entire contents of a file or -1;
5968: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 5969:
5970: =item *
5971:
1.243 albertel 5972: filelocation($dir,$file) : returns file system location of a file
5973: based on URI; meant to be "fairly clean" absolute reference, $dir is a
5974: directory that relative $file lookups are to looked in ($dir of /a/dir
5975: and a file of ../bob will become /a/bob)
1.191 harris41 5976:
5977: =item *
5978:
5979: hreflocation($dir,$file) : returns file system location or a URL; same as
5980: filelocation except for hrefs
5981:
5982: =item *
5983:
5984: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
5985:
1.243 albertel 5986: =back
5987:
5988: =head2 HTTP Helper Routines
5989:
5990: =over 4
5991:
1.191 harris41 5992: =item *
5993:
5994: escape() : unpack non-word characters into CGI-compatible hex codes
5995:
5996: =item *
5997:
5998: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
5999:
1.243 albertel 6000: =back
6001:
6002: =head1 PRIVATE SUBROUTINES
6003:
6004: =head2 Underlying communication routines (Shouldn't call)
6005:
6006: =over 4
6007:
6008: =item *
6009:
6010: subreply() : tries to pass a message to lonc, returns con_lost if incapable
6011:
6012: =item *
6013:
6014: reply() : uses subreply to send a message to remote machine, logs all failures
6015:
6016: =item *
6017:
6018: critical() : passes a critical message to another server; if cannot
6019: get through then place message in connection buffer directory and
6020: returns con_delayed, if incapable of saving message, returns
6021: con_failed
6022:
6023: =item *
6024:
6025: reconlonc() : tries to reconnect lonc client processes.
6026:
6027: =back
6028:
6029: =head2 Resource Access Logging
6030:
6031: =over 4
6032:
6033: =item *
6034:
6035: flushcourselogs() : flush (save) buffer logs and access logs
6036:
6037: =item *
6038:
6039: courselog($what) : save message for course in hash
6040:
6041: =item *
6042:
6043: courseacclog($what) : save message for course using &courselog(). Perform
6044: special processing for specific resource types (problems, exams, quizzes, etc).
6045:
1.191 harris41 6046: =item *
6047:
6048: goodbye() : flush course logs and log shutting down; it is called in srm.conf
6049: as a PerlChildExitHandler
1.243 albertel 6050:
6051: =back
6052:
6053: =head2 Other
6054:
6055: =over 4
6056:
6057: =item *
6058:
6059: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 6060:
6061: =back
6062:
6063: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>