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