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