Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.568
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.568 ! albertel 4: # $Id: lonnet.pm,v 1.567 2004/11/10 19:03:04 raeburn 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 $now=time;
1.21 www 2391: my $userroles="user.login.time=$now\n";
1.11 www 2392:
2393: if ($rolesdump ne '') {
1.191 harris41 2394: foreach (split(/&/,$rolesdump)) {
1.21 www 2395: if ($_!~/^rolesdef\&/) {
1.11 www 2396: my ($area,$role)=split(/=/,$_);
1.21 www 2397: $area=~s/\_\w\w$//;
1.11 www 2398: my ($trole,$tend,$tstart)=split(/_/,$role);
1.567 raeburn 2399: $userroles.=&set_arearole($trole,$area,$tstart,$tend);
2400: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2401: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 2402: if (($area ne '') && ($trole ne '')) {
1.347 albertel 2403: my $spec=$trole.'.'.$area;
2404: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2405: if ($trole =~ /^cr\//) {
1.567 raeburn 2406: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.347 albertel 2407: } else {
1.567 raeburn 2408: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 2409: }
1.12 www 2410: }
2411: }
1.191 harris41 2412: }
1.567 raeburn 2413: my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
1.128 www 2414: $userroles.='user.adv='.$adv."\n".
2415: 'user.author='.$author."\n";
1.126 www 2416: $ENV{'user.adv'}=$adv;
1.11 www 2417: }
2418: return $userroles;
2419: }
2420:
1.567 raeburn 2421: sub set_arearole {
2422: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2423: # log the associated role with the area
2424: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2425: return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
2426: }
2427:
2428: sub custom_roleprivs {
2429: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2430: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2431: my $homsvr=homeserver($rauthor,$rdomain);
2432: if ($hostname{$homsvr} ne '') {
2433: my ($rdummy,$roledef)=
2434: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2435: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2436: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2437: if (defined($syspriv)) {
2438: $$allroles{'cm./'}.=':'.$syspriv;
2439: $$allroles{$spec.'./'}.=':'.$syspriv;
2440: }
2441: if ($tdomain ne '') {
2442: if (defined($dompriv)) {
2443: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2444: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2445: }
2446: if (($trest ne '') && (defined($coursepriv))) {
2447: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2448: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2449: }
2450: }
2451: }
2452: }
2453: }
2454:
2455:
2456: sub standard_roleprivs {
2457: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2458: if (defined($pr{$trole.':s'})) {
2459: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2460: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2461: }
2462: if ($tdomain ne '') {
2463: if (defined($pr{$trole.':d'})) {
2464: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2465: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2466: }
2467: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2468: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2469: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2470: }
2471: }
2472: }
2473:
2474: sub set_userprivs {
2475: my ($userroles,$allroles) = @_;
2476: my $author=0;
2477: my $adv=0;
2478: foreach (keys %{$allroles}) {
2479: my %thesepriv=();
2480: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
2481: foreach (split(/:/,$$allroles{$_})) {
2482: if ($_ ne '') {
2483: my ($privilege,$restrictions)=split(/&/,$_);
2484: if ($restrictions eq '') {
2485: $thesepriv{$privilege}='F';
2486: } elsif ($thesepriv{$privilege} ne 'F') {
2487: $thesepriv{$privilege}.=$restrictions;
2488: }
2489: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2490: }
2491: }
2492: my $thesestr='';
2493: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
2494: $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
2495: }
2496: return ($author,$adv);
2497: }
2498:
1.12 www 2499: # --------------------------------------------------------------- get interface
2500:
2501: sub get {
1.131 albertel 2502: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2503: my $items='';
1.191 harris41 2504: foreach (@$storearr) {
1.12 www 2505: $items.=escape($_).'&';
1.191 harris41 2506: }
1.12 www 2507: $items=~s/\&$//;
1.131 albertel 2508: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2509: if (!$uname) { $uname=$ENV{'user.name'}; }
2510: my $uhome=&homeserver($uname,$udomain);
2511:
1.133 albertel 2512: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2513: my @pairs=split(/\&/,$rep);
1.273 albertel 2514: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2515: return @pairs;
2516: }
1.15 www 2517: my %returnhash=();
1.42 www 2518: my $i=0;
1.191 harris41 2519: foreach (@$storearr) {
1.557 albertel 2520: $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42 www 2521: $i++;
1.191 harris41 2522: }
1.15 www 2523: return %returnhash;
1.27 www 2524: }
2525:
2526: # --------------------------------------------------------------- del interface
2527:
2528: sub del {
1.133 albertel 2529: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 2530: my $items='';
1.191 harris41 2531: foreach (@$storearr) {
1.27 www 2532: $items.=escape($_).'&';
1.191 harris41 2533: }
1.27 www 2534: $items=~s/\&$//;
1.133 albertel 2535: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2536: if (!$uname) { $uname=$ENV{'user.name'}; }
2537: my $uhome=&homeserver($uname,$udomain);
2538:
2539: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2540: }
2541:
2542: # -------------------------------------------------------------- dump interface
2543:
2544: sub dump {
1.193 www 2545: my ($namespace,$udomain,$uname,$regexp)=@_;
1.129 albertel 2546: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2547: if (!$uname) { $uname=$ENV{'user.name'}; }
2548: my $uhome=&homeserver($uname,$udomain);
1.193 www 2549: if ($regexp) {
2550: $regexp=&escape($regexp);
2551: } else {
2552: $regexp='.';
2553: }
2554: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12 www 2555: my @pairs=split(/\&/,$rep);
2556: my %returnhash=();
1.191 harris41 2557: foreach (@pairs) {
1.12 www 2558: my ($key,$value)=split(/=/,$_);
1.557 albertel 2559: $returnhash{unescape($key)}=&thaw_unescape($value);
1.318 matthew 2560: }
2561: return %returnhash;
1.407 www 2562: }
2563:
2564: # -------------------------------------------------------------- keys interface
2565:
2566: sub getkeys {
2567: my ($namespace,$udomain,$uname)=@_;
2568: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2569: if (!$uname) { $uname=$ENV{'user.name'}; }
2570: my $uhome=&homeserver($uname,$udomain);
2571: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2572: my @keyarray=();
2573: foreach (split(/\&/,$rep)) {
2574: push (@keyarray,&unescape($_));
2575: }
2576: return @keyarray;
1.318 matthew 2577: }
2578:
1.319 matthew 2579: # --------------------------------------------------------------- currentdump
2580: sub currentdump {
1.328 matthew 2581: my ($courseid,$sdom,$sname)=@_;
1.326 matthew 2582: $courseid = $ENV{'request.course.id'} if (! defined($courseid));
2583: $sdom = $ENV{'user.domain'} if (! defined($sdom));
2584: $sname = $ENV{'user.name'} if (! defined($sname));
2585: my $uhome = &homeserver($sname,$sdom);
2586: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 2587: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 2588: #
1.318 matthew 2589: my %returnhash=();
1.319 matthew 2590: #
2591: if ($rep eq "unknown_cmd") {
2592: # an old lond will not know currentdump
2593: # Do a dump and make it look like a currentdump
1.326 matthew 2594: my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319 matthew 2595: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2596: my %hash = @tmp;
2597: @tmp=();
1.424 matthew 2598: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 2599: } else {
2600: my @pairs=split(/\&/,$rep);
2601: foreach (@pairs) {
2602: my ($key,$value)=split(/=/,$_);
2603: my ($symb,$param) = split(/:/,$key);
2604: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 2605: &thaw_unescape($value);
1.319 matthew 2606: }
1.191 harris41 2607: }
1.12 www 2608: return %returnhash;
1.424 matthew 2609: }
2610:
2611: sub convert_dump_to_currentdump{
2612: my %hash = %{shift()};
2613: my %returnhash;
2614: # Code ripped from lond, essentially. The only difference
2615: # here is the unescaping done by lonnet::dump(). Conceivably
2616: # we might run in to problems with parameter names =~ /^v\./
2617: while (my ($key,$value) = each(%hash)) {
2618: my ($v,$symb,$param) = split(/:/,$key);
2619: next if ($v eq 'version' || $symb eq 'keys');
2620: next if (exists($returnhash{$symb}) &&
2621: exists($returnhash{$symb}->{$param}) &&
2622: $returnhash{$symb}->{'v.'.$param} > $v);
2623: $returnhash{$symb}->{$param}=$value;
2624: $returnhash{$symb}->{'v.'.$param}=$v;
2625: }
2626: #
2627: # Remove all of the keys in the hashes which keep track of
2628: # the version of the parameter.
2629: while (my ($symb,$param_hash) = each(%returnhash)) {
2630: # use a foreach because we are going to delete from the hash.
2631: foreach my $key (keys(%$param_hash)) {
2632: delete($param_hash->{$key}) if ($key =~ /^v\./);
2633: }
2634: }
2635: return \%returnhash;
1.12 www 2636: }
2637:
1.449 matthew 2638: # --------------------------------------------------------------- inc interface
2639:
2640: sub inc {
2641: my ($namespace,$store,$udomain,$uname) = @_;
2642: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2643: if (!$uname) { $uname=$ENV{'user.name'}; }
2644: my $uhome=&homeserver($uname,$udomain);
2645: my $items='';
2646: if (! ref($store)) {
2647: # got a single value, so use that instead
2648: $items = &escape($store).'=&';
2649: } elsif (ref($store) eq 'SCALAR') {
2650: $items = &escape($$store).'=&';
2651: } elsif (ref($store) eq 'ARRAY') {
2652: $items = join('=&',map {&escape($_);} @{$store});
2653: } elsif (ref($store) eq 'HASH') {
2654: while (my($key,$value) = each(%{$store})) {
2655: $items.= &escape($key).'='.&escape($value).'&';
2656: }
2657: }
2658: $items=~s/\&$//;
2659: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
2660: }
2661:
1.12 www 2662: # --------------------------------------------------------------- put interface
2663:
2664: sub put {
1.134 albertel 2665: my ($namespace,$storehash,$udomain,$uname)=@_;
2666: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2667: if (!$uname) { $uname=$ENV{'user.name'}; }
2668: my $uhome=&homeserver($uname,$udomain);
1.12 www 2669: my $items='';
1.191 harris41 2670: foreach (keys %$storehash) {
1.557 albertel 2671: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2672: }
1.12 www 2673: $items=~s/\&$//;
1.134 albertel 2674: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 2675: }
2676:
1.524 raeburn 2677: # ---------------------------------------------------------- putstore interface
2678:
2679: sub putstore {
2680: my ($namespace,$storehash,$udomain,$uname)=@_;
2681: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2682: if (!$uname) { $uname=$ENV{'user.name'}; }
2683: my $uhome=&homeserver($uname,$udomain);
2684: my $items='';
2685: my %allitems = ();
2686: foreach (keys %$storehash) {
2687: if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
2688: my $key = $1.':keys:'.$2;
2689: $allitems{$key} .= $3.':';
2690: }
2691: $items.=$_.'='.&escape($$storehash{$_}).'&';
2692: }
2693: foreach (keys %allitems) {
2694: $allitems{$_} =~ s/\:$//;
2695: $items.= $_.'='.$allitems{$_}.'&';
2696: }
2697: $items=~s/\&$//;
2698: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
2699: }
2700:
1.47 www 2701: # ------------------------------------------------------ critical put interface
2702:
2703: sub cput {
1.134 albertel 2704: my ($namespace,$storehash,$udomain,$uname)=@_;
2705: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2706: if (!$uname) { $uname=$ENV{'user.name'}; }
2707: my $uhome=&homeserver($uname,$udomain);
1.47 www 2708: my $items='';
1.191 harris41 2709: foreach (keys %$storehash) {
1.557 albertel 2710: $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2711: }
1.47 www 2712: $items=~s/\&$//;
1.134 albertel 2713: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2714: }
2715:
2716: # -------------------------------------------------------------- eget interface
2717:
2718: sub eget {
1.133 albertel 2719: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2720: my $items='';
1.191 harris41 2721: foreach (@$storearr) {
1.12 www 2722: $items.=escape($_).'&';
1.191 harris41 2723: }
1.12 www 2724: $items=~s/\&$//;
1.133 albertel 2725: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2726: if (!$uname) { $uname=$ENV{'user.name'}; }
2727: my $uhome=&homeserver($uname,$udomain);
2728: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2729: my @pairs=split(/\&/,$rep);
2730: my %returnhash=();
1.42 www 2731: my $i=0;
1.191 harris41 2732: foreach (@$storearr) {
1.557 albertel 2733: $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42 www 2734: $i++;
1.191 harris41 2735: }
1.12 www 2736: return %returnhash;
2737: }
2738:
1.341 www 2739: # ---------------------------------------------- Custom access rule evaluation
2740:
2741: sub customaccess {
2742: my ($priv,$uri)=@_;
1.342 www 2743: my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343 www 2744: $urealm=~s/^\W//;
2745: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341 www 2746: my $access=0;
2747: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342 www 2748: my ($effect,$realm,$role)=split(/\:/,$_);
1.343 www 2749: if ($role) {
2750: if ($role ne $urole) { next; }
2751: }
2752: foreach (split(/\s*\,\s*/,$realm)) {
2753: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
2754: if ($tdom) {
2755: if ($tdom ne $udom) { next; }
2756: }
2757: if ($tcrs) {
2758: if ($tcrs ne $ucrs) { next; }
2759: }
2760: if ($tsec) {
2761: if ($tsec ne $usec) { next; }
2762: }
2763: $access=($effect eq 'allow');
2764: last;
1.342 www 2765: }
1.402 bowersj2 2766: if ($realm eq '' && $role eq '') {
2767: $access=($effect eq 'allow');
2768: }
1.341 www 2769: }
2770: return $access;
2771: }
2772:
1.103 harris41 2773: # ------------------------------------------------- Check for a user privilege
1.12 www 2774:
2775: sub allowed {
2776: my ($priv,$uri)=@_;
1.439 www 2777: $uri=&deversion($uri);
1.152 www 2778: my $orguri=$uri;
1.52 www 2779: $uri=&declutter($uri);
1.545 banghart 2780:
2781:
2782:
1.398 albertel 2783: if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
1.54 www 2784: # Free bre access to adm and meta resources
1.529 albertel 2785: if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|))
2786: || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14 www 2787: return 'F';
1.159 www 2788: }
2789:
1.545 banghart 2790: # Free bre access to user's own portfolio contents
1.546 albertel 2791: my ($space,$domain,$name,$dir)=split('/',$uri);
2792: if (('uploaded' eq $space) && ($ENV{'user.name'} eq $name) &&
2793: ($ENV{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545 banghart 2794: return 'F';
2795: }
2796:
1.159 www 2797: # Free bre to public access
2798:
2799: if ($priv eq 'bre') {
1.238 www 2800: my $copyright=&metadata($uri,'copyright');
1.301 www 2801: if (($copyright eq 'public') && (!$ENV{'request.course.id'})) {
2802: return 'F';
2803: }
1.238 www 2804: if ($copyright eq 'priv') {
2805: $uri=~/([^\/]+)\/([^\/]+)\//;
2806: unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
2807: return '';
2808: }
2809: }
2810: if ($copyright eq 'domain') {
2811: $uri=~/([^\/]+)\/([^\/]+)\//;
2812: unless (($ENV{'user.domain'} eq $1) ||
2813: ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
2814: return '';
2815: }
1.262 matthew 2816: }
2817: if ($ENV{'request.role'}=~ /li\.\//) {
2818: # Library role, so allow browsing of resources in this domain.
2819: return 'F';
1.238 www 2820: }
1.341 www 2821: if ($copyright eq 'custom') {
2822: unless (&customaccess($priv,$uri)) { return ''; }
2823: }
1.14 www 2824: }
1.264 matthew 2825: # Domain coordinator is trying to create a course
2826: if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
2827: # uri is the requested domain in this case.
2828: # comparison to 'request.role.domain' shows if the user has selected
2829: # a role of dc for the domain in question.
2830: return 'F' if ($uri eq $ENV{'request.role.domain'});
2831: }
1.29 www 2832:
1.52 www 2833: my $thisallowed='';
2834: my $statecond=0;
2835: my $courseprivid='';
2836:
2837: # Course
2838:
1.479 albertel 2839: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2840: $thisallowed.=$1;
2841: }
1.29 www 2842:
1.52 www 2843: # Domain
2844:
2845: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 2846: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 2847: $thisallowed.=$1;
2848: }
1.52 www 2849:
2850: # Course: uri itself is a course
1.66 www 2851: my $courseuri=$uri;
2852: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 2853: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 2854:
1.83 www 2855: if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.479 albertel 2856: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 2857: $thisallowed.=$1;
2858: }
1.29 www 2859:
1.314 www 2860: # URI is an uploaded document for this course
2861:
1.492 albertel 2862: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
2863: my $refuri=$ENV{'httpref.'.$orguri};
2864: if ($refuri) {
2865: if ($refuri =~ m|^/adm/|) {
2866: $thisallowed='F';
2867: }
2868: }
1.314 www 2869: }
1.492 albertel 2870:
1.52 www 2871: # Full access at system, domain or course-wide level? Exit.
1.29 www 2872:
2873: if ($thisallowed=~/F/) {
2874: return 'F';
2875: }
2876:
1.52 www 2877: # If this is generating or modifying users, exit with special codes
1.29 www 2878:
1.479 albertel 2879: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
1.52 www 2880: return $thisallowed;
2881: }
2882: #
1.103 harris41 2883: # Gathered so far: system, domain and course wide privileges
1.52 www 2884: #
2885: # Course: See if uri or referer is an individual resource that is part of
2886: # the course
2887:
2888: if ($ENV{'request.course.id'}) {
1.232 www 2889:
1.52 www 2890: $courseprivid=$ENV{'request.course.id'};
2891: if ($ENV{'request.course.sec'}) {
2892: $courseprivid.='/'.$ENV{'request.course.sec'};
2893: }
2894: $courseprivid=~s/\_/\//;
2895: my $checkreferer=1;
1.232 www 2896: my ($match,$cond)=&is_on_map($uri);
2897: if ($match) {
2898: $statecond=$cond;
1.52 www 2899: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1.479 albertel 2900: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2901: $thisallowed.=$1;
2902: $checkreferer=0;
2903: }
1.29 www 2904: }
1.83 www 2905:
1.148 www 2906: if ($checkreferer) {
1.152 www 2907: my $refuri=$ENV{'httpref.'.$orguri};
1.148 www 2908: unless ($refuri) {
1.191 harris41 2909: foreach (keys %ENV) {
1.148 www 2910: if ($_=~/^httpref\..*\*/) {
2911: my $pattern=$_;
1.156 www 2912: $pattern=~s/^httpref\.\/res\///;
1.148 www 2913: $pattern=~s/\*/\[\^\/\]\+/g;
2914: $pattern=~s/\//\\\//g;
1.152 www 2915: if ($orguri=~/$pattern/) {
1.148 www 2916: $refuri=$ENV{$_};
2917: }
2918: }
1.191 harris41 2919: }
1.148 www 2920: }
1.232 www 2921:
1.148 www 2922: if ($refuri) {
1.152 www 2923: $refuri=&declutter($refuri);
1.232 www 2924: my ($match,$cond)=&is_on_map($refuri);
2925: if ($match) {
2926: my $refstatecond=$cond;
1.52 www 2927: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
1.479 albertel 2928: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2929: $thisallowed.=$1;
1.53 www 2930: $uri=$refuri;
2931: $statecond=$refstatecond;
1.52 www 2932: }
2933: }
1.148 www 2934: }
1.29 www 2935: }
1.52 www 2936: }
1.29 www 2937:
1.52 www 2938: #
1.103 harris41 2939: # Gathered now: all privileges that could apply, and condition number
1.52 www 2940: #
2941: #
2942: # Full or no access?
2943: #
1.29 www 2944:
1.52 www 2945: if ($thisallowed=~/F/) {
2946: return 'F';
2947: }
1.29 www 2948:
1.52 www 2949: unless ($thisallowed) {
2950: return '';
2951: }
1.29 www 2952:
1.52 www 2953: # Restrictions exist, deal with them
2954: #
2955: # C:according to course preferences
2956: # R:according to resource settings
2957: # L:unless locked
2958: # X:according to user session state
2959: #
2960:
2961: # Possibly locked functionality, check all courses
1.54 www 2962: # Locks might take effect only after 10 minutes cache expiration for other
2963: # courses, and 2 minutes for current course
1.52 www 2964:
2965: my $envkey;
2966: if ($thisallowed=~/L/) {
2967: foreach $envkey (keys %ENV) {
1.54 www 2968: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
2969: my $courseid=$2;
2970: my $roleid=$1.'.'.$2;
1.92 www 2971: $courseid=~s/^\///;
1.54 www 2972: my $expiretime=600;
2973: if ($ENV{'request.role'} eq $roleid) {
2974: $expiretime=120;
2975: }
2976: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
2977: my $prefix='course.'.$cdom.'_'.$cnum.'.';
2978: if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
2979: &coursedescription($courseid);
2980: }
1.479 albertel 2981: if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
1.54 www 2982: || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
2983: if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57 www 2984: &log($ENV{'user.domain'},$ENV{'user.name'},
1.239 www 2985: $ENV{'user.home'},
1.57 www 2986: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 2987: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54 www 2988: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 2989: return '';
2990: }
2991: }
1.479 albertel 2992: if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
1.54 www 2993: || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
2994: if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57 www 2995: &log($ENV{'user.domain'},$ENV{'user.name'},
1.239 www 2996: $ENV{'user.home'},
1.57 www 2997: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 2998: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54 www 2999: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3000: return '';
3001: }
3002: }
3003: }
1.29 www 3004: }
1.52 www 3005: }
3006:
3007: #
3008: # Rest of the restrictions depend on selected course
3009: #
3010:
3011: unless ($ENV{'request.course.id'}) {
3012: return '1';
3013: }
1.29 www 3014:
1.52 www 3015: #
3016: # Now user is definitely in a course
3017: #
1.53 www 3018:
3019:
3020: # Course preferences
3021:
3022: if ($thisallowed=~/C/) {
1.54 www 3023: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237 www 3024: my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54 www 3025: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 3026: =~/\Q$rolecode\E/) {
1.57 www 3027: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
3028: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237 www 3029: $ENV{'request.course.id'});
3030: return '';
3031: }
3032:
3033: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 3034: =~/\Q$unamedom\E/) {
1.237 www 3035: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
3036: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54 www 3037: $ENV{'request.course.id'});
3038: return '';
3039: }
1.53 www 3040: }
3041:
3042: # Resource preferences
3043:
3044: if ($thisallowed=~/R/) {
1.54 www 3045: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.479 albertel 3046: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.341 www 3047: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57 www 3048: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341 www 3049: return '';
1.54 www 3050: }
1.53 www 3051: }
1.30 www 3052:
1.246 www 3053: # Restricted by state or randomout?
1.30 www 3054:
1.52 www 3055: if ($thisallowed=~/X/) {
1.247 www 3056: if ($ENV{'acc.randomout'}) {
1.249 www 3057: my $symb=&symbread($uri,1);
1.479 albertel 3058: if (($symb) && ($ENV{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 3059: return '';
3060: }
1.247 www 3061: }
3062: if (&condval($statecond)) {
1.52 www 3063: return '2';
3064: } else {
3065: return '';
3066: }
3067: }
1.30 www 3068:
1.52 www 3069: return 'F';
1.232 www 3070: }
3071:
3072: # --------------------------------------------------- Is a resource on the map?
3073:
3074: sub is_on_map {
3075: my $uri=&declutter(shift);
1.435 www 3076: $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232 www 3077: my @uriparts=split(/\//,$uri);
3078: my $filename=$uriparts[$#uriparts];
3079: my $pathname=$uri;
1.289 bowersj2 3080: $pathname=~s|/\Q$filename\E$||;
1.332 www 3081: $pathname=~s/^adm\/wrapper\///;
1.289 bowersj2 3082: #Trying to find the conditional for the file
1.232 www 3083: my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 3084: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 3085: if ($match) {
1.289 bowersj2 3086: return (1,$1);
3087: } else {
1.434 www 3088: return (0,0);
1.289 bowersj2 3089: }
1.12 www 3090: }
3091:
1.427 www 3092: # --------------------------------------------------------- Get symb from alias
3093:
3094: sub get_symb_from_alias {
3095: my $symb=shift;
3096: my ($map,$resid,$url)=&decode_symb($symb);
3097: # Already is a symb
3098: if ($url) { return $symb; }
3099: # Must be an alias
3100: my $aliassymb='';
3101: my %bighash;
3102: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
3103: &GDBM_READER(),0640)) {
3104: my $rid=$bighash{'mapalias_'.$symb};
3105: if ($rid) {
3106: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 3107: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3108: $resid,$bighash{'src_'.$rid});
1.427 www 3109: }
3110: untie %bighash;
3111: }
3112: return $aliassymb;
3113: }
3114:
1.12 www 3115: # ----------------------------------------------------------------- Define Role
3116:
3117: sub definerole {
3118: if (allowed('mcr','/')) {
3119: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392 www 3120: foreach (split(':',$sysrole)) {
1.21 www 3121: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3122: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
3123: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
3124: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3125: return "refused:s:$crole&$cqual";
3126: }
3127: }
1.191 harris41 3128: }
1.392 www 3129: foreach (split(':',$domrole)) {
1.21 www 3130: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3131: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
3132: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
3133: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 3134: return "refused:d:$crole&$cqual";
3135: }
3136: }
1.191 harris41 3137: }
1.392 www 3138: foreach (split(':',$courole)) {
1.21 www 3139: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3140: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3141: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3142: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3143: return "refused:c:$crole&$cqual";
3144: }
3145: }
1.191 harris41 3146: }
1.12 www 3147: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
3148: "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21 www 3149: "rolesdef_$rolename=".
3150: escape($sysrole.'_'.$domrole.'_'.$courole);
1.12 www 3151: return reply($command,$ENV{'user.home'});
3152: } else {
3153: return 'refused';
3154: }
1.105 harris41 3155: }
3156:
3157: # ---------------- Make a metadata query against the network of library servers
3158:
3159: sub metadata_query {
1.244 matthew 3160: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 3161: my %rhash;
1.244 matthew 3162: my @server_list = (defined($server_array) ? @$server_array
3163: : keys(%libserv) );
3164: for my $server (@server_list) {
1.118 harris41 3165: unless ($custom or $customshow) {
3166: my $reply=&reply("querysend:".&escape($query),$server);
3167: $rhash{$server}=$reply;
3168: }
3169: else {
3170: my $reply=&reply("querysend:".&escape($query).':'.
3171: &escape($custom).':'.&escape($customshow),
3172: $server);
3173: $rhash{$server}=$reply;
3174: }
1.112 harris41 3175: }
1.118 harris41 3176: return \%rhash;
1.240 www 3177: }
3178:
3179: # ----------------------------------------- Send log queries and wait for reply
3180:
3181: sub log_query {
3182: my ($uname,$udom,$query,%filters)=@_;
3183: my $uhome=&homeserver($uname,$udom);
3184: if ($uhome eq 'no_host') { return 'error: no_host'; }
3185: my $uhost=$hostname{$uhome};
1.241 www 3186: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240 www 3187: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3188: $uhome);
1.479 albertel 3189: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 3190: return get_query_reply($queryid);
3191: }
3192:
1.508 raeburn 3193: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 3194:
3195: sub fetch_enrollment_query {
1.511 raeburn 3196: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 3197: my $homeserver;
1.547 raeburn 3198: my $maxtries = 1;
1.508 raeburn 3199: if ($context eq 'automated') {
3200: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 3201: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 3202: } else {
3203: $homeserver = &homeserver($cnum,$dom);
3204: }
1.506 raeburn 3205: my $host=$hostname{$homeserver};
3206: my $cmd = '';
3207: foreach (keys %{$affiliatesref}) {
1.508 raeburn 3208: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506 raeburn 3209: }
3210: $cmd =~ s/%%$//;
3211: $cmd = &escape($cmd);
3212: my $query = 'fetchenrollment';
3213: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$ENV{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 3214: unless ($queryid=~/^\Q$host\E\_/) {
3215: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
3216: return 'error: '.$queryid;
3217: }
1.506 raeburn 3218: my $reply = &get_query_reply($queryid);
1.547 raeburn 3219: my $tries = 1;
3220: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
3221: $reply = &get_query_reply($queryid);
3222: $tries ++;
3223: }
1.526 raeburn 3224: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.547 raeburn 3225: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$ENV{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 3226: } else {
1.515 raeburn 3227: my @responses = split/:/,$reply;
3228: if ($homeserver eq $perlvar{'lonHostID'}) {
3229: foreach (@responses) {
3230: my ($key,$value) = split/=/,$_;
3231: $$replyref{$key} = $value;
3232: }
3233: } else {
1.506 raeburn 3234: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
3235: foreach (@responses) {
3236: my ($key,$value) = split/=/,$_;
3237: $$replyref{$key} = $value;
3238: if ($value > 0) {
3239: foreach (@{$$affiliatesref{$key}}) {
3240: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
3241: my $destname = $pathname.'/'.$filename;
3242: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 3243: if ($xml_classlist =~ /^error/) {
3244: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
3245: } else {
1.506 raeburn 3246: if ( open(FILE,">$destname") ) {
3247: print FILE &unescape($xml_classlist);
3248: close(FILE);
1.526 raeburn 3249: } else {
3250: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 3251: }
3252: }
3253: }
3254: }
3255: }
3256: }
3257: return 'ok';
3258: }
3259: return 'error';
3260: }
3261:
1.242 www 3262: sub get_query_reply {
3263: my $queryid=shift;
1.240 www 3264: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
3265: my $reply='';
3266: for (1..100) {
3267: sleep 2;
3268: if (-e $replyfile.'.end') {
1.448 albertel 3269: if (open(my $fh,$replyfile)) {
1.240 www 3270: $reply.=<$fh>;
1.448 albertel 3271: close($fh);
1.240 www 3272: } else { return 'error: reply_file_error'; }
1.242 www 3273: return &unescape($reply);
3274: }
1.240 www 3275: }
1.242 www 3276: return 'timeout:'.$queryid;
1.240 www 3277: }
3278:
3279: sub courselog_query {
1.241 www 3280: #
3281: # possible filters:
3282: # url: url or symb
3283: # username
3284: # domain
3285: # action: view, submit, grade
3286: # start: timestamp
3287: # end: timestamp
3288: #
1.240 www 3289: my (%filters)=@_;
3290: unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241 www 3291: if ($filters{'url'}) {
3292: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
3293: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
3294: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
3295: }
1.240 www 3296: my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
3297: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
3298: return &log_query($cname,$cdom,'courselog',%filters);
3299: }
3300:
3301: sub userlog_query {
3302: my ($uname,$udom,%filters)=@_;
3303: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 3304: }
3305:
1.506 raeburn 3306: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
3307:
3308: sub auto_run {
1.508 raeburn 3309: my ($cnum,$cdom) = @_;
3310: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 3311: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 3312: return $response;
3313: }
3314:
3315: sub auto_get_sections {
1.508 raeburn 3316: my ($cnum,$cdom,$inst_coursecode) = @_;
3317: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 3318: my @secs = ();
1.511 raeburn 3319: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 3320: unless ($response eq 'refused') {
3321: @secs = split/:/,$response;
3322: }
3323: return @secs;
3324: }
3325:
3326: sub auto_new_course {
1.508 raeburn 3327: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
3328: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 3329: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 3330: return $response;
3331: }
3332:
3333: sub auto_validate_courseID {
1.508 raeburn 3334: my ($cnum,$cdom,$inst_course_id) = @_;
3335: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 3336: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 3337: return $response;
3338: }
3339:
3340: sub auto_create_password {
1.508 raeburn 3341: my ($cnum,$cdom,$authparam) = @_;
3342: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 3343: my $create_passwd = 0;
3344: my $authchk = '';
1.511 raeburn 3345: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 3346: if ($response eq 'refused') {
3347: $authchk = 'refused';
3348: } else {
3349: ($authparam,$create_passwd,$authchk) = split/:/,$response;
3350: }
3351: return ($authparam,$create_passwd,$authchk);
3352: }
3353:
1.521 raeburn 3354: sub auto_instcode_format {
3355: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
3356: my $courses = '';
3357: my $homeserver;
3358: if ($caller eq 'global') {
3359: $homeserver = $perlvar{'lonHostID'};
3360: } else {
3361: $homeserver = &homeserver($caller,$codedom);
3362: }
3363: my $host=$hostname{$homeserver};
3364: foreach (keys %{$instcodes}) {
3365: $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
3366: }
3367: chop($courses);
3368: my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
3369: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
3370: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
3371: %{$codes} = &str2hash($codes_str);
3372: @{$codetitles} = &str2array($codetitles_str);
3373: %{$cat_titles} = &str2hash($cat_titles_str);
3374: %{$cat_order} = &str2hash($cat_order_str);
3375: return 'ok';
3376: }
3377: return $response;
3378: }
3379:
1.12 www 3380: # ------------------------------------------------------------------ Plain Text
3381:
3382: sub plaintext {
1.22 www 3383: my $short=shift;
1.414 www 3384: return &mt($prp{$short});
1.12 www 3385: }
3386:
3387: # ----------------------------------------------------------------- Assign Role
3388:
3389: sub assignrole {
1.357 www 3390: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 3391: my $mrole;
3392: if ($role =~ /^cr\//) {
1.393 www 3393: my $cwosec=$url;
3394: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
3395: unless (&allowed('ccr',$cwosec)) {
1.104 www 3396: &logthis('Refused custom assignrole: '.
3397: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
3398: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
3399: return 'refused';
3400: }
1.21 www 3401: $mrole='cr';
3402: } else {
1.82 www 3403: my $cwosec=$url;
1.83 www 3404: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373 www 3405: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 3406: &logthis('Refused assignrole: '.
3407: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
3408: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
3409: return 'refused';
3410: }
1.21 www 3411: $mrole=$role;
3412: }
3413: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
3414: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 3415: if ($end) { $command.='_'.$end; }
1.21 www 3416: if ($start) {
3417: if ($end) {
1.81 www 3418: $command.='_'.$start;
1.21 www 3419: } else {
1.81 www 3420: $command.='_0_'.$start;
1.21 www 3421: }
3422: }
1.357 www 3423: # actually delete
3424: if ($deleteflag) {
1.373 www 3425: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 3426: # modify command to delete the role
3427: $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
3428: "$udom:$uname:$url".'_'."$mrole";
1.373 www 3429: &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 3430: # set start and finish to negative values for userrolelog
3431: $start=-1;
3432: $end=-1;
3433: }
3434: }
3435: # send command
1.349 www 3436: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 3437: # log new user role if status is ok
1.349 www 3438: if ($answer eq 'ok') {
3439: &userrolelog($mrole,$uname,$udom,$url,$start,$end);
3440: }
3441: return $answer;
1.169 harris41 3442: }
3443:
3444: # -------------------------------------------------- Modify user authentication
1.197 www 3445: # Overrides without validation
3446:
1.169 harris41 3447: sub modifyuserauth {
3448: my ($udom,$uname,$umode,$upass)=@_;
3449: my $uhome=&homeserver($uname,$udom);
1.197 www 3450: unless (&allowed('mau',$udom)) { return 'refused'; }
3451: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272 matthew 3452: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
3453: ' in domain '.$ENV{'request.role.domain'});
1.169 harris41 3454: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
3455: &escape($upass),$uhome);
1.197 www 3456: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
3457: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
3458: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
3459: &log($udom,,$uname,$uhome,
3460: 'Authentication changed by '.$ENV{'user.domain'}.', '.
3461: $ENV{'user.name'}.', '.$umode.
3462: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 3463: unless ($reply eq 'ok') {
1.197 www 3464: &logthis('Authentication mode error: '.$reply);
1.169 harris41 3465: return 'error: '.$reply;
3466: }
1.170 harris41 3467: return 'ok';
1.80 www 3468: }
3469:
1.81 www 3470: # --------------------------------------------------------------- Modify a user
1.80 www 3471:
1.81 www 3472: sub modifyuser {
1.206 matthew 3473: my ($udom, $uname, $uid,
3474: $umode, $upass, $first,
3475: $middle, $last, $gene,
1.387 www 3476: $forceid, $desiredhome, $email)=@_;
1.198 www 3477: $udom=~s/\W//g;
3478: $uname=~s/\W//g;
1.81 www 3479: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3480: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 3481: $last.', '.$gene.'(forceid: '.$forceid.')'.
3482: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
3483: ' desiredhome not specified').
1.272 matthew 3484: ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
3485: ' in domain '.$ENV{'request.role.domain'});
1.230 stredwic 3486: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 3487: # ----------------------------------------------------------------- Create User
1.406 albertel 3488: if (($uhome eq 'no_host') &&
3489: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 3490: my $unhome='';
1.209 matthew 3491: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
3492: $unhome = $desiredhome;
3493: } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80 www 3494: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209 matthew 3495: } else { # load balancing routine for determining $unhome
1.80 www 3496: my $tryserver;
1.81 www 3497: my $loadm=10000000;
1.80 www 3498: foreach $tryserver (keys %libserv) {
3499: if ($hostdom{$tryserver} eq $udom) {
3500: my $answer=reply('load',$tryserver);
3501: if (($answer=~/\d+/) && ($answer<$loadm)) {
3502: $loadm=$answer;
3503: $unhome=$tryserver;
3504: }
3505: }
3506: }
3507: }
3508: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 3509: return 'error: unable to find a home server for '.$uname.
3510: ' in domain '.$udom;
1.80 www 3511: }
3512: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
3513: &escape($upass),$unhome);
3514: unless ($reply eq 'ok') {
3515: return 'error: '.$reply;
3516: }
1.230 stredwic 3517: $uhome=&homeserver($uname,$udom,'true');
1.80 www 3518: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 3519: return 'error: unable verify users home machine.';
1.80 www 3520: }
1.209 matthew 3521: } # End of creation of new user
1.80 www 3522: # ---------------------------------------------------------------------- Add ID
3523: if ($uid) {
3524: $uid=~tr/A-Z/a-z/;
3525: my %uidhash=&idrget($udom,$uname);
1.196 www 3526: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
3527: && (!$forceid)) {
1.80 www 3528: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 3529: return 'error: user id "'.$uid.'" does not match '.
3530: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 3531: }
3532: } else {
3533: &idput($udom,($uname => $uid));
3534: }
3535: }
3536: # -------------------------------------------------------------- Add names, etc
1.313 matthew 3537: my @tmp=&get('environment',
1.134 albertel 3538: ['firstname','middlename','lastname','generation'],
3539: $udom,$uname);
1.313 matthew 3540: my %names;
3541: if ($tmp[0] =~ m/^error:.*/) {
3542: %names=();
3543: } else {
3544: %names = @tmp;
3545: }
1.388 www 3546: #
3547: # Make sure to not trash student environment if instructor does not bother
3548: # to supply name and email information
3549: #
3550: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 3551: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 3552: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 3553: if (defined($gene)) { $names{'generation'} = $gene; }
1.388 www 3554: if ($email) { $names{'notification'} = $email;
3555: $names{'critnotification'} = $email; }
1.387 www 3556:
1.134 albertel 3557: my $reply = &put('environment', \%names, $udom,$uname);
3558: if ($reply ne 'ok') { return 'error: '.$reply; }
1.81 www 3559: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3560: $umode.', '.$first.', '.$middle.', '.
3561: $last.', '.$gene.' by '.
3562: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134 albertel 3563: return 'ok';
1.80 www 3564: }
3565:
1.81 www 3566: # -------------------------------------------------------------- Modify student
1.80 www 3567:
1.81 www 3568: sub modifystudent {
3569: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 3570: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 3571: if (!$cid) {
3572: unless ($cid=$ENV{'request.course.id'}) {
3573: return 'not_in_class';
3574: }
1.80 www 3575: }
3576: # --------------------------------------------------------------- Make the user
1.81 www 3577: my $reply=&modifyuser
1.209 matthew 3578: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 3579: $desiredhome,$email);
1.80 www 3580: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 3581: # This will cause &modify_student_enrollment to get the uid from the
3582: # students environment
3583: $uid = undef if (!$forceid);
1.455 albertel 3584: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 3585: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 3586: return $reply;
3587: }
3588:
3589: sub modify_student_enrollment {
1.515 raeburn 3590: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 3591: my ($cdom,$cnum,$chome);
3592: if (!$cid) {
3593: unless ($cid=$ENV{'request.course.id'}) {
3594: return 'not_in_class';
3595: }
3596: $cdom=$ENV{'course.'.$cid.'.domain'};
3597: $cnum=$ENV{'course.'.$cid.'.num'};
3598: } else {
3599: ($cdom,$cnum)=split(/_/,$cid);
3600: }
3601: $chome=$ENV{'course.'.$cid.'.home'};
3602: if (!$chome) {
1.457 raeburn 3603: $chome=&homeserver($cnum,$cdom);
1.297 matthew 3604: }
1.455 albertel 3605: if (!$chome) { return 'unknown_course'; }
1.297 matthew 3606: # Make sure the user exists
1.81 www 3607: my $uhome=&homeserver($uname,$udom);
3608: if (($uhome eq '') || ($uhome eq 'no_host')) {
3609: return 'error: no such user';
3610: }
1.297 matthew 3611: # Get student data if we were not given enough information
3612: if (!defined($first) || $first eq '' ||
3613: !defined($last) || $last eq '' ||
3614: !defined($uid) || $uid eq '' ||
3615: !defined($middle) || $middle eq '' ||
3616: !defined($gene) || $gene eq '') {
1.294 matthew 3617: # They did not supply us with enough data to enroll the student, so
3618: # we need to pick up more information.
1.297 matthew 3619: my %tmp = &get('environment',
1.294 matthew 3620: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 3621: ,$udom,$uname);
3622:
1.455 albertel 3623: #foreach (keys(%tmp)) {
3624: # &logthis("key $_ = ".$tmp{$_});
3625: #}
1.294 matthew 3626: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
3627: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
3628: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 3629: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 3630: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
3631: }
1.556 albertel 3632: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 3633: my $reply=cput('classlist',
3634: {"$uname:$udom" =>
1.515 raeburn 3635: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 3636: $cdom,$cnum);
1.81 www 3637: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
3638: return 'error: '.$reply;
3639: }
1.297 matthew 3640: # Add student role to user
1.83 www 3641: my $uurl='/'.$cid;
1.81 www 3642: $uurl=~s/\_/\//g;
3643: if ($usec) {
3644: $uurl.='/'.$usec;
3645: }
3646: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 3647: }
3648:
1.556 albertel 3649: sub format_name {
3650: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
3651: my $name;
3652: if ($first ne 'lastname') {
3653: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
3654: } else {
3655: if ($lastname=~/\S/) {
3656: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
3657: $name=~s/\s+,/,/;
3658: } else {
3659: $name.= $firstname.' '.$middlename.' '.$generation;
3660: }
3661: }
3662: $name=~s/^\s+//;
3663: $name=~s/\s+$//;
3664: $name=~s/\s+/ /g;
3665: return $name;
3666: }
3667:
1.84 www 3668: # ------------------------------------------------- Write to course preferences
3669:
3670: sub writecoursepref {
3671: my ($courseid,%prefs)=@_;
3672: $courseid=~s/^\///;
3673: $courseid=~s/\_/\//g;
3674: my ($cdomain,$cnum)=split(/\//,$courseid);
3675: my $chome=homeserver($cnum,$cdomain);
3676: if (($chome eq '') || ($chome eq 'no_host')) {
3677: return 'error: no such course';
3678: }
3679: my $cstring='';
1.191 harris41 3680: foreach (keys %prefs) {
1.84 www 3681: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191 harris41 3682: }
1.84 www 3683: $cstring=~s/\&$//;
3684: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
3685: }
3686:
3687: # ---------------------------------------------------------- Make/modify course
3688:
3689: sub createcourse {
1.516 raeburn 3690: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code)=@_;
1.84 www 3691: $url=&declutter($url);
3692: my $cid='';
1.264 matthew 3693: unless (&allowed('ccc',$udom)) {
1.84 www 3694: return 'refused';
3695: }
3696: # ------------------------------------------------------------------- Create ID
3697: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3698: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3699: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 3700: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 3701: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3702: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3703: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 3704: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3705: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3706: return 'error: unable to generate unique course-ID';
3707: }
3708: }
1.264 matthew 3709: # ------------------------------------------------ Check supplied server name
3710: $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
3711: if (! exists($libserv{$course_server})) {
3712: return 'error:bad server name '.$course_server;
3713: }
1.84 www 3714: # ------------------------------------------------------------- Make the course
3715: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 3716: $course_server);
1.84 www 3717: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 3718: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3719: if (($uhome eq '') || ($uhome eq 'no_host')) {
3720: return 'error: no such course';
3721: }
1.271 www 3722: # ----------------------------------------------------------------- Course made
1.516 raeburn 3723: # log existence
3724: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
3725: '='.&escape($inst_code),$uhome);
1.358 www 3726: &flushcourselogs();
3727: # set toplevel url
1.271 www 3728: my $topurl=$url;
3729: unless ($nonstandard) {
3730: # ------------------------------------------ For standard courses, make top url
3731: my $mapurl=&clutter($url);
1.278 www 3732: if ($mapurl eq '/res/') { $mapurl=''; }
1.271 www 3733: $ENV{'form.initmap'}=(<<ENDINITMAP);
3734: <map>
3735: <resource id="1" type="start"></resource>
3736: <resource id="2" src="$mapurl"></resource>
3737: <resource id="3" type="finish"></resource>
3738: <link index="1" from="1" to="2"></link>
3739: <link index="2" from="2" to="3"></link>
3740: </map>
3741: ENDINITMAP
3742: $topurl=&declutter(
3743: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
3744: );
3745: }
3746: # ----------------------------------------------------------- Write preferences
1.84 www 3747: &writecoursepref($udom.'_'.$uname,
3748: ('description' => $description,
1.271 www 3749: 'url' => $topurl));
1.84 www 3750: return '/'.$udom.'/'.$uname;
3751: }
3752:
1.21 www 3753: # ---------------------------------------------------------- Assign Custom Role
3754:
3755: sub assigncustomrole {
1.357 www 3756: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 3757: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 3758: $end,$start,$deleteflag);
1.21 www 3759: }
3760:
3761: # ----------------------------------------------------------------- Revoke Role
3762:
3763: sub revokerole {
1.357 www 3764: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 3765: my $now=time;
1.357 www 3766: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 3767: }
3768:
3769: # ---------------------------------------------------------- Revoke Custom Role
3770:
3771: sub revokecustomrole {
1.357 www 3772: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 3773: my $now=time;
1.357 www 3774: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
3775: $deleteflag);
1.17 www 3776: }
3777:
1.533 banghart 3778: # ------------------------------------------------------------ Disk usage
1.535 albertel 3779: sub diskusage {
1.533 banghart 3780: my ($udom,$uname,$directoryRoot)=@_;
3781: $directoryRoot =~ s/\/$//;
1.535 albertel 3782: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 3783: return $listing;
1.512 banghart 3784: }
3785:
1.566 banghart 3786: sub is_locked {
3787: my ($file_name, $domain, $user) = @_;
3788: my @check;
3789: my $is_locked;
3790: push @check, $file_name;
3791: my %locked = &Apache::lonnet::get('file_permissions',\@check,
3792: $ENV{'user.domain'},$ENV{'user.name'});
3793: if (ref($locked{$file_name}) eq 'ARRAY') {
3794: $is_locked = 'true';
3795: } else {
3796: $is_locked = 'false';
3797: }
3798: }
3799:
1.559 banghart 3800: # ------------------------------------------------------------- Mark as Read Only
3801:
3802: sub mark_as_readonly {
3803: my ($domain,$user,$files,$what) = @_;
3804: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
1.560 banghart 3805: foreach my $file (@{$files}) {
1.561 banghart 3806: push(@{$current_permissions{$file}},$what);
1.559 banghart 3807: }
1.560 banghart 3808: &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 3809: return;
3810: }
3811:
1.561 banghart 3812: #--------------------------------------------------------------Get Marked as Read Only
3813:
3814: sub get_marked_as_readonly {
3815: my ($domain,$user,$what) = @_;
3816: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
1.563 banghart 3817: my @readonly_files;
3818: while (my ($file_name,$value) = each(%current_permissions)) {
1.561 banghart 3819: if (ref($value) eq "ARRAY"){
3820: foreach my $stored_what (@{$value}) {
3821: if ($stored_what eq $what) {
3822: push(@readonly_files, $file_name);
1.563 banghart 3823: } elsif (!defined($what)) {
3824: push(@readonly_files, $file_name);
1.561 banghart 3825: }
3826: }
3827: }
3828: }
3829: return @readonly_files;
3830: }
3831:
1.559 banghart 3832: # ------------------------------------------------------------ Unmark as Read Only
3833:
3834: sub unmark_as_readonly {
1.561 banghart 3835: # unmarks all files locked by $what
3836: # for portfolio submissions, $what contains $crsid and $symb
3837: my ($domain,$user,$what) = @_;
3838: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
3839: my @readonly_files = &Apache::lonnet::get_marked_as_readonly($domain,$user,$what);
3840: foreach my $file(@readonly_files){
1.563 banghart 3841: my $current_locks = $current_permissions{$file};
3842: my @new_locks;
3843: my @del_keys;
3844: if (ref($current_locks) eq "ARRAY"){
3845: foreach my $locker (@{$current_locks}) {
3846: unless ($locker eq $what) {
3847: push(@new_locks, $what);
3848: }
3849: }
3850: if (@new_locks > 0) {
3851: $current_permissions{$file} = \@new_locks;
3852: } else {
3853: push(@del_keys, $file);
3854: &Apache::lonnet::del('file_permissions',\@del_keys, $domain, $user);
3855: delete $current_permissions{$file};
3856: }
3857: }
1.561 banghart 3858: }
3859: &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 3860: return;
3861: }
1.512 banghart 3862:
1.17 www 3863: # ------------------------------------------------------------ Directory lister
3864:
3865: sub dirlist {
1.253 stredwic 3866: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
3867:
1.18 www 3868: $uri=~s/^\///;
3869: $uri=~s/\/$//;
1.253 stredwic 3870: my ($udom, $uname);
3871: (undef,$udom,$uname)=split(/\//,$uri);
3872: if(defined($userdomain)) {
3873: $udom = $userdomain;
3874: }
3875: if(defined($username)) {
3876: $uname = $username;
3877: }
3878:
3879: my $dirRoot = $perlvar{'lonDocRoot'};
3880: if(defined($alternateDirectoryRoot)) {
3881: $dirRoot = $alternateDirectoryRoot;
3882: $dirRoot =~ s/\/$//;
3883: }
3884:
3885: if($udom) {
3886: if($uname) {
3887: my $listing=reply('ls:'.$dirRoot.'/'.$uri,
3888: homeserver($uname,$udom));
3889: return split(/:/,$listing);
3890: } elsif(!defined($alternateDirectoryRoot)) {
3891: my $tryserver;
3892: my %allusers=();
3893: foreach $tryserver (keys %libserv) {
3894: if($hostdom{$tryserver} eq $udom) {
3895: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
3896: $udom, $tryserver);
3897: if (($listing ne 'no_such_dir') && ($listing ne 'empty')
3898: && ($listing ne 'con_lost')) {
3899: foreach (split(/:/,$listing)) {
3900: my ($entry,@stat)=split(/&/,$_);
3901: $allusers{$entry}=1;
3902: }
3903: }
1.191 harris41 3904: }
1.253 stredwic 3905: }
3906: my $alluserstr='';
3907: foreach (sort keys %allusers) {
3908: $alluserstr.=$_.'&user:';
3909: }
3910: $alluserstr=~s/:$//;
3911: return split(/:/,$alluserstr);
3912: } else {
3913: my @emptyResults = ();
3914: push(@emptyResults, 'missing user name');
3915: return split(':',@emptyResults);
3916: }
3917: } elsif(!defined($alternateDirectoryRoot)) {
3918: my $tryserver;
3919: my %alldom=();
3920: foreach $tryserver (keys %libserv) {
3921: $alldom{$hostdom{$tryserver}}=1;
3922: }
3923: my $alldomstr='';
3924: foreach (sort keys %alldom) {
1.397 albertel 3925: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253 stredwic 3926: }
3927: $alldomstr=~s/:$//;
3928: return split(/:/,$alldomstr);
3929: } else {
3930: my @emptyResults = ();
3931: push(@emptyResults, 'missing domain');
3932: return split(':',@emptyResults);
1.275 stredwic 3933: }
3934: }
3935:
3936: # --------------------------------------------- GetFileTimestamp
3937: # This function utilizes dirlist and returns the date stamp for
3938: # when it was last modified. It will also return an error of -1
3939: # if an error occurs
3940:
1.410 matthew 3941: ##
3942: ## FIXME: This subroutine assumes its caller knows something about the
3943: ## directory structure of the home server for the student ($root).
3944: ## Not a good assumption to make. Since this is for looking up files
3945: ## in user directories, the full path should be constructed by lond, not
3946: ## whatever machine we request data from.
3947: ##
1.275 stredwic 3948: sub GetFileTimestamp {
3949: my ($studentDomain,$studentName,$filename,$root)=@_;
3950: $studentDomain=~s/\W//g;
3951: $studentName=~s/\W//g;
3952: my $subdir=$studentName.'__';
3953: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3954: my $proname="$studentDomain/$subdir/$studentName";
3955: $proname .= '/'.$filename;
1.375 matthew 3956: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
3957: $studentName, $root);
1.275 stredwic 3958: my @stats = split('&', $fileStat);
3959: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 3960: # @stats contains first the filename, then the stat output
3961: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 3962: } else {
3963: return -1;
1.253 stredwic 3964: }
1.26 www 3965: }
3966:
3967: # -------------------------------------------------------- Value of a Condition
3968:
1.40 www 3969: sub directcondval {
3970: my $number=shift;
1.555 albertel 3971: if (!defined($ENV{'user.state.'.$ENV{'request.course.id'}})) {
3972: &Apache::lonuserstate::evalstate();
3973: }
1.40 www 3974: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
3975: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
3976: } else {
3977: return 2;
3978: }
3979: }
3980:
1.26 www 3981: sub condval {
3982: my $condidx=shift;
3983: my $result=0;
1.54 www 3984: my $allpathcond='';
1.191 harris41 3985: foreach (split(/\|/,$condidx)) {
1.54 www 3986: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
3987: $allpathcond.=
3988: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
3989: }
1.191 harris41 3990: }
1.54 www 3991: $allpathcond=~s/\|$//;
1.33 www 3992: if ($ENV{'request.course.id'}) {
1.54 www 3993: if ($allpathcond) {
1.26 www 3994: my $operand='|';
3995: my @stack;
1.191 harris41 3996: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26 www 3997: if ($_ eq '(') {
3998: push @stack,($operand,$result)
3999: } elsif ($_ eq ')') {
4000: my $before=pop @stack;
4001: if (pop @stack eq '&') {
4002: $result=$result>$before?$before:$result;
4003: } else {
4004: $result=$result>$before?$result:$before;
4005: }
4006: } elsif (($_ eq '&') || ($_ eq '|')) {
4007: $operand=$_;
4008: } else {
1.40 www 4009: my $new=directcondval($_);
1.26 www 4010: if ($operand eq '&') {
4011: $result=$result>$new?$new:$result;
4012: } else {
4013: $result=$result>$new?$result:$new;
1.191 harris41 4014: }
1.26 www 4015: }
1.191 harris41 4016: }
1.26 www 4017: }
4018: }
4019: return $result;
1.421 albertel 4020: }
4021:
4022: # ---------------------------------------------------- Devalidate courseresdata
4023:
4024: sub devalidatecourseresdata {
4025: my ($coursenum,$coursedomain)=@_;
4026: my $hashid=$coursenum.':'.$coursedomain;
1.428 albertel 4027: &devalidate_cache(\%courseresdatacache,$hashid,'courseres');
1.28 www 4028: }
4029:
1.200 www 4030: # --------------------------------------------------- Course Resourcedata Query
4031:
4032: sub courseresdata {
4033: my ($coursenum,$coursedomain,@which)=@_;
4034: my $coursehom=&homeserver($coursenum,$coursedomain);
4035: my $hashid=$coursenum.':'.$coursedomain;
1.425 albertel 4036: my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres');
1.417 albertel 4037: unless (defined($cached)) {
1.251 albertel 4038: my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 4039: $result=\%dumpreply;
1.251 albertel 4040: my ($tmp) = keys(%dumpreply);
4041: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.425 albertel 4042: &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.306 albertel 4043: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
4044: return $tmp;
1.416 albertel 4045: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 4046: $result=undef;
1.425 albertel 4047: &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.250 albertel 4048: }
4049: }
1.251 albertel 4050: foreach my $item (@which) {
1.417 albertel 4051: if (defined($result->{$item})) {
4052: return $result->{$item};
1.251 albertel 4053: }
1.250 albertel 4054: }
1.291 albertel 4055: return undef;
1.200 www 4056: }
4057:
1.379 matthew 4058: #
4059: # EXT resource caching routines
4060: #
4061:
4062: sub clear_EXT_cache_status {
1.383 albertel 4063: &delenv('cache.EXT.');
1.379 matthew 4064: }
4065:
4066: sub EXT_cache_status {
4067: my ($target_domain,$target_user) = @_;
1.383 albertel 4068: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389 www 4069: if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379 matthew 4070: # We know already the user has no data
4071: return 1;
4072: } else {
4073: return 0;
4074: }
4075: }
4076:
4077: sub EXT_cache_set {
4078: my ($target_domain,$target_user) = @_;
1.383 albertel 4079: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379 matthew 4080: &appenv($cachename => time);
4081: }
4082:
1.28 www 4083: # --------------------------------------------------------- Value of a Variable
1.58 www 4084: sub EXT {
1.395 albertel 4085: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218 albertel 4086:
1.68 www 4087: unless ($varname) { return ''; }
1.218 albertel 4088: #get real user name/domain, courseid and symb
4089: my $courseid;
1.359 albertel 4090: my $publicuser;
1.427 www 4091: if ($symbparm) {
4092: $symbparm=&get_symb_from_alias($symbparm);
4093: }
1.218 albertel 4094: if (!($uname && $udom)) {
1.360 albertel 4095: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378 matthew 4096: &Apache::lonxml::whichuser($symbparm);
1.218 albertel 4097: if (!$symbparm) { $symbparm=$cursymb; }
4098: } else {
4099: $courseid=$ENV{'request.course.id'};
4100: }
1.48 www 4101: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
4102: my $rest;
1.320 albertel 4103: if (defined($therest[0])) {
1.48 www 4104: $rest=join('.',@therest);
4105: } else {
4106: $rest='';
4107: }
1.320 albertel 4108:
1.57 www 4109: my $qualifierrest=$qualifier;
4110: if ($rest) { $qualifierrest.='.'.$rest; }
4111: my $spacequalifierrest=$space;
4112: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 4113: if ($realm eq 'user') {
1.48 www 4114: # --------------------------------------------------------------- user.resource
4115: if ($space eq 'resource') {
1.335 albertel 4116: if (defined($Apache::lonhomework::parsing_a_problem)) {
4117: return $Apache::lonhomework::history{$qualifierrest};
4118: } else {
1.359 albertel 4119: my %restored;
4120: if ($publicuser || $ENV{'request.state'} eq 'construct') {
4121: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
4122: } else {
4123: %restored=&restore($symbparm,$courseid,$udom,$uname);
4124: }
1.335 albertel 4125: return $restored{$qualifierrest};
4126: }
1.48 www 4127: # ----------------------------------------------------------------- user.access
4128: } elsif ($space eq 'access') {
1.218 albertel 4129: # FIXME - not supporting calls for a specific user
1.48 www 4130: return &allowed($qualifier,$rest);
4131: # ------------------------------------------ user.preferences, user.environment
4132: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218 albertel 4133: if (($uname eq $ENV{'user.name'}) &&
4134: ($udom eq $ENV{'user.domain'})) {
4135: return $ENV{join('.',('environment',$qualifierrest))};
4136: } else {
1.359 albertel 4137: my %returnhash;
4138: if (!$publicuser) {
4139: %returnhash=&userenvironment($udom,$uname,
4140: $qualifierrest);
4141: }
1.218 albertel 4142: return $returnhash{$qualifierrest};
4143: }
1.48 www 4144: # ----------------------------------------------------------------- user.course
4145: } elsif ($space eq 'course') {
1.218 albertel 4146: # FIXME - not supporting calls for a specific user
1.48 www 4147: return $ENV{join('.',('request.course',$qualifier))};
4148: # ------------------------------------------------------------------- user.role
4149: } elsif ($space eq 'role') {
1.218 albertel 4150: # FIXME - not supporting calls for a specific user
1.48 www 4151: my ($role,$where)=split(/\./,$ENV{'request.role'});
4152: if ($qualifier eq 'value') {
4153: return $role;
4154: } elsif ($qualifier eq 'extent') {
4155: return $where;
4156: }
4157: # ----------------------------------------------------------------- user.domain
4158: } elsif ($space eq 'domain') {
1.218 albertel 4159: return $udom;
1.48 www 4160: # ------------------------------------------------------------------- user.name
4161: } elsif ($space eq 'name') {
1.218 albertel 4162: return $uname;
1.48 www 4163: # ---------------------------------------------------- Any other user namespace
1.29 www 4164: } else {
1.359 albertel 4165: my %reply;
4166: if (!$publicuser) {
4167: %reply=&get($space,[$qualifierrest],$udom,$uname);
4168: }
4169: return $reply{$qualifierrest};
1.48 www 4170: }
1.236 www 4171: } elsif ($realm eq 'query') {
4172: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 4173: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
4174: [$spacequalifierrest]);
1.376 albertel 4175: return $ENV{'form.'.$spacequalifierrest};
1.236 www 4176: } elsif ($realm eq 'request') {
1.48 www 4177: # ------------------------------------------------------------- request.browser
4178: if ($space eq 'browser') {
1.430 www 4179: if ($qualifier eq 'textremote') {
4180: if (&mt('textual_remote_display') eq 'on') {
4181: return 1;
4182: } else {
4183: return 0;
4184: }
4185: } else {
4186: return $ENV{'browser.'.$qualifier};
4187: }
1.57 www 4188: # ------------------------------------------------------------ request.filename
4189: } else {
4190: return $ENV{'request.'.$spacequalifierrest};
1.29 www 4191: }
1.28 www 4192: } elsif ($realm eq 'course') {
1.48 www 4193: # ---------------------------------------------------------- course.description
1.218 albertel 4194: return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 4195: } elsif ($realm eq 'resource') {
1.165 www 4196:
1.395 albertel 4197: my $section;
1.359 albertel 4198: if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.539 albertel 4199: if (!$symbparm) { $symbparm=&symbread(); }
4200: }
4201: if ($symbparm && defined($courseid) &&
4202: $courseid eq $ENV{'request.course.id'}) {
1.165 www 4203:
1.218 albertel 4204: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 4205:
1.60 www 4206: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 4207: my $symbp=$symbparm;
1.409 www 4208: my $mapp=(&decode_symb($symbp))[0];
1.218 albertel 4209:
4210: my $symbparm=$symbp.'.'.$spacequalifierrest;
4211: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
4212:
4213: if (($ENV{'user.name'} eq $uname) &&
4214: ($ENV{'user.domain'} eq $udom)) {
1.255 albertel 4215: $section=$ENV{'request.course.sec'};
1.218 albertel 4216: } else {
1.539 albertel 4217: if (! defined($usection)) {
1.551 albertel 4218: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 4219: } else {
4220: $section = $usection;
4221: }
1.218 albertel 4222: }
4223:
4224: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
4225: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
4226: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
4227:
4228: my $courselevel=$courseid.'.'.$spacequalifierrest;
4229: my $courselevelr=$courseid.'.'.$symbparm;
4230: my $courselevelm=$courseid.'.'.$mapparm;
1.69 www 4231:
1.60 www 4232: # ----------------------------------------------------------- first, check user
1.379 matthew 4233: #most student don\'t have any data set, check if there is some data
4234: if (! &EXT_cache_status($udom,$uname)) {
1.420 albertel 4235: my $hashid="$udom:$uname";
1.425 albertel 4236: my ($result,$cached)=&is_cached(\%userresdatacache,$hashid,
4237: 'userres');
1.454 albertel 4238: if (!defined($cached)) {
4239: my %resourcedata=&dump('resourcedata',$udom,$uname);
1.420 albertel 4240: $result=\%resourcedata;
1.425 albertel 4241: &do_cache(\%userresdatacache,$hashid,$result,'userres');
1.420 albertel 4242: }
4243: my ($tmp)=keys(%$result);
1.308 albertel 4244: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
1.420 albertel 4245: if ($$result{$courselevelr}) {
4246: return $$result{$courselevelr}; }
4247: if ($$result{$courselevelm}) {
4248: return $$result{$courselevelm}; }
4249: if ($$result{$courselevel}) {
4250: return $$result{$courselevel}; }
1.308 albertel 4251: } else {
1.459 albertel 4252: #error 2 occurs when the .db doesn't exist
4253: if ($tmp!~/error: 2 /) {
1.308 albertel 4254: &logthis("<font color=blue>WARNING:".
4255: " Trying to get resource data for ".
4256: $uname." at ".$udom.": ".
4257: $tmp."</font>");
1.459 albertel 4258: } elsif ($tmp=~/error: 2 /) {
1.539 albertel 4259: &EXT_cache_set($udom,$uname);
1.308 albertel 4260: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
4261: return $tmp;
4262: }
1.218 albertel 4263: }
4264: }
1.95 www 4265:
1.60 www 4266: # -------------------------------------------------------- second, check course
1.96 www 4267:
1.218 albertel 4268: my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
1.539 albertel 4269: $ENV{'course.'.$courseid.'.domain'},
4270: ($seclevelr,$seclevelm,$seclevel,
4271: $courselevelr,$courselevelm,
4272: $courselevel));
1.287 albertel 4273: if (defined($coursereply)) { return $coursereply; }
1.200 www 4274:
1.60 www 4275: # ------------------------------------------------------ third, check map parms
1.218 albertel 4276: my %parmhash=();
4277: my $thisparm='';
4278: if (tie(%parmhash,'GDBM_File',
4279: $ENV{'request.course.fn'}.'_parms.db',
1.256 albertel 4280: &GDBM_READER(),0640)) {
1.218 albertel 4281: $thisparm=$parmhash{$symbparm};
4282: untie(%parmhash);
4283: }
4284: if ($thisparm) { return $thisparm; }
4285: }
1.60 www 4286: # --------------------------------------------- last, look in resource metadata
1.71 www 4287:
1.218 albertel 4288: $spacequalifierrest=~s/\./\_/;
1.282 albertel 4289: my $filename;
4290: if (!$symbparm) { $symbparm=&symbread(); }
4291: if ($symbparm) {
1.409 www 4292: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 4293: } else {
4294: $filename=$ENV{'request.filename'};
4295: }
4296: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 4297: if (defined($metadata)) { return $metadata; }
1.282 albertel 4298: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 4299: if (defined($metadata)) { return $metadata; }
1.142 www 4300:
1.145 www 4301: # ------------------------------------------------------------------ Cascade up
1.218 albertel 4302: unless ($space eq '0') {
1.336 albertel 4303: my @parts=split(/_/,$space);
4304: my $id=pop(@parts);
4305: my $part=join('_',@parts);
4306: if ($part eq '') { $part='0'; }
4307: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 4308: $symbparm,$udom,$uname,$section,1);
1.337 albertel 4309: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 4310: }
1.395 albertel 4311: if ($recurse) { return undef; }
4312: my $pack_def=&packages_tab_default($filename,$varname);
4313: if (defined($pack_def)) { return $pack_def; }
1.71 www 4314:
1.48 www 4315: # ---------------------------------------------------- Any other user namespace
4316: } elsif ($realm eq 'environment') {
4317: # ----------------------------------------------------------------- environment
1.219 albertel 4318: if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
4319: return $ENV{'environment.'.$spacequalifierrest};
4320: } else {
4321: my %returnhash=&userenvironment($udom,$uname,
4322: $spacequalifierrest);
4323: return $returnhash{$spacequalifierrest};
4324: }
1.28 www 4325: } elsif ($realm eq 'system') {
1.48 www 4326: # ----------------------------------------------------------------- system.time
4327: if ($space eq 'time') {
4328: return time;
4329: }
1.28 www 4330: }
1.48 www 4331: return '';
1.61 www 4332: }
4333:
1.395 albertel 4334: sub packages_tab_default {
4335: my ($uri,$varname)=@_;
4336: my (undef,$part,$name)=split(/\./,$varname);
4337: my $packages=&metadata($uri,'packages');
4338: foreach my $package (split(/,/,$packages)) {
4339: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468 albertel 4340: if (defined($packagetab{"$pack_type&$name&default"})) {
4341: return $packagetab{"$pack_type&$name&default"};
4342: }
4343: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
4344: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 4345: }
4346: }
4347: return undef;
4348: }
4349:
1.334 albertel 4350: sub add_prefix_and_part {
4351: my ($prefix,$part)=@_;
4352: my $keyroot;
4353: if (defined($prefix) && $prefix !~ /^__/) {
4354: # prefix that has a part already
4355: $keyroot=$prefix;
4356: } elsif (defined($prefix)) {
4357: # prefix that is missing a part
4358: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
4359: } else {
4360: # no prefix at all
4361: if (defined($part)) { $keyroot='_'.$part; }
4362: }
4363: return $keyroot;
4364: }
4365:
1.71 www 4366: # ---------------------------------------------------------------- Get metadata
4367:
4368: sub metadata {
1.176 www 4369: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 4370: $uri=&declutter($uri);
1.288 albertel 4371: # if it is a non metadata possible uri return quickly
1.529 albertel 4372: if (($uri eq '') ||
4373: (($uri =~ m|^/*adm/|) &&
4374: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 4375: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489 albertel 4376: ($uri =~ m|home/[^/]+/public_html/|)) {
1.468 albertel 4377: return undef;
1.288 albertel 4378: }
1.73 www 4379: my $filename=$uri;
4380: $uri=~s/\.meta$//;
1.172 www 4381: #
4382: # Is the metadata already cached?
1.177 www 4383: # Look at timestamp of caching
1.172 www 4384: # Everything is cached by the main uri, libraries are never directly cached
4385: #
1.428 albertel 4386: if (!defined($liburi)) {
4387: my ($result,$cached)=&is_cached(\%metacache,$uri,'meta');
4388: if (defined($cached)) { return $result->{':'.$what}; }
4389: }
4390: {
1.172 www 4391: #
4392: # Is this a recursive call for a library?
4393: #
1.453 albertel 4394: if (! exists($metacache{$uri})) {
4395: $metacache{$uri}={};
4396: }
1.171 www 4397: if ($liburi) {
4398: $liburi=&declutter($liburi);
4399: $filename=$liburi;
1.401 bowersj2 4400: } else {
1.428 albertel 4401: &devalidate_cache(\%metacache,$uri,'meta');
1.401 bowersj2 4402: }
1.140 www 4403: my %metathesekeys=();
1.73 www 4404: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 4405: my $metastring;
4406: if ($uri !~ m|^uploaded/|) {
1.543 albertel 4407: my $file=&filelocation('',&clutter($filename));
4408: push(@{$metacache{$uri.'.file'}},$file);
4409: $metastring=&getfile($file);
1.489 albertel 4410: }
1.208 albertel 4411: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 4412: my $token;
1.140 www 4413: undef %metathesekeys;
1.71 www 4414: while ($token=$parser->get_token) {
1.339 albertel 4415: if ($token->[0] eq 'S') {
4416: if (defined($token->[2]->{'package'})) {
1.172 www 4417: #
4418: # This is a package - get package info
4419: #
1.339 albertel 4420: my $package=$token->[2]->{'package'};
4421: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4422: if (defined($token->[2]->{'id'})) {
4423: $keyroot.='_'.$token->[2]->{'id'};
4424: }
1.453 albertel 4425: if ($metacache{$uri}->{':packages'}) {
4426: $metacache{$uri}->{':packages'}.=','.$package.$keyroot;
1.339 albertel 4427: } else {
1.453 albertel 4428: $metacache{$uri}->{':packages'}=$package.$keyroot;
1.339 albertel 4429: }
4430: foreach (keys %packagetab) {
1.432 albertel 4431: my $part=$keyroot;
4432: $part=~s/^\_//;
4433: if ($_=~/^\Q$package\E\&/ ||
4434: $_=~/^\Q$package\E_0\&/) {
1.339 albertel 4435: my ($pack,$name,$subp)=split(/\&/,$_);
1.395 albertel 4436: # ignore package.tab specified default values
4437: # here &package_tab_default() will fetch those
4438: if ($subp eq 'default') { next; }
1.339 albertel 4439: my $value=$packagetab{$_};
1.432 albertel 4440: my $unikey;
4441: if ($pack =~ /_0$/) {
4442: $unikey='parameter_0_'.$name;
4443: $part=0;
4444: } else {
4445: $unikey='parameter'.$keyroot.'_'.$name;
4446: }
1.339 albertel 4447: if ($subp eq 'display') {
4448: $value.=' [Part: '.$part.']';
4449: }
1.453 albertel 4450: $metacache{$uri}->{':'.$unikey.'.part'}=$part;
1.395 albertel 4451: $metathesekeys{$unikey}=1;
1.453 albertel 4452: unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
4453: $metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 4454: }
1.453 albertel 4455: if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
4456: $metacache{$uri}->{':'.$unikey}=
4457: $metacache{$uri}->{':'.$unikey.'.default'};
1.356 albertel 4458: }
1.339 albertel 4459: }
4460: }
4461: } else {
1.172 www 4462: #
4463: # This is not a package - some other kind of start tag
1.339 albertel 4464: #
4465: my $entry=$token->[1];
4466: my $unikey;
4467: if ($entry eq 'import') {
4468: $unikey='';
4469: } else {
4470: $unikey=$entry;
4471: }
4472: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4473:
4474: if (defined($token->[2]->{'id'})) {
4475: $unikey.='_'.$token->[2]->{'id'};
4476: }
1.175 www 4477:
1.339 albertel 4478: if ($entry eq 'import') {
1.175 www 4479: #
4480: # Importing a library here
1.339 albertel 4481: #
4482: if ($depthcount<20) {
4483: my $location=$parser->get_text('/import');
4484: my $dir=$filename;
4485: $dir=~s|[^/]*$||;
4486: $location=&filelocation($dir,$location);
4487: foreach (sort(split(/\,/,&metadata($uri,'keys',
4488: $location,$unikey,
4489: $depthcount+1)))) {
1.453 albertel 4490: $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
1.339 albertel 4491: $metathesekeys{$_}=1;
4492: }
4493: }
4494: } else {
4495:
4496: if (defined($token->[2]->{'name'})) {
4497: $unikey.='_'.$token->[2]->{'name'};
4498: }
4499: $metathesekeys{$unikey}=1;
4500: foreach (@{$token->[3]}) {
1.453 albertel 4501: $metacache{$uri}->{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339 albertel 4502: }
4503: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.453 albertel 4504: my $default=$metacache{$uri}->{':'.$unikey.'.default'};
1.339 albertel 4505: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
4506: # only ws inside the tag, and not in default, so use default
4507: # as value
1.453 albertel 4508: $metacache{$uri}->{':'.$unikey}=$default;
1.339 albertel 4509: } else {
1.321 albertel 4510: # either something interesting inside the tag or default
4511: # uninteresting
1.453 albertel 4512: $metacache{$uri}->{':'.$unikey}=$internaltext;
1.339 albertel 4513: }
1.172 www 4514: # end of not-a-package not-a-library import
1.339 albertel 4515: }
1.172 www 4516: # end of not-a-package start tag
1.339 albertel 4517: }
1.172 www 4518: # the next is the end of "start tag"
1.339 albertel 4519: }
4520: }
1.483 albertel 4521: my ($extension) = ($uri =~ /\.(\w+)$/);
4522: foreach my $key (sort(keys(%packagetab))) {
4523: #&logthis("extsion1 $extension $key !!");
4524: #no specific packages #how's our extension
4525: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 4526: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 4527: \%metathesekeys);
4528: }
4529: if (!exists($metacache{$uri}->{':packages'})) {
4530: foreach my $key (sort(keys(%packagetab))) {
4531: #no specific packages well let's get default then
4532: if ($key!~/^default&/) { next; }
1.488 albertel 4533: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 4534: \%metathesekeys);
4535: }
4536: }
1.338 www 4537: # are there custom rights to evaluate
1.453 albertel 4538: if ($metacache{$uri}->{':copyright'} eq 'custom') {
1.339 albertel 4539:
1.338 www 4540: #
4541: # Importing a rights file here
1.339 albertel 4542: #
4543: unless ($depthcount) {
1.453 albertel 4544: my $location=$metacache{$uri}->{':customdistributionfile'};
1.339 albertel 4545: my $dir=$filename;
4546: $dir=~s|[^/]*$||;
4547: $location=&filelocation($dir,$location);
4548: foreach (sort(split(/\,/,&metadata($uri,'keys',
4549: $location,'_rights',
4550: $depthcount+1)))) {
1.453 albertel 4551: $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_};
1.339 albertel 4552: $metathesekeys{$_}=1;
4553: }
4554: }
4555: }
1.453 albertel 4556: $metacache{$uri}->{':keys'}=join(',',keys %metathesekeys);
4557: &metadata_generate_part0(\%metathesekeys,$metacache{$uri},$uri);
4558: $metacache{$uri}->{':allpossiblekeys'}=join(',',keys %metathesekeys);
4559: &do_cache(\%metacache,$uri,$metacache{$uri},'meta');
1.177 www 4560: # this is the end of "was not already recently cached
1.71 www 4561: }
1.428 albertel 4562: return $metacache{$uri}->{':'.$what};
1.261 albertel 4563: }
4564:
1.488 albertel 4565: sub metadata_create_package_def {
1.483 albertel 4566: my ($uri,$key,$package,$metathesekeys)=@_;
4567: my ($pack,$name,$subp)=split(/\&/,$key);
4568: if ($subp eq 'default') { next; }
4569:
4570: if (defined($metacache{$uri}->{':packages'})) {
4571: $metacache{$uri}->{':packages'}.=','.$package;
4572: } else {
4573: $metacache{$uri}->{':packages'}=$package;
4574: }
4575: my $value=$packagetab{$key};
4576: my $unikey;
4577: $unikey='parameter_0_'.$name;
4578: $metacache{$uri}->{':'.$unikey.'.part'}=0;
4579: $$metathesekeys{$unikey}=1;
4580: unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) {
4581: $metacache{$uri}->{':'.$unikey.'.'.$subp}=$value;
4582: }
4583: if (defined($metacache{$uri}->{':'.$unikey.'.default'})) {
4584: $metacache{$uri}->{':'.$unikey}=
4585: $metacache{$uri}->{':'.$unikey.'.default'};
4586: }
4587: }
4588:
1.261 albertel 4589: sub metadata_generate_part0 {
4590: my ($metadata,$metacache,$uri) = @_;
4591: my %allnames;
4592: foreach my $metakey (sort keys %$metadata) {
4593: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 4594: my $part=$$metacache{':'.$metakey.'.part'};
4595: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 4596: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 4597: $allnames{$name}=$part;
4598: }
4599: }
4600: }
4601: foreach my $name (keys(%allnames)) {
4602: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 4603: my $key=":parameter_0_$name";
1.261 albertel 4604: $$metacache{"$key.part"}='0';
4605: $$metacache{"$key.name"}=$name;
1.428 albertel 4606: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 4607: $allnames{$name}.'_'.$name.
4608: '.type'};
1.428 albertel 4609: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 4610: '.display'};
4611: my $expr='\\[Part: '.$allnames{$name}.'\\]';
1.479 albertel 4612: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 4613: $$metacache{"$key.display"}=$olddis;
4614: }
1.71 www 4615: }
4616:
1.301 www 4617: # ------------------------------------------------- Get the title of a resource
4618:
4619: sub gettitle {
4620: my $urlsymb=shift;
4621: my $symb=&symbread($urlsymb);
1.534 albertel 4622: if ($symb) {
4623: my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600);
4624: if (defined($cached)) { return $result; }
4625: my ($map,$resid,$url)=&decode_symb($symb);
4626: my $title='';
4627: my %bighash;
4628: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
4629: &GDBM_READER(),0640)) {
4630: my $mapid=$bighash{'map_pc_'.&clutter($map)};
4631: $title=$bighash{'title_'.$mapid.'.'.$resid};
4632: untie %bighash;
4633: }
4634: $title=~s/\&colon\;/\:/gs;
4635: if ($title) {
4636: return &do_cache(\%titlecache,$symb,$title,'title');
4637: }
4638: $urlsymb=$url;
4639: }
4640: my $title=&metadata($urlsymb,'title');
4641: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
4642: return $title;
1.301 www 4643: }
4644:
1.31 www 4645: # ------------------------------------------------- Update symbolic store links
4646:
4647: sub symblist {
4648: my ($mapname,%newhash)=@_;
1.438 www 4649: $mapname=&deversion(&declutter($mapname));
1.31 www 4650: my %hash;
4651: if (($ENV{'request.course.fn'}) && (%newhash)) {
4652: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256 albertel 4653: &GDBM_WRCREAT(),0640)) {
1.191 harris41 4654: foreach (keys %newhash) {
1.438 www 4655: $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
1.191 harris41 4656: }
1.31 www 4657: if (untie(%hash)) {
4658: return 'ok';
4659: }
4660: }
4661: }
4662: return 'error';
1.212 www 4663: }
4664:
4665: # --------------------------------------------------------------- Verify a symb
4666:
4667: sub symbverify {
1.510 www 4668: my ($symb,$thisurl)=@_;
4669: my $thisfn=$thisurl;
4670: # wrapper not part of symbs
4671: $thisfn=~s/^\/adm\/wrapper//;
1.439 www 4672: $thisfn=&declutter($thisfn);
1.215 www 4673: # direct jump to resource in page or to a sequence - will construct own symbs
4674: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
4675: # check URL part
1.409 www 4676: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 4677:
1.431 www 4678: unless ($url eq $thisfn) { return 0; }
1.213 www 4679:
1.216 www 4680: $symb=&symbclean($symb);
1.510 www 4681: $thisurl=&deversion($thisurl);
1.439 www 4682: $thisfn=&deversion($thisfn);
1.213 www 4683:
4684: my %bighash;
4685: my $okay=0;
1.431 www 4686:
1.213 www 4687: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256 albertel 4688: &GDBM_READER(),0640)) {
1.510 www 4689: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 4690: unless ($ids) {
1.510 www 4691: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 4692: }
4693: if ($ids) {
4694: # ------------------------------------------------------------------- Has ID(s)
4695: foreach (split(/\,/,$ids)) {
4696: my ($mapid,$resid)=split(/\./,$_);
4697: if (
4698: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
4699: eq $symb) {
4700: $okay=1;
4701: }
4702: }
4703: }
1.213 www 4704: untie(%bighash);
4705: }
4706: return $okay;
1.31 www 4707: }
4708:
1.210 www 4709: # --------------------------------------------------------------- Clean-up symb
4710:
4711: sub symbclean {
4712: my $symb=shift;
1.568 ! albertel 4713: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 4714: # remove version from map
4715: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 4716:
1.210 www 4717: # remove version from URL
4718: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 4719:
1.507 www 4720: # remove wrapper
4721:
1.510 www 4722: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210 www 4723: return $symb;
1.409 www 4724: }
4725:
4726: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 4727:
4728: sub encode_symb {
4729: my ($map,$resid,$url)=@_;
4730: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
4731: }
1.409 www 4732:
4733: sub decode_symb {
1.568 ! albertel 4734: my $symb=shift;
! 4735: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
! 4736: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 4737: return (&fixversion($map),$resid,&fixversion($url));
4738: }
4739:
4740: sub fixversion {
4741: my $fn=shift;
4742: if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
1.435 www 4743: my %bighash;
4744: my $uri=&clutter($fn);
1.440 www 4745: my $key=$ENV{'request.course.id'}.'_'.$uri;
4746: # is this cached?
4747: my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
4748: 'courseresversion',600);
4749: if (defined($cached)) { return $result; }
4750: # unfortunately not cached, or expired
1.435 www 4751: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.440 www 4752: &GDBM_READER(),0640)) {
4753: if ($bighash{'version_'.$uri}) {
4754: my $version=$bighash{'version_'.$uri};
1.444 www 4755: unless (($version eq 'mostrecent') ||
4756: ($version==&getversion($uri))) {
1.440 www 4757: $uri=~s/\.(\w+)$/\.$version\.$1/;
4758: }
4759: }
4760: untie %bighash;
1.413 www 4761: }
1.440 www 4762: return &do_cache
4763: (\%courseresversioncache,$key,&declutter($uri),'courseresversion');
1.438 www 4764: }
4765:
4766: sub deversion {
4767: my $url=shift;
4768: $url=~s/\.\d+\.(\w+)$/\.$1/;
4769: return $url;
1.210 www 4770: }
4771:
1.31 www 4772: # ------------------------------------------------------ Return symb list entry
4773:
4774: sub symbread {
1.249 www 4775: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 4776: my $cache_str='request.symbread.cached.'.$thisfn;
4777: if (defined($ENV{$cache_str})) { return $ENV{$cache_str}; }
1.242 www 4778: # no filename provided? try from environment
1.44 www 4779: unless ($thisfn) {
1.539 albertel 4780: if ($ENV{'request.symb'}) {
1.542 albertel 4781: return $ENV{$cache_str}=&symbclean($ENV{'request.symb'});
1.539 albertel 4782: }
1.44 www 4783: $thisfn=$ENV{'request.filename'};
4784: }
1.242 www 4785: # is that filename actually a symb? Verify, clean, and return
4786: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 4787: if (&symbverify($thisfn,$1)) {
1.542 albertel 4788: return $ENV{$cache_str}=&symbclean($thisfn);
1.539 albertel 4789: }
1.242 www 4790: }
1.44 www 4791: $thisfn=declutter($thisfn);
1.31 www 4792: my %hash;
1.37 www 4793: my %bighash;
4794: my $syval='';
1.45 www 4795: if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 4796: my $targetfn = $thisfn;
4797: if ( ($thisfn =~ m/^uploaded\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
4798: $targetfn = 'adm/wrapper/'.$thisfn;
4799: }
1.31 www 4800: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256 albertel 4801: &GDBM_READER(),0640)) {
1.481 raeburn 4802: $syval=$hash{$targetfn};
1.37 www 4803: untie(%hash);
4804: }
4805: # ---------------------------------------------------------- There was an entry
4806: if ($syval) {
4807: unless ($syval=~/\_\d+$/) {
4808: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44 www 4809: &appenv('request.ambiguous' => $thisfn);
1.542 albertel 4810: return $ENV{$cache_str}='';
1.37 www 4811: }
4812: $syval.=$1;
4813: }
4814: } else {
4815: # ------------------------------------------------------- Was not in symb table
4816: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256 albertel 4817: &GDBM_READER(),0640)) {
1.37 www 4818: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 4819: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 4820: unless ($ids) {
4821: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 4822: }
4823: unless ($ids) {
4824: # alias?
4825: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 4826: }
1.37 www 4827: if ($ids) {
4828: # ------------------------------------------------------------------- Has ID(s)
4829: my @possibilities=split(/\,/,$ids);
1.39 www 4830: if ($#possibilities==0) {
4831: # ----------------------------------------------- There is only one possibility
1.37 www 4832: my ($mapid,$resid)=split(/\./,$ids);
4833: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249 www 4834: } elsif (!$donotrecurse) {
1.39 www 4835: # ------------------------------------------ There is more than one possibility
4836: my $realpossible=0;
1.191 harris41 4837: foreach (@possibilities) {
1.39 www 4838: my $file=$bighash{'src_'.$_};
4839: if (&allowed('bre',$file)) {
4840: my ($mapid,$resid)=split(/\./,$_);
4841: if ($bighash{'map_type_'.$mapid} ne 'page') {
4842: $realpossible++;
4843: $syval=declutter($bighash{'map_id_'.$mapid}).
4844: '___'.$resid;
4845: }
4846: }
1.191 harris41 4847: }
1.39 www 4848: if ($realpossible!=1) { $syval=''; }
1.249 www 4849: } else {
4850: $syval='';
1.37 www 4851: }
4852: }
4853: untie(%bighash)
1.481 raeburn 4854: }
1.31 www 4855: }
1.62 www 4856: if ($syval) {
1.542 albertel 4857: return $ENV{$cache_str}=&symbclean($syval.'___'.$thisfn);
1.62 www 4858: }
1.31 www 4859: }
1.44 www 4860: &appenv('request.ambiguous' => $thisfn);
1.542 albertel 4861: return $ENV{$cache_str}='';
1.31 www 4862: }
4863:
4864: # ---------------------------------------------------------- Return random seed
4865:
1.32 www 4866: sub numval {
4867: my $txt=shift;
4868: $txt=~tr/A-J/0-9/;
4869: $txt=~tr/a-j/0-9/;
4870: $txt=~tr/K-T/0-9/;
4871: $txt=~tr/k-t/0-9/;
4872: $txt=~tr/U-Z/0-5/;
4873: $txt=~tr/u-z/0-5/;
4874: $txt=~s/\D//g;
1.564 albertel 4875: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 4876: return int($txt);
1.368 albertel 4877: }
4878:
1.484 albertel 4879: sub numval2 {
4880: my $txt=shift;
4881: $txt=~tr/A-J/0-9/;
4882: $txt=~tr/a-j/0-9/;
4883: $txt=~tr/K-T/0-9/;
4884: $txt=~tr/k-t/0-9/;
4885: $txt=~tr/U-Z/0-5/;
4886: $txt=~tr/u-z/0-5/;
4887: $txt=~s/\D//g;
4888: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
4889: my $total;
4890: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 4891: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 4892: return int($total);
4893: }
4894:
1.368 albertel 4895: sub latest_rnd_algorithm_id {
1.501 albertel 4896: return '64bit3';
1.366 albertel 4897: }
1.32 www 4898:
1.503 albertel 4899: sub get_rand_alg {
4900: my ($courseid)=@_;
4901: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
4902: if ($courseid) {
4903: return $ENV{"course.$courseid.rndseed"};
4904: }
4905: return &latest_rnd_algorithm_id();
4906: }
4907:
1.562 albertel 4908: sub validCODE {
4909: my ($CODE)=@_;
4910: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
4911: return 0;
4912: }
4913:
1.491 albertel 4914: sub getCODE {
1.562 albertel 4915: if (&validCODE($ENV{'form.CODE'})) { return $ENV{'form.CODE'}; }
1.491 albertel 4916: if (defined($Apache::lonhomework::parsing_a_problem) &&
1.562 albertel 4917: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 4918: return $Apache::lonhomework::history{'resource.CODE'};
4919: }
4920: return undef;
4921: }
4922:
1.31 www 4923: sub rndseed {
1.155 albertel 4924: my ($symb,$courseid,$domain,$username)=@_;
1.366 albertel 4925:
4926: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155 albertel 4927: if (!$symb) {
1.366 albertel 4928: unless ($symb=$wsymb) { return time; }
4929: }
4930: if (!$courseid) { $courseid=$wcourseid; }
4931: if (!$domain) { $domain=$wdomain; }
4932: if (!$username) { $username=$wusername }
1.503 albertel 4933: my $which=&get_rand_alg();
1.491 albertel 4934: if (defined(&getCODE())) {
1.484 albertel 4935: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
1.501 albertel 4936: } elsif ($which eq '64bit3') {
4937: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 4938: } elsif ($which eq '64bit2') {
4939: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 4940: } elsif ($which eq '64bit') {
4941: return &rndseed_64bit($symb,$courseid,$domain,$username);
4942: }
4943: return &rndseed_32bit($symb,$courseid,$domain,$username);
4944: }
4945:
4946: sub rndseed_32bit {
4947: my ($symb,$courseid,$domain,$username)=@_;
4948: {
4949: use integer;
4950: my $symbchck=unpack("%32C*",$symb) << 27;
4951: my $symbseed=numval($symb) << 22;
4952: my $namechck=unpack("%32C*",$username) << 17;
4953: my $nameseed=numval($username) << 12;
4954: my $domainseed=unpack("%32C*",$domain) << 7;
4955: my $courseseed=unpack("%32C*",$courseid);
4956: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
4957: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4958: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.564 albertel 4959: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 4960: return $num;
4961: }
4962: }
4963:
4964: sub rndseed_64bit {
4965: my ($symb,$courseid,$domain,$username)=@_;
4966: {
4967: use integer;
4968: my $symbchck=unpack("%32S*",$symb) << 21;
4969: my $symbseed=numval($symb) << 10;
4970: my $namechck=unpack("%32S*",$username);
4971:
4972: my $nameseed=numval($username) << 21;
4973: my $domainseed=unpack("%32S*",$domain) << 10;
4974: my $courseseed=unpack("%32S*",$courseid);
4975:
4976: my $num1=$symbchck+$symbseed+$namechck;
4977: my $num2=$nameseed+$domainseed+$courseseed;
4978: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4979: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.564 albertel 4980: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
4981: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 4982: return "$num1,$num2";
1.155 albertel 4983: }
1.366 albertel 4984: }
4985:
1.443 albertel 4986: sub rndseed_64bit2 {
4987: my ($symb,$courseid,$domain,$username)=@_;
4988: {
4989: use integer;
4990: # strings need to be an even # of cahracters long, it it is odd the
4991: # last characters gets thrown away
4992: my $symbchck=unpack("%32S*",$symb.' ') << 21;
4993: my $symbseed=numval($symb) << 10;
4994: my $namechck=unpack("%32S*",$username.' ');
4995:
4996: my $nameseed=numval($username) << 21;
1.501 albertel 4997: my $domainseed=unpack("%32S*",$domain.' ') << 10;
4998: my $courseseed=unpack("%32S*",$courseid.' ');
4999:
5000: my $num1=$symbchck+$symbseed+$namechck;
5001: my $num2=$nameseed+$domainseed+$courseseed;
5002: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5003: #&Apache::lonxml::debug("rndseed :$num:$symb");
5004: return "$num1,$num2";
5005: }
5006: }
5007:
5008: sub rndseed_64bit3 {
5009: my ($symb,$courseid,$domain,$username)=@_;
5010: {
5011: use integer;
5012: # strings need to be an even # of cahracters long, it it is odd the
5013: # last characters gets thrown away
5014: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5015: my $symbseed=numval2($symb) << 10;
5016: my $namechck=unpack("%32S*",$username.' ');
5017:
5018: my $nameseed=numval2($username) << 21;
1.443 albertel 5019: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5020: my $courseseed=unpack("%32S*",$courseid.' ');
5021:
5022: my $num1=$symbchck+$symbseed+$namechck;
5023: my $num2=$nameseed+$domainseed+$courseseed;
5024: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564 albertel 5025: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
5026: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5027:
1.503 albertel 5028: return "$num1:$num2";
1.443 albertel 5029: }
5030: }
5031:
1.366 albertel 5032: sub rndseed_CODE_64bit {
5033: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 5034: {
1.366 albertel 5035: use integer;
1.443 albertel 5036: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 5037: my $symbseed=numval2($symb);
1.491 albertel 5038: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
5039: my $CODEseed=numval(&getCODE());
1.443 albertel 5040: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 5041: my $num1=$symbseed+$CODEchck;
5042: my $num2=$CODEseed+$courseseed+$symbchck;
5043: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366 albertel 5044: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564 albertel 5045: if ($_64bit) { $num1=(($num1<<32)>>32); }
5046: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 5047: return "$num1:$num2";
1.366 albertel 5048: }
5049: }
5050:
5051: sub setup_random_from_rndseed {
5052: my ($rndseed)=@_;
1.503 albertel 5053: if ($rndseed =~/([,:])/) {
5054: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 5055: &Math::Random::random_set_seed(abs($num1),abs($num2));
5056: } else {
5057: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 5058: }
1.36 albertel 5059: }
5060:
1.474 albertel 5061: sub latest_receipt_algorithm_id {
5062: return 'receipt2';
5063: }
5064:
1.480 www 5065: sub recunique {
5066: my $fucourseid=shift;
5067: my $unique;
5068: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
5069: $unique=$ENV{"course.$fucourseid.internal.encseed"};
5070: } else {
5071: $unique=$perlvar{'lonReceipt'};
5072: }
5073: return unpack("%32C*",$unique);
5074: }
5075:
5076: sub recprefix {
5077: my $fucourseid=shift;
5078: my $prefix;
5079: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
5080: $prefix=$ENV{"course.$fucourseid.internal.encpref"};
5081: } else {
5082: $prefix=$perlvar{'lonHostID'};
5083: }
5084: return unpack("%32C*",$prefix);
5085: }
5086:
1.76 www 5087: sub ireceipt {
1.474 albertel 5088: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76 www 5089: my $cuname=unpack("%32C*",$funame);
5090: my $cudom=unpack("%32C*",$fudom);
5091: my $cucourseid=unpack("%32C*",$fucourseid);
5092: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 5093: my $cunique=&recunique($fucourseid);
1.474 albertel 5094: my $cpart=unpack("%32S*",$part);
1.480 www 5095: my $return =&recprefix($fucourseid).'-';
1.474 albertel 5096: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
5097: $ENV{'request.state'} eq 'construct') {
5098: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname).
5099: " and ".($cpart%$cudom));
5100:
5101: $return.= ($cunique%$cuname+
5102: $cunique%$cudom+
5103: $cusymb%$cuname+
5104: $cusymb%$cudom+
5105: $cucourseid%$cuname+
5106: $cucourseid%$cudom+
5107: $cpart%$cuname+
5108: $cpart%$cudom);
5109: } else {
5110: $return.= ($cunique%$cuname+
5111: $cunique%$cudom+
5112: $cusymb%$cuname+
5113: $cusymb%$cudom+
5114: $cucourseid%$cuname+
5115: $cucourseid%$cudom);
5116: }
5117: return $return;
1.76 www 5118: }
5119:
5120: sub receipt {
1.474 albertel 5121: my ($part)=@_;
5122: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
5123: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 5124: }
1.260 ng 5125:
1.36 albertel 5126: # ------------------------------------------------------------ Serves up a file
1.472 albertel 5127: # returns either the contents of the file or
5128: # -1 if the file doesn't exist
1.481 raeburn 5129: #
5130: # if the target is a file that was uploaded via DOCS,
5131: # a check will be made to see if a current copy exists on the local server,
5132: # if it does this will be served, otherwise a copy will be retrieved from
5133: # the home server for the course and stored in /home/httpd/html/userfiles on
5134: # the local server.
1.472 albertel 5135:
1.36 albertel 5136: sub getfile {
1.538 albertel 5137: my ($file) = @_;
1.482 albertel 5138:
1.538 albertel 5139: if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); }
5140: &repcopy($file);
5141: return &readfile($file);
5142: }
5143:
5144: sub repcopy_userfile {
5145: my ($file)=@_;
5146:
5147: if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); }
5148: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return OK; }
5149:
5150: my ($cdom,$cnum,$filename) =
5151: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
5152: my ($info,$rtncode);
5153: my $uri="/uploaded/$cdom/$cnum/$filename";
5154: if (-e "$file") {
5155: my @fileinfo = stat($file);
5156: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 5157: if ($lwpresp ne 'ok') {
5158: if ($rtncode eq '404') {
1.538 albertel 5159: unlink($file);
1.482 albertel 5160: }
1.517 albertel 5161: #my $ua=new LWP::UserAgent;
1.538 albertel 5162: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 5163: #my $response=$ua->request($request);
5164: #if ($response->is_success()) {
5165: # return $response->content;
5166: # } else {
5167: # return -1;
5168: # }
1.482 albertel 5169: return -1;
5170: }
5171: if ($info < $fileinfo[9]) {
1.538 albertel 5172: return OK;
1.482 albertel 5173: }
5174: $info = '';
1.538 albertel 5175: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 5176: if ($lwpresp ne 'ok') {
5177: return -1;
5178: }
5179: } else {
1.538 albertel 5180: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 5181: if ($lwpresp ne 'ok') {
1.517 albertel 5182: my $ua=new LWP::UserAgent;
1.538 albertel 5183: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 5184: my $response=$ua->request($request);
5185: if ($response->is_success()) {
1.538 albertel 5186: $info=$response->content;
1.517 albertel 5187: } else {
5188: return -1;
5189: }
1.482 albertel 5190: }
5191: my @parts = ($cdom,$cnum);
5192: if ($filename =~ m|^(.+)/[^/]+$|) {
5193: push @parts, split(/\//,$1);
1.518 albertel 5194: }
1.538 albertel 5195: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482 albertel 5196: foreach my $part (@parts) {
5197: $path .= '/'.$part;
5198: if (!-e $path) {
5199: mkdir($path,0770);
5200: }
5201: }
5202: }
1.538 albertel 5203: open(FILE,">$file");
1.482 albertel 5204: print FILE $info;
5205: close(FILE);
1.538 albertel 5206: return OK;
1.481 raeburn 5207: }
5208:
1.517 albertel 5209: sub tokenwrapper {
5210: my $uri=shift;
1.552 albertel 5211: $uri=~s|^http\://([^/]+)||;
5212: $uri=~s|^/||;
1.517 albertel 5213: $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
5214: my $token=$1;
1.552 albertel 5215: my (undef,$udom,$uname,$file)=split('/',$uri,4);
5216: if ($udom && $uname && $file) {
5217: $file=~s|(\?\.*)*$||;
5218: &appenv("userfile.$udom/$uname/$file" => $ENV{'request.course.id'});
5219: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517 albertel 5220: (($uri=~/\?/)?'&':'?').'token='.$token.
5221: '&tokenissued='.$perlvar{'lonHostID'};
5222: } else {
5223: return '/adm/notfound.html';
5224: }
5225: }
5226:
1.481 raeburn 5227: sub getuploaded {
5228: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
5229: $uri=~s/^\///;
5230: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
5231: my $ua=new LWP::UserAgent;
5232: my $request=new HTTP::Request($reqtype,$uri);
5233: my $response=$ua->request($request);
5234: $$rtncode = $response->code;
1.482 albertel 5235: if (! $response->is_success()) {
5236: return 'failed';
5237: }
5238: if ($reqtype eq 'HEAD') {
1.486 www 5239: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 5240: } elsif ($reqtype eq 'GET') {
5241: $$info = $response->content;
1.472 albertel 5242: }
1.482 albertel 5243: return 'ok';
1.36 albertel 5244: }
5245:
1.481 raeburn 5246: sub readfile {
5247: my $file = shift;
5248: if ( (! -e $file ) || ($file eq '') ) { return -1; };
5249: my $fh;
5250: open($fh,"<$file");
5251: my $a='';
5252: while (<$fh>) { $a .=$_; }
5253: return $a;
5254: }
5255:
1.36 albertel 5256: sub filelocation {
5257: my ($dir,$file) = @_;
5258: my $location;
5259: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59 albertel 5260: if ($file=~m:^/~:) { # is a contruction space reference
5261: $location = $file;
5262: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270 www 5263: } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
1.537 albertel 5264: my ($udom,$uname,$filename)=
5265: ($file=~m|^/+uploaded/+([^/]+)/+([^/]+)/+(.*)$|);
5266: my $home=&homeserver($uname,$udom);
5267: my $is_me=0;
1.536 sakharuk 5268: my @ids=¤t_machine_ids();
1.537 albertel 5269: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
5270: if ($is_me) {
5271: $location=&Apache::loncommon::propath($udom,$uname).
5272: '/userfiles/'.$filename;
1.527 sakharuk 5273: } else {
1.537 albertel 5274: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
5275: $udom.'/'.$uname.'/'.$filename;
1.527 sakharuk 5276: }
1.36 albertel 5277: } else {
1.479 albertel 5278: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.464 albertel 5279: $file=~s:^/res/:/:;
1.59 albertel 5280: if ( !( $file =~ m:^/:) ) {
5281: $location = $dir. '/'.$file;
5282: } else {
5283: $location = '/home/httpd/html/res'.$file;
5284: }
1.36 albertel 5285: }
5286: $location=~s://+:/:g; # remove duplicate /
1.46 www 5287: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
1.475 albertel 5288: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
1.46 www 5289: return $location;
5290: }
1.36 albertel 5291:
1.46 www 5292: sub hreflocation {
5293: my ($dir,$file)=@_;
1.460 albertel 5294: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
5295: my $finalpath=filelocation($dir,$file);
5296: $finalpath=~s-^/home/httpd/html--;
1.462 albertel 5297: $finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460 albertel 5298: return $finalpath;
5299: } elsif ($file=~m-^/home-) {
5300: $file=~s-^/home/httpd/html--;
1.462 albertel 5301: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460 albertel 5302: return $file;
1.46 www 5303: }
1.462 albertel 5304: return $file;
1.465 albertel 5305: }
5306:
5307: sub current_machine_domains {
5308: my $hostname=$hostname{$perlvar{'lonHostID'}};
5309: my @domains;
5310: while( my($id, $name) = each(%hostname)) {
1.467 matthew 5311: # &logthis("-$id-$name-$hostname-");
1.465 albertel 5312: if ($hostname eq $name) {
5313: push(@domains,$hostdom{$id});
5314: }
5315: }
5316: return @domains;
5317: }
5318:
5319: sub current_machine_ids {
5320: my $hostname=$hostname{$perlvar{'lonHostID'}};
5321: my @ids;
5322: while( my($id, $name) = each(%hostname)) {
1.467 matthew 5323: # &logthis("-$id-$name-$hostname-");
1.465 albertel 5324: if ($hostname eq $name) {
5325: push(@ids,$id);
5326: }
5327: }
5328: return @ids;
1.31 www 5329: }
5330:
5331: # ------------------------------------------------------------- Declutters URLs
5332:
5333: sub declutter {
5334: my $thisfn=shift;
1.479 albertel 5335: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 5336: $thisfn=~s/^\///;
5337: $thisfn=~s/^res\///;
1.235 www 5338: $thisfn=~s/\?.+$//;
1.268 www 5339: return $thisfn;
5340: }
5341:
5342: # ------------------------------------------------------------- Clutter up URLs
5343:
5344: sub clutter {
5345: my $thisfn='/'.&declutter(shift);
1.509 albertel 5346: unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 5347: $thisfn='/res'.$thisfn;
5348: }
1.31 www 5349: return $thisfn;
1.12 www 5350: }
5351:
1.557 albertel 5352: sub freeze_escape {
5353: my ($value)=@_;
5354: if (ref($value)) {
5355: $value=&nfreeze($value);
5356: return '__FROZEN__'.&escape($value);
5357: }
5358: return &escape($value);
5359: }
5360:
1.12 www 5361: # -------------------------------------------------------- Escape Special Chars
5362:
5363: sub escape {
5364: my $str=shift;
5365: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
5366: return $str;
5367: }
5368:
5369: # ----------------------------------------------------- Un-Escape Special Chars
5370:
5371: sub unescape {
5372: my $str=shift;
5373: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
5374: return $str;
5375: }
1.11 www 5376:
1.557 albertel 5377: sub thaw_unescape {
5378: my ($value)=@_;
5379: if ($value =~ /^__FROZEN__/) {
5380: substr($value,0,10,undef);
5381: $value=&unescape($value);
5382: return &thaw($value);
5383: }
5384: return &unescape($value);
5385: }
5386:
1.415 albertel 5387: sub mod_perl_version {
5388: if (defined($perlvar{'MODPERL2'})) {
5389: return 2;
5390: }
5391: return 1;
1.436 albertel 5392: }
5393:
5394: sub correct_line_ends {
5395: my ($result)=@_;
5396: $$result =~s/\r\n/\n/mg;
5397: $$result =~s/\r/\n/mg;
1.415 albertel 5398: }
1.1 albertel 5399: # ================================================================ Main Program
5400:
1.184 www 5401: sub goodbye {
1.204 albertel 5402: &logthis("Starting Shut down");
1.443 albertel 5403: #not converted to using infrastruture and probably shouldn't be
1.425 albertel 5404: &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache)));
1.443 albertel 5405: #converted
1.425 albertel 5406: &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.443 albertel 5407: &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache)));
1.425 albertel 5408: &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache)));
5409: &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache)));
5410: #1.1 only
5411: &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache)));
1.551 albertel 5412: &logthis(sprintf("%-20s is %s",'%getsectioncache',scalar(%getsectioncache)));
1.440 www 5413: &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache)));
5414: &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache)));
1.184 www 5415: &flushcourselogs();
5416: &logthis("Shutting down");
1.362 albertel 5417: return DONE;
1.184 www 5418: }
5419:
1.179 www 5420: BEGIN {
1.228 harris41 5421: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 5422: unless ($readit) {
1.217 harris41 5423: {
1.448 albertel 5424: open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217 harris41 5425:
5426: while (my $configline=<$config>) {
1.484 albertel 5427: if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1 albertel 5428: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8 www 5429: chomp($varvalue);
1.1 albertel 5430: $perlvar{$varname}=$varvalue;
5431: }
5432: }
1.448 albertel 5433: close($config);
1.1 albertel 5434: }
1.227 harris41 5435: {
1.448 albertel 5436: open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227 harris41 5437:
5438: while (my $configline=<$config>) {
5439: if ($configline =~ /^[^\#]*PerlSetVar/) {
5440: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
5441: chomp($varvalue);
5442: $perlvar{$varname}=$varvalue;
5443: }
5444: }
1.448 albertel 5445: close($config);
1.227 harris41 5446: }
1.1 albertel 5447:
1.327 albertel 5448: # ------------------------------------------------------------ Read domain file
5449: {
5450: %domaindescription = ();
5451: %domain_auth_def = ();
5452: %domain_auth_arg_def = ();
1.448 albertel 5453: my $fh;
5454: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327 albertel 5455: while (<$fh>) {
1.390 matthew 5456: next if (/^(\#|\s*$)/);
5457: # next if /^\#/;
1.327 albertel 5458: chomp;
1.403 www 5459: my ($domain, $domain_description, $def_auth, $def_auth_arg,
5460: $def_lang, $city, $longi, $lati) = split(/:/,$_);
5461: $domain_auth_def{$domain}=$def_auth;
1.327 albertel 5462: $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403 www 5463: $domaindescription{$domain}=$domain_description;
5464: $domain_lang_def{$domain}=$def_lang;
5465: $domain_city{$domain}=$city;
5466: $domain_longi{$domain}=$longi;
5467: $domain_lati{$domain}=$lati;
5468:
1.448 albertel 5469: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327 albertel 5470: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448 albertel 5471: }
1.327 albertel 5472: }
1.448 albertel 5473: close ($fh);
1.327 albertel 5474: }
5475:
5476:
1.1 albertel 5477: # ------------------------------------------------------------- Read hosts file
5478: {
1.448 albertel 5479: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1 albertel 5480:
5481: while (my $configline=<$config>) {
1.303 matthew 5482: next if ($configline =~ /^(\#|\s*$)/);
1.154 www 5483: chomp($configline);
1.245 www 5484: my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252 albertel 5485: if ($id && $domain && $role && $name && $ip) {
5486: $hostname{$id}=$name;
5487: $hostdom{$id}=$domain;
5488: $hostip{$id}=$ip;
1.300 albertel 5489: $iphost{$ip}=$id;
1.252 albertel 5490: if ($role eq 'library') { $libserv{$id}=$name; }
1.245 www 5491: }
1.1 albertel 5492: }
1.448 albertel 5493: close($config);
1.1 albertel 5494: }
5495:
5496: # ------------------------------------------------------ Read spare server file
5497: {
1.448 albertel 5498: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 5499:
5500: while (my $configline=<$config>) {
5501: chomp($configline);
1.284 matthew 5502: if ($configline) {
1.1 albertel 5503: $spareid{$configline}=1;
5504: }
5505: }
1.448 albertel 5506: close($config);
1.1 albertel 5507: }
1.11 www 5508: # ------------------------------------------------------------ Read permissions
5509: {
1.448 albertel 5510: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 5511:
5512: while (my $configline=<$config>) {
1.448 albertel 5513: chomp($configline);
5514: if ($configline) {
5515: my ($role,$perm)=split(/ /,$configline);
5516: if ($perm ne '') { $pr{$role}=$perm; }
5517: }
1.11 www 5518: }
1.448 albertel 5519: close($config);
1.11 www 5520: }
5521:
5522: # -------------------------------------------- Read plain texts for permissions
5523: {
1.448 albertel 5524: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 5525:
5526: while (my $configline=<$config>) {
1.448 albertel 5527: chomp($configline);
5528: if ($configline) {
5529: my ($short,$plain)=split(/:/,$configline);
5530: if ($plain ne '') { $prp{$short}=$plain; }
5531: }
1.135 www 5532: }
1.448 albertel 5533: close($config);
1.135 www 5534: }
5535:
5536: # ---------------------------------------------------------- Read package table
5537: {
1.448 albertel 5538: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 5539:
5540: while (my $configline=<$config>) {
1.483 albertel 5541: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 5542: chomp($configline);
5543: my ($short,$plain)=split(/:/,$configline);
5544: my ($pack,$name)=split(/\&/,$short);
5545: if ($plain ne '') {
5546: $packagetab{$pack.'&'.$name.'&name'}=$name;
5547: $packagetab{$short}=$plain;
5548: }
1.11 www 5549: }
1.448 albertel 5550: close($config);
1.329 matthew 5551: }
5552:
5553: # ------------- set up temporary directory
5554: {
5555: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
5556:
1.11 www 5557: }
5558:
1.71 www 5559: %metacache=();
1.185 www 5560:
1.281 www 5561: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 5562: $dumpcount=0;
1.22 www 5563:
1.163 harris41 5564: &logtouch();
1.12 www 5565: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195 www 5566: $readit=1;
1.564 albertel 5567: {
5568: use integer;
5569: my $test=(2**32)+1;
1.568 ! albertel 5570: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 5571: &logthis(" Detected 64bit platform ($_64bit)");
5572: }
1.195 www 5573: }
1.1 albertel 5574: }
1.179 www 5575:
1.1 albertel 5576: 1;
1.191 harris41 5577: __END__
5578:
1.243 albertel 5579: =pod
5580:
1.191 harris41 5581: =head1 NAME
5582:
1.243 albertel 5583: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 5584:
5585: =head1 SYNOPSIS
5586:
1.243 albertel 5587: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 5588:
5589: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
5590:
1.243 albertel 5591: Common parameters:
5592:
5593: =over 4
5594:
5595: =item *
5596:
5597: $uname : an internal username (if $cname expecting a course Id specifically)
5598:
5599: =item *
5600:
5601: $udom : a domain (if $cdom expecting a course's domain specifically)
5602:
5603: =item *
5604:
5605: $symb : a resource instance identifier
5606:
5607: =item *
5608:
5609: $namespace : the name of a .db file that contains the data needed or
5610: being set.
5611:
5612: =back
5613:
1.394 bowersj2 5614: =head1 OVERVIEW
1.191 harris41 5615:
1.394 bowersj2 5616: lonnet provides subroutines which interact with the
5617: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
5618: about classes, users, and resources.
1.243 albertel 5619:
5620: For many of these objects you can also use this to store data about
5621: them or modify them in various ways.
1.191 harris41 5622:
1.394 bowersj2 5623: =head2 Symbs
1.191 harris41 5624:
1.394 bowersj2 5625: To identify a specific instance of a resource, LON-CAPA uses symbols
5626: or "symbs"X<symb>. These identifiers are built from the URL of the
5627: map, the resource number of the resource in the map, and the URL of
5628: the resource itself. The latter is somewhat redundant, but might help
5629: if maps change.
5630:
5631: An example is
5632:
5633: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
5634:
5635: The respective map entry is
5636:
5637: <resource id="19" src="/res/msu/korte/tests/part12.problem"
5638: title="Problem 2">
5639: </resource>
5640:
5641: Symbs are used by the random number generator, as well as to store and
5642: restore data specific to a certain instance of for example a problem.
5643:
5644: =head2 Storing And Retrieving Data
5645:
5646: X<store()>X<cstore()>X<restore()>Three of the most important functions
5647: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
5648: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
5649: is is the non-critical message twin of cstore. These functions are for
5650: handlers to store a perl hash to a user's permanent data space in an
5651: easy manner, and to retrieve it again on another call. It is expected
5652: that a handler would use this once at the beginning to retrieve data,
5653: and then again once at the end to send only the new data back.
5654:
5655: The data is stored in the user's data directory on the user's
5656: homeserver under the ID of the course.
5657:
5658: The hash that is returned by restore will have all of the previous
5659: value for all of the elements of the hash.
5660:
5661: Example:
5662:
5663: #creating a hash
5664: my %hash;
5665: $hash{'foo'}='bar';
5666:
5667: #storing it
5668: &Apache::lonnet::cstore(\%hash);
5669:
5670: #changing a value
5671: $hash{'foo'}='notbar';
5672:
5673: #adding a new value
5674: $hash{'bar'}='foo';
5675: &Apache::lonnet::cstore(\%hash);
5676:
5677: #retrieving the hash
5678: my %history=&Apache::lonnet::restore();
5679:
5680: #print the hash
5681: foreach my $key (sort(keys(%history))) {
5682: print("\%history{$key} = $history{$key}");
5683: }
5684:
5685: Will print out:
1.191 harris41 5686:
1.394 bowersj2 5687: %history{1:foo} = bar
5688: %history{1:keys} = foo:timestamp
5689: %history{1:timestamp} = 990455579
5690: %history{2:bar} = foo
5691: %history{2:foo} = notbar
5692: %history{2:keys} = foo:bar:timestamp
5693: %history{2:timestamp} = 990455580
5694: %history{bar} = foo
5695: %history{foo} = notbar
5696: %history{timestamp} = 990455580
5697: %history{version} = 2
5698:
5699: Note that the special hash entries C<keys>, C<version> and
5700: C<timestamp> were added to the hash. C<version> will be equal to the
5701: total number of versions of the data that have been stored. The
5702: C<timestamp> attribute will be the UNIX time the hash was
5703: stored. C<keys> is available in every historical section to list which
5704: keys were added or changed at a specific historical revision of a
5705: hash.
5706:
5707: B<Warning>: do not store the hash that restore returns directly. This
5708: will cause a mess since it will restore the historical keys as if the
5709: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 5710:
1.394 bowersj2 5711: Calling convention:
1.191 harris41 5712:
1.394 bowersj2 5713: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
5714: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 5715:
1.394 bowersj2 5716: For more detailed information, see lonnet specific documentation.
1.191 harris41 5717:
1.394 bowersj2 5718: =head1 RETURN MESSAGES
1.191 harris41 5719:
1.394 bowersj2 5720: =over 4
1.191 harris41 5721:
1.394 bowersj2 5722: =item * B<con_lost>: unable to contact remote host
1.191 harris41 5723:
1.394 bowersj2 5724: =item * B<con_delayed>: unable to contact remote host, message will be delivered
5725: when the connection is brought back up
1.191 harris41 5726:
1.394 bowersj2 5727: =item * B<con_failed>: unable to contact remote host and unable to save message
5728: for later delivery
1.191 harris41 5729:
1.394 bowersj2 5730: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 5731:
1.394 bowersj2 5732: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 5733: that was requested
1.191 harris41 5734:
1.243 albertel 5735: =back
1.191 harris41 5736:
1.243 albertel 5737: =head1 PUBLIC SUBROUTINES
1.191 harris41 5738:
1.243 albertel 5739: =head2 Session Environment Functions
1.191 harris41 5740:
1.243 albertel 5741: =over 4
1.191 harris41 5742:
1.394 bowersj2 5743: =item *
5744: X<appenv()>
5745: B<appenv(%hash)>: the value of %hash is written to
5746: the user envirnoment file, and will be restored for each access this
5747: user makes during this session, also modifies the %ENV for the current
5748: process
1.191 harris41 5749:
5750: =item *
1.394 bowersj2 5751: X<delenv()>
5752: B<delenv($regexp)>: removes all items from the session
5753: environment file that matches the regular expression in $regexp. The
5754: values are also delted from the current processes %ENV.
1.191 harris41 5755:
1.243 albertel 5756: =back
5757:
5758: =head2 User Information
1.191 harris41 5759:
1.243 albertel 5760: =over 4
1.191 harris41 5761:
5762: =item *
1.394 bowersj2 5763: X<queryauthenticate()>
5764: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 5765: authentication scheme
5766:
5767: =item *
1.394 bowersj2 5768: X<authenticate()>
5769: B<authenticate($uname,$upass,$udom)>: try to
5770: authenticate user from domain's lib servers (first use the current
5771: one). C<$upass> should be the users password.
1.191 harris41 5772:
5773: =item *
1.394 bowersj2 5774: X<homeserver()>
5775: B<homeserver($uname,$udom)>: find the server which has
5776: the user's directory and files (there must be only one), this caches
5777: the answer, and also caches if there is a borken connection.
1.191 harris41 5778:
5779: =item *
1.394 bowersj2 5780: X<idget()>
5781: B<idget($udom,@ids)>: find the usernames behind a list of IDs
5782: (IDs are a unique resource in a domain, there must be only 1 ID per
5783: username, and only 1 username per ID in a specific domain) (returns
5784: hash: id=>name,id=>name)
1.191 harris41 5785:
5786: =item *
1.394 bowersj2 5787: X<idrget()>
5788: B<idrget($udom,@unames)>: find the IDs behind a list of
5789: usernames (returns hash: name=>id,name=>id)
1.191 harris41 5790:
5791: =item *
1.394 bowersj2 5792: X<idput()>
5793: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 5794:
5795: =item *
1.394 bowersj2 5796: X<rolesinit()>
5797: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 5798:
5799: =item *
1.551 albertel 5800: X<getsection()>
5801: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 5802: course $cname, return section name/number or '' for "not in course"
5803: and '-1' for "no section"
5804:
5805: =item *
1.394 bowersj2 5806: X<userenvironment()>
5807: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 5808: passed in @what from the requested user's environment, returns a hash
5809:
5810: =back
5811:
5812: =head2 User Roles
5813:
5814: =over 4
5815:
5816: =item *
5817:
5818: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
5819: actions
5820: F: full access
5821: U,I,K: authentication modes (cxx only)
5822: '': forbidden
5823: 1: user needs to choose course
5824: 2: browse allowed
5825:
5826: =item *
5827:
5828: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
5829: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
5830: and course level
5831:
5832: =item *
5833:
5834: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
5835: explanation of a user role term
5836:
5837: =back
5838:
5839: =head2 User Modification
5840:
5841: =over 4
5842:
5843: =item *
5844:
5845: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
5846: user for the level given by URL. Optional start and end dates (leave empty
5847: string or zero for "no date")
1.191 harris41 5848:
5849: =item *
5850:
1.243 albertel 5851: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
5852: change a users, password, possible return values are: ok,
5853: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
5854: refused
1.191 harris41 5855:
5856: =item *
5857:
1.243 albertel 5858: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 5859:
5860: =item *
5861:
1.243 albertel 5862: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
5863: modify user
1.191 harris41 5864:
5865: =item *
5866:
1.286 matthew 5867: modifystudent
5868:
5869: modify a students enrollment and identification information.
5870: The course id is resolved based on the current users environment.
5871: This means the envoking user must be a course coordinator or otherwise
5872: associated with a course.
5873:
1.297 matthew 5874: This call is essentially a wrapper for lonnet::modifyuser and
5875: lonnet::modify_student_enrollment
1.286 matthew 5876:
5877: Inputs:
5878:
5879: =over 4
5880:
5881: =item B<$udom> Students loncapa domain
5882:
5883: =item B<$uname> Students loncapa login name
5884:
5885: =item B<$uid> Students id/student number
5886:
5887: =item B<$umode> Students authentication mode
5888:
5889: =item B<$upass> Students password
5890:
5891: =item B<$first> Students first name
5892:
5893: =item B<$middle> Students middle name
5894:
5895: =item B<$last> Students last name
5896:
5897: =item B<$gene> Students generation
5898:
5899: =item B<$usec> Students section in course
5900:
5901: =item B<$end> Unix time of the roles expiration
5902:
5903: =item B<$start> Unix time of the roles start date
5904:
5905: =item B<$forceid> If defined, allow $uid to be changed
5906:
5907: =item B<$desiredhome> server to use as home server for student
5908:
5909: =back
1.297 matthew 5910:
5911: =item *
5912:
5913: modify_student_enrollment
5914:
5915: Change a students enrollment status in a class. The environment variable
5916: 'role.request.course' must be defined for this function to proceed.
5917:
5918: Inputs:
5919:
5920: =over 4
5921:
5922: =item $udom, students domain
5923:
5924: =item $uname, students name
5925:
5926: =item $uid, students user id
5927:
5928: =item $first, students first name
5929:
5930: =item $middle
5931:
5932: =item $last
5933:
5934: =item $gene
5935:
5936: =item $usec
5937:
5938: =item $end
5939:
5940: =item $start
5941:
5942: =back
5943:
1.191 harris41 5944:
5945: =item *
5946:
1.243 albertel 5947: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
5948: custom role; give a custom role to a user for the level given by URL. Specify
5949: name and domain of role author, and role name
1.191 harris41 5950:
5951: =item *
5952:
1.243 albertel 5953: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 5954:
5955: =item *
5956:
1.243 albertel 5957: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
5958:
5959: =back
5960:
5961: =head2 Course Infomation
5962:
5963: =over 4
1.191 harris41 5964:
5965: =item *
5966:
1.243 albertel 5967: coursedescription($courseid) : course description
1.191 harris41 5968:
5969: =item *
5970:
1.243 albertel 5971: courseresdata($coursenum,$coursedomain,@which) : request for current
5972: parameter setting for a specific course, @what should be a list of
5973: parameters to ask about. This routine caches answers for 5 minutes.
5974:
5975: =back
5976:
5977: =head2 Course Modification
5978:
5979: =over 4
1.191 harris41 5980:
5981: =item *
5982:
1.243 albertel 5983: writecoursepref($courseid,%prefs) : write preferences (environment
5984: database) for a course
1.191 harris41 5985:
5986: =item *
5987:
1.243 albertel 5988: createcourse($udom,$description,$url) : make/modify course
5989:
5990: =back
5991:
5992: =head2 Resource Subroutines
5993:
5994: =over 4
1.191 harris41 5995:
5996: =item *
5997:
1.243 albertel 5998: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 5999:
6000: =item *
6001:
1.243 albertel 6002: repcopy($filename) : subscribes to the requested file, and attempts to
6003: replicate from the owning library server, Might return
6004: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
6005: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
6006: resource. Expects the local filesystem pathname
6007: (/home/httpd/html/res/....)
6008:
6009: =back
6010:
6011: =head2 Resource Information
6012:
6013: =over 4
1.191 harris41 6014:
6015: =item *
6016:
1.243 albertel 6017: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
6018: a vairety of different possible values, $varname should be a request
6019: string, and the other parameters can be used to specify who and what
6020: one is asking about.
6021:
6022: Possible values for $varname are environment.lastname (or other item
6023: from the envirnment hash), user.name (or someother aspect about the
6024: user), resource.0.maxtries (or some other part and parameter of a
6025: resource)
1.204 albertel 6026:
6027: =item *
6028:
1.243 albertel 6029: directcondval($number) : get current value of a condition; reads from a state
6030: string
1.204 albertel 6031:
6032: =item *
6033:
1.243 albertel 6034: condval($condidx) : value of condition index based on state
1.204 albertel 6035:
6036: =item *
6037:
1.243 albertel 6038: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
6039: resource's metadata, $what should be either a specific key, or either
6040: 'keys' (to get a list of possible keys) or 'packages' to get a list of
6041: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
6042:
6043: this function automatically caches all requests
1.191 harris41 6044:
6045: =item *
6046:
1.243 albertel 6047: metadata_query($query,$custom,$customshow) : make a metadata query against the
6048: network of library servers; returns file handle of where SQL and regex results
6049: will be stored for query
1.191 harris41 6050:
6051: =item *
6052:
1.243 albertel 6053: symbread($filename) : return symbolic list entry (filename argument optional);
6054: returns the data handle
1.191 harris41 6055:
6056: =item *
6057:
1.243 albertel 6058: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
6059: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
6060: failure, user must be in a course, as it assumes the existance of the
6061: course initi hash, and uses $ENV('request.course.id'}
6062:
1.191 harris41 6063:
6064: =item *
6065:
1.243 albertel 6066: symbclean($symb) : removes versions numbers from a symb, returns the
6067: cleaned symb
1.191 harris41 6068:
6069: =item *
6070:
1.243 albertel 6071: is_on_map($uri) : checks if the $uri is somewhere on the current
6072: course map, user must be in a course for it to work.
1.191 harris41 6073:
6074: =item *
6075:
1.243 albertel 6076: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 6077:
6078: =item *
6079:
1.243 albertel 6080: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
6081: a random seed, all arguments are optional, if they aren't sent it uses the
6082: environment to derive them. Note: if symb isn't sent and it can't get one
6083: from &symbread it will use the current time as its return value
1.191 harris41 6084:
6085: =item *
6086:
1.243 albertel 6087: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
6088: unfakeable, receipt
1.191 harris41 6089:
6090: =item *
6091:
1.243 albertel 6092: receipt() : API to ireceipt working off of ENV values; given out to users
1.191 harris41 6093:
6094: =item *
6095:
1.243 albertel 6096: countacc($url) : count the number of accesses to a given URL
1.191 harris41 6097:
6098: =item *
6099:
1.243 albertel 6100: 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 6101:
6102: =item *
6103:
1.243 albertel 6104: 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 6105:
6106: =item *
6107:
1.243 albertel 6108: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 6109:
6110: =item *
6111:
1.243 albertel 6112: devalidate($symb) : devalidate temporary spreadsheet calculations,
6113: forcing spreadsheet to reevaluate the resource scores next time.
6114:
6115: =back
6116:
6117: =head2 Storing/Retreiving Data
6118:
6119: =over 4
1.191 harris41 6120:
6121: =item *
6122:
1.243 albertel 6123: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
6124: for this url; hashref needs to be given and should be a \%hashname; the
6125: remaining args aren't required and if they aren't passed or are '' they will
6126: be derived from the ENV
1.191 harris41 6127:
6128: =item *
6129:
1.243 albertel 6130: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
6131: uses critical subroutine
1.191 harris41 6132:
6133: =item *
6134:
1.243 albertel 6135: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
6136: all args are optional
1.191 harris41 6137:
6138: =item *
6139:
1.243 albertel 6140: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
6141: works very similar to store/cstore, but all data is stored in a
6142: temporary location and can be reset using tmpreset, $storehash should
6143: be a hash reference, returns nothing on success
1.191 harris41 6144:
6145: =item *
6146:
1.243 albertel 6147: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
6148: similar to restore, but all data is stored in a temporary location and
6149: can be reset using tmpreset. Returns a hash of values on success,
6150: error string otherwise.
1.191 harris41 6151:
6152: =item *
6153:
1.243 albertel 6154: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
6155: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 6156:
6157: =item *
6158:
1.243 albertel 6159: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
6160: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 6161:
6162: =item *
6163:
1.243 albertel 6164: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
6165: namesp ($udom and $uname are optional)
1.191 harris41 6166:
6167: =item *
6168:
1.243 albertel 6169: dump($namespace,$udom,$uname,$regexp) :
6170: dumps the complete (or key matching regexp) namespace into a hash
6171: ($udom, $uname and $regexp are optional)
1.449 matthew 6172:
6173: =item *
6174:
6175: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
6176: $store can be a scalar, an array reference, or if the amount to be
6177: incremented is > 1, a hash reference.
6178:
6179: ($udom and $uname are optional)
1.191 harris41 6180:
6181: =item *
6182:
1.243 albertel 6183: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
6184: ($udom and $uname are optional)
1.191 harris41 6185:
6186: =item *
6187:
1.524 raeburn 6188: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
6189: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
6190: used in records written by &store and retrieved by &restore. This function
6191: was created for use in editing discussion posts, without incrementing the
6192: version number included in the key for a particular post. The colon
6193: separated list of attribute names (e.g., the value associated with the key
6194: 1:keys:$symb) is also generated and passed in the ampersand separated
6195: items sent to lonnet::reply().
6196:
6197: =item *
6198:
1.243 albertel 6199: cput($namespace,$storehash,$udom,$uname) : critical put
6200: ($udom and $uname are optional)
1.191 harris41 6201:
6202: =item *
6203:
1.243 albertel 6204: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
6205: reference filled in from namesp (encrypts the return communication)
6206: ($udom and $uname are optional)
1.191 harris41 6207:
6208: =item *
6209:
1.243 albertel 6210: log($udom,$name,$home,$message) : write to permanent log for user; use
6211: critical subroutine
6212:
6213: =back
6214:
6215: =head2 Network Status Functions
6216:
6217: =over 4
1.191 harris41 6218:
6219: =item *
6220:
6221: dirlist($uri) : return directory list based on URI
6222:
6223: =item *
6224:
1.243 albertel 6225: spareserver() : find server with least workload from spare.tab
6226:
6227: =back
6228:
6229: =head2 Apache Request
6230:
6231: =over 4
1.191 harris41 6232:
6233: =item *
6234:
1.243 albertel 6235: ssi($url,%hash) : server side include, does a complete request cycle on url to
6236: localhost, posts hash
6237:
6238: =back
6239:
6240: =head2 Data to String to Data
6241:
6242: =over 4
1.191 harris41 6243:
6244: =item *
6245:
1.243 albertel 6246: hash2str(%hash) : convert a hash into a string complete with escaping and '='
6247: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 6248:
6249: =item *
6250:
1.243 albertel 6251: hashref2str($hashref) : convert a hashref into a string complete with
6252: escaping and '=' and '&' separators, supports elements that are
6253: arrayrefs and hashrefs
1.191 harris41 6254:
6255: =item *
6256:
1.243 albertel 6257: arrayref2str($arrayref) : convert an arrayref into a string complete
6258: with escaping and '&' separators, supports elements that are arrayrefs
6259: and hashrefs
1.191 harris41 6260:
6261: =item *
6262:
1.243 albertel 6263: str2hash($string) : convert string to hash using unescaping and
6264: splitting on '=' and '&', supports elements that are arrayrefs and
6265: hashrefs
1.191 harris41 6266:
6267: =item *
6268:
1.243 albertel 6269: str2array($string) : convert string to hash using unescaping and
6270: splitting on '&', supports elements that are arrayrefs and hashrefs
6271:
6272: =back
6273:
6274: =head2 Logging Routines
6275:
6276: =over 4
6277:
6278: These routines allow one to make log messages in the lonnet.log and
6279: lonnet.perm logfiles.
1.191 harris41 6280:
6281: =item *
6282:
1.243 albertel 6283: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 6284:
6285: =item *
6286:
1.243 albertel 6287: logthis() : append message to the normal lonnet.log file, it gets
6288: preiodically rolled over and deleted.
1.191 harris41 6289:
6290: =item *
6291:
1.243 albertel 6292: logperm() : append a permanent message to lonnet.perm.log, this log
6293: file never gets deleted by any automated portion of the system, only
6294: messages of critical importance should go in here.
6295:
6296: =back
6297:
6298: =head2 General File Helper Routines
6299:
6300: =over 4
1.191 harris41 6301:
6302: =item *
6303:
1.481 raeburn 6304: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
6305: (a) files in /uploaded
6306: (i) If a local copy of the file exists -
6307: compares modification date of local copy with last-modified date for
6308: definitive version stored on home server for course. If local copy is
6309: stale, requests a new version from the home server and stores it.
6310: If the original has been removed from the home server, then local copy
6311: is unlinked.
6312: (ii) If local copy does not exist -
6313: requests the file from the home server and stores it.
6314:
6315: If $caller is 'uploadrep':
6316: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
6317: for request for files originally uploaded via DOCS.
6318: - returns 'ok' if fresh local copy now available, -1 otherwise.
6319:
6320: Otherwise:
6321: This indicates a call from the content generation phase of the request.
6322: - returns the entire contents of the file or -1.
6323:
6324: (b) files in /res
6325: - returns the entire contents of a file or -1;
6326: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 6327:
6328: =item *
6329:
1.243 albertel 6330: filelocation($dir,$file) : returns file system location of a file
6331: based on URI; meant to be "fairly clean" absolute reference, $dir is a
6332: directory that relative $file lookups are to looked in ($dir of /a/dir
6333: and a file of ../bob will become /a/bob)
1.191 harris41 6334:
6335: =item *
6336:
6337: hreflocation($dir,$file) : returns file system location or a URL; same as
6338: filelocation except for hrefs
6339:
6340: =item *
6341:
6342: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
6343:
1.243 albertel 6344: =back
6345:
6346: =head2 HTTP Helper Routines
6347:
6348: =over 4
6349:
1.191 harris41 6350: =item *
6351:
6352: escape() : unpack non-word characters into CGI-compatible hex codes
6353:
6354: =item *
6355:
6356: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
6357:
1.243 albertel 6358: =back
6359:
6360: =head1 PRIVATE SUBROUTINES
6361:
6362: =head2 Underlying communication routines (Shouldn't call)
6363:
6364: =over 4
6365:
6366: =item *
6367:
6368: subreply() : tries to pass a message to lonc, returns con_lost if incapable
6369:
6370: =item *
6371:
6372: reply() : uses subreply to send a message to remote machine, logs all failures
6373:
6374: =item *
6375:
6376: critical() : passes a critical message to another server; if cannot
6377: get through then place message in connection buffer directory and
6378: returns con_delayed, if incapable of saving message, returns
6379: con_failed
6380:
6381: =item *
6382:
6383: reconlonc() : tries to reconnect lonc client processes.
6384:
6385: =back
6386:
6387: =head2 Resource Access Logging
6388:
6389: =over 4
6390:
6391: =item *
6392:
6393: flushcourselogs() : flush (save) buffer logs and access logs
6394:
6395: =item *
6396:
6397: courselog($what) : save message for course in hash
6398:
6399: =item *
6400:
6401: courseacclog($what) : save message for course using &courselog(). Perform
6402: special processing for specific resource types (problems, exams, quizzes, etc).
6403:
1.191 harris41 6404: =item *
6405:
6406: goodbye() : flush course logs and log shutting down; it is called in srm.conf
6407: as a PerlChildExitHandler
1.243 albertel 6408:
6409: =back
6410:
6411: =head2 Other
6412:
6413: =over 4
6414:
6415: =item *
6416:
6417: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 6418:
6419: =back
6420:
6421: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>