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