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