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