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