Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.871
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.871 ! albertel 4: # $Id: lonnet.pm,v 1.870 2007/04/12 00:03:08 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.486 www 34: use HTTP::Date;
35: # use Date::Parse;
1.871 ! albertel 36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
! 37: $_64bit %env);
! 38:
! 39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
! 40: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
! 41: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
! 42: %courseownerbuf, %coursetypebuf);
1.403 www 43:
1.1 albertel 44: use IO::Socket;
1.31 www 45: use GDBM_File;
1.208 albertel 46: use HTML::LCParser;
1.88 www 47: use Fcntl qw(:flock);
1.870 albertel 48: use Storable qw(thaw nfreeze);
1.539 albertel 49: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 50: use Cache::Memcached;
1.676 albertel 51: use Digest::MD5;
1.790 albertel 52: use Math::Random;
1.807 albertel 53: use LONCAPA qw(:DEFAULT :match);
1.740 www 54: use LONCAPA::Configuration;
1.676 albertel 55:
1.195 www 56: my $readit;
1.550 foxr 57: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 58:
1.619 albertel 59: require Exporter;
60:
61: our @ISA = qw (Exporter);
62: our @EXPORT = qw(%env);
63:
1.449 matthew 64: =pod
65:
66: =head1 Package Variables
67:
68: These are largely undocumented, so if you decipher one please note it here.
69:
70: =over 4
71:
72: =item $processmarker
73:
74: Contains the time this process was started and this servers host id.
75:
76: =item $dumpcount
77:
78: Counts the number of times a message log flush has been attempted (regardless
79: of success) by this process. Used as part of the filename when messages are
80: delayed.
81:
82: =back
83:
84: =cut
85:
86:
1.1 albertel 87: # --------------------------------------------------------------------- Logging
1.729 www 88: {
89: my $logid;
90: sub instructor_log {
91: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
92: $logid++;
93: my $id=time().'00000'.$$.'00000'.$logid;
94: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 95: { $id => {
96: 'exe_uname' => $env{'user.name'},
97: 'exe_udom' => $env{'user.domain'},
98: 'exe_time' => time(),
99: 'exe_ip' => $ENV{'REMOTE_ADDR'},
100: 'delflag' => $delflag,
101: 'logentry' => $storehash,
102: 'uname' => $uname,
103: 'udom' => $udom,
104: }
105: },
1.729 www 106: $env{'course.'.$env{'request.course.id'}.'.domain'},
107: $env{'course.'.$env{'request.course.id'}.'.num'}
108: );
109: }
110: }
1.1 albertel 111:
1.163 harris41 112: sub logtouch {
113: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 114: unless (-e "$execdir/logs/lonnet.log") {
115: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 116: close $fh;
117: }
118: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
119: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
120: }
121:
1.1 albertel 122: sub logthis {
123: my $message=shift;
124: my $execdir=$perlvar{'lonDaemons'};
125: my $now=time;
126: my $local=localtime($now);
1.448 albertel 127: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
128: print $fh "$local ($$): $message\n";
129: close($fh);
130: }
1.1 albertel 131: return 1;
132: }
133:
134: sub logperm {
135: my $message=shift;
136: my $execdir=$perlvar{'lonDaemons'};
137: my $now=time;
138: my $local=localtime($now);
1.448 albertel 139: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
140: print $fh "$now:$message:$local\n";
141: close($fh);
142: }
1.1 albertel 143: return 1;
144: }
145:
1.850 albertel 146: sub create_connection {
1.853 albertel 147: my ($hostname,$lonid) = @_;
1.851 albertel 148: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 149: Type => SOCK_STREAM,
150: Timeout => 10);
151: return 0 if (!$client);
1.854 albertel 152: print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850 albertel 153: my $result = <$client>;
154: chomp($result);
155: return 1 if ($result eq 'done');
156: return 0;
157: }
158:
159:
1.1 albertel 160: # -------------------------------------------------- Non-critical communication
161: sub subreply {
162: my ($cmd,$server)=@_;
1.838 albertel 163: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 164: #
165: # With loncnew process trimming, there's a timing hole between lonc server
166: # process exit and the master server picking up the listen on the AF_UNIX
167: # socket. In that time interval, a lock file will exist:
168:
169: my $lockfile=$peerfile.".lock";
170: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
171: sleep(1);
172: }
173: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 174: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 175: #
1.550 foxr 176: # We'll give the connection a few tries before abandoning it. If
177: # connection is not possible, we'll con_lost back to the client.
178: #
179: my $client;
180: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
181: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
182: Type => SOCK_STREAM,
183: Timeout => 10);
1.869 albertel 184: if ($client) {
1.550 foxr 185: last; # Connected!
1.850 albertel 186: } else {
1.853 albertel 187: &create_connection(&hostname($server),$server);
1.550 foxr 188: }
1.850 albertel 189: sleep(1); # Try again later if failed connection.
1.550 foxr 190: }
191: my $answer;
192: if ($client) {
1.704 albertel 193: print $client "sethost:$server:$cmd\n";
1.550 foxr 194: $answer=<$client>;
195: if (!$answer) { $answer="con_lost"; }
196: chomp($answer);
197: } else {
198: $answer = 'con_lost'; # Failed connection.
199: }
1.1 albertel 200: return $answer;
201: }
202:
203: sub reply {
204: my ($cmd,$server)=@_;
1.838 albertel 205: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 206: my $answer=subreply($cmd,$server);
1.65 www 207: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 208: &logthis("<font color=\"blue\">WARNING:".
1.12 www 209: " $cmd to $server returned $answer</font>");
210: }
1.1 albertel 211: return $answer;
212: }
213:
214: # ----------------------------------------------------------- Send USR1 to lonc
215:
216: sub reconlonc {
1.836 www 217: &logthis("Trying to reconnect lonc");
1.1 albertel 218: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 219: if (open(my $fh,"<$loncfile")) {
1.1 albertel 220: my $loncpid=<$fh>;
221: chomp($loncpid);
222: if (kill 0 => $loncpid) {
223: &logthis("lonc at pid $loncpid responding, sending USR1");
224: kill USR1 => $loncpid;
225: sleep 1;
1.836 www 226: } else {
1.12 www 227: &logthis(
1.672 albertel 228: "<font color=\"blue\">WARNING:".
1.12 www 229: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 230: }
231: } else {
1.836 www 232: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 233: }
234: }
235:
236: # ------------------------------------------------------ Critical communication
1.12 www 237:
1.1 albertel 238: sub critical {
239: my ($cmd,$server)=@_;
1.838 albertel 240: unless (&hostname($server)) {
1.672 albertel 241: &logthis("<font color=\"blue\">WARNING:".
1.89 www 242: " Critical message to unknown server ($server)</font>");
243: return 'no_such_host';
244: }
1.1 albertel 245: my $answer=reply($cmd,$server);
246: if ($answer eq 'con_lost') {
247: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 248: my $answer=reply($cmd,$server);
1.1 albertel 249: if ($answer eq 'con_lost') {
250: my $now=time;
251: my $middlename=$cmd;
1.5 www 252: $middlename=substr($middlename,0,16);
1.1 albertel 253: $middlename=~s/\W//g;
254: my $dfilename=
1.305 www 255: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
256: $dumpcount++;
1.1 albertel 257: {
1.448 albertel 258: my $dfh;
259: if (open($dfh,">$dfilename")) {
260: print $dfh "$cmd\n";
261: close($dfh);
262: }
1.1 albertel 263: }
264: sleep 2;
265: my $wcmd='';
266: {
1.448 albertel 267: my $dfh;
268: if (open($dfh,"<$dfilename")) {
269: $wcmd=<$dfh>;
270: close($dfh);
271: }
1.1 albertel 272: }
273: chomp($wcmd);
1.7 www 274: if ($wcmd eq $cmd) {
1.672 albertel 275: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 276: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 277: &logperm("D:$server:$cmd");
278: return 'con_delayed';
279: } else {
1.672 albertel 280: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 281: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 282: &logperm("F:$server:$cmd");
283: return 'con_failed';
284: }
285: }
286: }
287: return $answer;
1.405 albertel 288: }
289:
1.755 albertel 290: # ------------------------------------------- check if return value is an error
291:
292: sub error {
293: my ($result) = @_;
1.756 albertel 294: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 295: if ($2 == 2) { return undef; }
296: return $1;
297: }
298: return undef;
299: }
300:
1.783 albertel 301: sub convert_and_load_session_env {
302: my ($lonidsdir,$handle)=@_;
303: my @profile;
304: {
305: open(my $idf,"$lonidsdir/$handle.id");
306: flock($idf,LOCK_SH);
307: @profile=<$idf>;
308: close($idf);
309: }
310: my %temp_env;
311: foreach my $line (@profile) {
1.786 albertel 312: if ($line !~ m/=/) {
313: return 0;
314: }
1.783 albertel 315: chomp($line);
316: my ($envname,$envvalue)=split(/=/,$line,2);
317: $temp_env{&unescape($envname)} = &unescape($envvalue);
318: }
319: unlink("$lonidsdir/$handle.id");
320: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
321: 0640)) {
322: %disk_env = %temp_env;
323: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
324: untie(%disk_env);
325: }
1.786 albertel 326: return 1;
1.783 albertel 327: }
328:
1.374 www 329: # ------------------------------------------- Transfer profile into environment
1.780 albertel 330: my $env_loaded;
331: sub transfer_profile_to_env {
1.788 albertel 332: my ($lonidsdir,$handle,$force_transfer) = @_;
333: if (!$force_transfer && $env_loaded) { return; }
1.374 www 334:
1.720 albertel 335: if (!defined($lonidsdir)) {
336: $lonidsdir = $perlvar{'lonIDsDir'};
337: }
338: if (!defined($handle)) {
339: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
340: }
341:
1.786 albertel 342: my $convert;
343: {
344: open(my $idf,"$lonidsdir/$handle.id");
345: flock($idf,LOCK_SH);
346: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
347: &GDBM_READER(),0640)) {
348: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
349: untie(%disk_env);
350: } else {
351: $convert = 1;
352: }
353: }
354: if ($convert) {
355: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
356: &logthis("Failed to load session, or convert session.");
357: }
1.374 www 358: }
1.783 albertel 359:
1.786 albertel 360: my %remove;
1.783 albertel 361: while ( my $envname = each(%env) ) {
1.433 matthew 362: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
363: if ($time < time-300) {
1.783 albertel 364: $remove{$key}++;
1.433 matthew 365: }
366: }
367: }
1.783 albertel 368:
1.619 albertel 369: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 370: $env_loaded=1;
1.783 albertel 371: foreach my $expired_key (keys(%remove)) {
1.433 matthew 372: &delenv($expired_key);
1.374 www 373: }
1.1 albertel 374: }
375:
1.830 albertel 376: sub timed_flock {
377: my ($file,$lock_type) = @_;
378: my $failed=0;
379: eval {
380: local $SIG{__DIE__}='DEFAULT';
381: local $SIG{ALRM}=sub {
382: $failed=1;
383: die("failed lock");
384: };
385: alarm(13);
386: flock($file,$lock_type);
387: alarm(0);
388: };
389: if ($failed) {
390: return undef;
391: } else {
392: return 1;
393: }
394: }
395:
1.5 www 396: # ---------------------------------------------------------- Append Environment
397:
398: sub appenv {
1.6 www 399: my %newenv=@_;
1.692 albertel 400: foreach my $key (keys(%newenv)) {
401: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 402: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 403: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 404: .'</font>');
1.692 albertel 405: delete($newenv{$key});
1.35 www 406: } else {
1.692 albertel 407: $env{$key}=$newenv{$key};
1.35 www 408: }
1.191 harris41 409: }
1.830 albertel 410: open(my $env_file,$env{'user.environment'});
411: if (&timed_flock($env_file,LOCK_EX)
412: &&
413: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
414: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 415: while (my ($key,$value) = each(%newenv)) {
416: $disk_env{$key} = $value;
1.448 albertel 417: }
1.783 albertel 418: untie(%disk_env);
1.56 www 419: }
420: return 'ok';
421: }
422: # ----------------------------------------------------- Delete from Environment
423:
424: sub delenv {
425: my $delthis=shift;
426: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 427: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 428: "Attempt to delete from environment ".$delthis);
429: return 'error';
430: }
1.830 albertel 431: open(my $env_file,$env{'user.environment'});
432: if (&timed_flock($env_file,LOCK_EX)
433: &&
434: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
435: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 436: foreach my $key (keys(%disk_env)) {
437: if ($key=~/^$delthis/) {
1.619 albertel 438: delete($env{$key});
1.783 albertel 439: delete($disk_env{$key});
1.473 matthew 440: }
1.448 albertel 441: }
1.783 albertel 442: untie(%disk_env);
1.5 www 443: }
444: return 'ok';
1.369 albertel 445: }
446:
1.790 albertel 447: sub get_env_multiple {
448: my ($name) = @_;
449: my @values;
450: if (defined($env{$name})) {
451: # exists is it an array
452: if (ref($env{$name})) {
453: @values=@{ $env{$name} };
454: } else {
455: $values[0]=$env{$name};
456: }
457: }
458: return(@values);
459: }
460:
1.369 albertel 461: # ------------------------------------------ Find out current server userload
462: # there is a copy in lond
463: sub userload {
464: my $numusers=0;
465: {
466: opendir(LONIDS,$perlvar{'lonIDsDir'});
467: my $filename;
468: my $curtime=time;
469: while ($filename=readdir(LONIDS)) {
470: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 471: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 472: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 473: }
474: closedir(LONIDS);
475: }
476: my $userloadpercent=0;
477: my $maxuserload=$perlvar{'lonUserLoadLim'};
478: if ($maxuserload) {
1.371 albertel 479: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 480: }
1.372 albertel 481: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 482: return $userloadpercent;
1.283 www 483: }
484:
485: # ------------------------------------------ Fight off request when overloaded
486:
487: sub overloaderror {
488: my ($r,$checkserver)=@_;
489: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
490: my $loadavg;
491: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 492: open(my $loadfile,'/proc/loadavg');
1.283 www 493: $loadavg=<$loadfile>;
494: $loadavg =~ s/\s.*//g;
1.285 matthew 495: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 496: close($loadfile);
1.283 www 497: } else {
498: $loadavg=&reply('load',$checkserver);
499: }
1.285 matthew 500: my $overload=$loadavg-100;
1.283 www 501: if ($overload>0) {
1.285 matthew 502: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 503: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 504: return 413;
1.283 www 505: }
506: return '';
1.5 www 507: }
1.1 albertel 508:
509: # ------------------------------ Find server with least workload from spare.tab
1.11 www 510:
1.1 albertel 511: sub spareserver {
1.670 albertel 512: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 513: my $spare_server;
1.370 albertel 514: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 515: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
516: : $userloadpercent;
517:
518: foreach my $try_server (@{ $spareid{'primary'} }) {
519: ($spare_server, $lowest_load) =
520: &compare_server_load($try_server, $spare_server, $lowest_load);
521: }
522:
523: my $found_server = ($spare_server ne '' && $lowest_load < 100);
524:
525: if (!$found_server) {
526: foreach my $try_server (@{ $spareid{'default'} }) {
527: ($spare_server, $lowest_load) =
528: &compare_server_load($try_server, $spare_server, $lowest_load);
529: }
530: }
531:
532: if (!$want_server_name) {
1.838 albertel 533: $spare_server="http://".&hostname($spare_server);
1.784 albertel 534: }
535: return $spare_server;
536: }
537:
538: sub compare_server_load {
539: my ($try_server, $spare_server, $lowest_load) = @_;
540:
541: my $loadans = &reply('load', $try_server);
542: my $userloadans = &reply('userload',$try_server);
543:
544: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
545: next; #didn't get a number from the server
546: }
547:
548: my $load;
549: if ($loadans =~ /\d/) {
550: if ($userloadans =~ /\d/) {
551: #both are numbers, pick the bigger one
552: $load = ($loadans > $userloadans) ? $loadans
553: : $userloadans;
1.411 albertel 554: } else {
1.784 albertel 555: $load = $loadans;
1.411 albertel 556: }
1.784 albertel 557: } else {
558: $load = $userloadans;
559: }
560:
561: if (($load =~ /\d/) && ($load < $lowest_load)) {
562: $spare_server = $try_server;
563: $lowest_load = $load;
1.370 albertel 564: }
1.784 albertel 565: return ($spare_server,$lowest_load);
1.202 matthew 566: }
567: # --------------------------------------------- Try to change a user's password
568:
569: sub changepass {
1.799 raeburn 570: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 571: $currentpass = &escape($currentpass);
572: $newpass = &escape($newpass);
1.799 raeburn 573: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 574: $server);
575: if (! $answer) {
576: &logthis("No reply on password change request to $server ".
577: "by $uname in domain $udom.");
578: } elsif ($answer =~ "^ok") {
579: &logthis("$uname in $udom successfully changed their password ".
580: "on $server.");
581: } elsif ($answer =~ "^pwchange_failure") {
582: &logthis("$uname in $udom was unable to change their password ".
583: "on $server. The action was blocked by either lcpasswd ".
584: "or pwchange");
585: } elsif ($answer =~ "^non_authorized") {
586: &logthis("$uname in $udom did not get their password correct when ".
587: "attempting to change it on $server.");
588: } elsif ($answer =~ "^auth_mode_error") {
589: &logthis("$uname in $udom attempted to change their password despite ".
590: "not being locally or internally authenticated on $server.");
591: } elsif ($answer =~ "^unknown_user") {
592: &logthis("$uname in $udom attempted to change their password ".
593: "on $server but were unable to because $server is not ".
594: "their home server.");
595: } elsif ($answer =~ "^refused") {
596: &logthis("$server refused to change $uname in $udom password because ".
597: "it was sent an unencrypted request to change the password.");
598: }
599: return $answer;
1.1 albertel 600: }
601:
1.169 harris41 602: # ----------------------- Try to determine user's current authentication scheme
603:
604: sub queryauthenticate {
605: my ($uname,$udom)=@_;
1.456 albertel 606: my $uhome=&homeserver($uname,$udom);
607: if (!$uhome) {
608: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
609: return 'no_host';
610: }
611: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
612: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
613: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 614: }
1.456 albertel 615: return $answer;
1.169 harris41 616: }
617:
1.1 albertel 618: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 619:
1.1 albertel 620: sub authenticate {
621: my ($uname,$upass,$udom)=@_;
1.807 albertel 622: $upass=&escape($upass);
623: $uname= &LONCAPA::clean_username($uname);
1.836 www 624: my $uhome=&homeserver($uname,$udom,1);
625: if ((!$uhome) || ($uhome eq 'no_host')) {
626: # Maybe the machine was offline and only re-appeared again recently?
627: &reconlonc();
628: # One more
629: my $uhome=&homeserver($uname,$udom,1);
630: if ((!$uhome) || ($uhome eq 'no_host')) {
631: &logthis("User $uname at $udom is unknown in authenticate");
632: }
1.471 albertel 633: return 'no_host';
1.1 albertel 634: }
1.471 albertel 635: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
636: if ($answer eq 'authorized') {
637: &logthis("User $uname at $udom authorized by $uhome");
638: return $uhome;
639: }
640: if ($answer eq 'non_authorized') {
641: &logthis("User $uname at $udom rejected by $uhome");
642: return 'no_host';
1.9 www 643: }
1.471 albertel 644: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 645: return 'no_host';
646: }
647:
648: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 649:
1.599 albertel 650: my %homecache;
1.1 albertel 651: sub homeserver {
1.230 stredwic 652: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 653: my $index="$uname:$udom";
1.426 albertel 654:
1.599 albertel 655: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 656:
657: my %servers = &get_servers($udom,'library');
658: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 659: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 660: exists($badServerCache{$tryserver}));
1.841 albertel 661:
662: my $answer=reply("home:$udom:$uname",$tryserver);
663: if ($answer eq 'found') {
664: delete($badServerCache{$tryserver});
665: return $homecache{$index}=$tryserver;
666: } elsif ($answer eq 'no_host') {
667: $badServerCache{$tryserver}=1;
668: }
1.1 albertel 669: }
670: return 'no_host';
1.70 www 671: }
672:
673: # ------------------------------------- Find the usernames behind a list of IDs
674:
675: sub idget {
676: my ($udom,@ids)=@_;
677: my %returnhash=();
678:
1.841 albertel 679: my %servers = &get_servers($udom,'library');
680: foreach my $tryserver (keys(%servers)) {
681: my $idlist=join('&',@ids);
682: $idlist=~tr/A-Z/a-z/;
683: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
684: my @answer=();
685: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
686: @answer=split(/\&/,$reply);
687: } ;
688: my $i;
689: for ($i=0;$i<=$#ids;$i++) {
690: if ($answer[$i]) {
691: $returnhash{$ids[$i]}=$answer[$i];
692: }
693: }
694: }
1.70 www 695: return %returnhash;
696: }
697:
698: # ------------------------------------- Find the IDs behind a list of usernames
699:
700: sub idrget {
701: my ($udom,@unames)=@_;
702: my %returnhash=();
1.800 albertel 703: foreach my $uname (@unames) {
704: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 705: }
1.70 www 706: return %returnhash;
707: }
708:
709: # ------------------------------- Store away a list of names and associated IDs
710:
711: sub idput {
712: my ($udom,%ids)=@_;
713: my %servers=();
1.800 albertel 714: foreach my $uname (keys(%ids)) {
715: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
716: my $uhom=&homeserver($uname,$udom);
1.70 www 717: if ($uhom ne 'no_host') {
1.800 albertel 718: my $id=&escape($ids{$uname});
1.70 www 719: $id=~tr/A-Z/a-z/;
1.800 albertel 720: my $esc_unam=&escape($uname);
1.70 www 721: if ($servers{$uhom}) {
1.800 albertel 722: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 723: } else {
1.800 albertel 724: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 725: }
726: }
1.191 harris41 727: }
1.800 albertel 728: foreach my $server (keys(%servers)) {
729: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 730: }
1.344 www 731: }
732:
1.806 raeburn 733: # ------------------------------------------- get items from domain db files
734:
735: sub get_dom {
1.860 raeburn 736: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 737: my $items='';
738: foreach my $item (@$storearr) {
739: $items.=&escape($item).'&';
740: }
741: $items=~s/\&$//;
1.860 raeburn 742: if (!$udom) {
743: $udom=$env{'user.domain'};
744: if (defined(&domain($udom,'primary'))) {
745: $uhome=&domain($udom,'primary');
746: } else {
747: $uhome eq '';
748: }
749: } else {
750: if (!$uhome) {
751: if (defined(&domain($udom,'primary'))) {
752: $uhome=&domain($udom,'primary');
753: }
754: }
755: }
756: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 757: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 758: my %returnhash;
759: if ($rep =~ /^error: 2 /) {
760: return %returnhash;
761: }
1.806 raeburn 762: my @pairs=split(/\&/,$rep);
763: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
764: return @pairs;
765: }
766: my %returnhash=();
767: my $i=0;
768: foreach my $item (@$storearr) {
769: $returnhash{$item}=&thaw_unescape($pairs[$i]);
770: $i++;
771: }
772: return %returnhash;
773: } else {
1.860 raeburn 774: &logthis("get_dom failed - no homeserver and/or domain");
1.806 raeburn 775: }
776: }
777:
778: # -------------------------------------------- put items in domain db files
779:
780: sub put_dom {
1.860 raeburn 781: my ($namespace,$storehash,$udom,$uhome)=@_;
782: if (!$udom) {
783: $udom=$env{'user.domain'};
784: if (defined(&domain($udom,'primary'))) {
785: $uhome=&domain($udom,'primary');
786: } else {
787: $uhome eq '';
788: }
789: } else {
790: if (!$uhome) {
791: if (defined(&domain($udom,'primary'))) {
792: $uhome=&domain($udom,'primary');
793: }
794: }
795: }
796: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 797: my $items='';
798: foreach my $item (keys(%$storehash)) {
799: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
800: }
801: $items=~s/\&$//;
802: return &reply("putdom:$udom:$namespace:$items",$uhome);
803: } else {
1.860 raeburn 804: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 805: }
806: }
807:
1.837 raeburn 808: sub retrieve_inst_usertypes {
809: my ($udom) = @_;
810: my (%returnhash,@order);
1.846 albertel 811: if (defined(&domain($udom,'primary'))) {
812: my $uhome=&domain($udom,'primary');
1.837 raeburn 813: my $rep=&reply("inst_usertypes:$udom",$uhome);
814: my ($hashitems,$orderitems) = split(/:/,$rep);
815: my @pairs=split(/\&/,$hashitems);
816: foreach my $item (@pairs) {
817: my ($key,$value)=split(/=/,$item,2);
818: $key = &unescape($key);
819: next if ($key =~ /^error: 2 /);
820: $returnhash{$key}=&thaw_unescape($value);
821: }
822: my @esc_order = split(/\&/,$orderitems);
823: foreach my $item (@esc_order) {
824: push(@order,&unescape($item));
825: }
826: } else {
827: &logthis("get_dom failed - no primary domain server for $udom");
828: }
829: return (\%returnhash,\@order);
830: }
831:
1.868 raeburn 832: sub is_domainimage {
833: my ($url) = @_;
834: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
835: if (&domain($1) ne '') {
836: return '1';
837: }
838: }
839: return;
840: }
841:
1.344 www 842: # --------------------------------------------------- Assign a key to a student
843:
844: sub assign_access_key {
1.364 www 845: #
846: # a valid key looks like uname:udom#comments
847: # comments are being appended
848: #
1.498 www 849: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
850: $kdom=
1.620 albertel 851: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 852: $knum=
1.620 albertel 853: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 854: $cdom=
1.620 albertel 855: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 856: $cnum=
1.620 albertel 857: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
858: $udom=$env{'user.name'} unless (defined($udom));
859: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 860: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 861: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 862: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 863: # assigned to this person
864: # - this should not happen,
1.345 www 865: # unless something went wrong
866: # the first time around
867: # ready to assign
1.364 www 868: $logentry=$1.'; '.$logentry;
1.496 www 869: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 870: $kdom,$knum) eq 'ok') {
1.345 www 871: # key now belongs to user
1.346 www 872: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 873: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
874: &appenv('environment.'.$envkey => $ckey);
875: return 'ok';
876: } else {
877: return
878: 'error: Count not permanently assign key, will need to be re-entered later.';
879: }
880: } else {
881: return 'error: Could not assign key, try again later.';
882: }
1.364 www 883: } elsif (!$existing{$ckey}) {
1.345 www 884: # the key does not exist
885: return 'error: The key does not exist';
886: } else {
887: # the key is somebody else's
888: return 'error: The key is already in use';
889: }
1.344 www 890: }
891:
1.364 www 892: # ------------------------------------------ put an additional comment on a key
893:
894: sub comment_access_key {
895: #
896: # a valid key looks like uname:udom#comments
897: # comments are being appended
898: #
899: my ($ckey,$cdom,$cnum,$logentry)=@_;
900: $cdom=
1.620 albertel 901: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 902: $cnum=
1.620 albertel 903: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 904: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
905: if ($existing{$ckey}) {
906: $existing{$ckey}.='; '.$logentry;
907: # ready to assign
1.367 www 908: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 909: $cdom,$cnum) eq 'ok') {
910: return 'ok';
911: } else {
912: return 'error: Count not store comment.';
913: }
914: } else {
915: # the key does not exist
916: return 'error: The key does not exist';
917: }
918: }
919:
1.344 www 920: # ------------------------------------------------------ Generate a set of keys
921:
922: sub generate_access_keys {
1.364 www 923: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 924: $cdom=
1.620 albertel 925: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 926: $cnum=
1.620 albertel 927: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 928: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 929: unless (($cdom) && ($cnum)) { return 0; }
930: if ($number>10000) { return 0; }
931: sleep(2); # make sure don't get same seed twice
932: srand(time()^($$+($$<<15))); # from "Programming Perl"
933: my $total=0;
934: for (my $i=1;$i<=$number;$i++) {
935: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
936: sprintf("%lx",int(100000*rand)).'-'.
937: sprintf("%lx",int(100000*rand));
938: $newkey=~s/1/g/g; # folks mix up 1 and l
939: $newkey=~s/0/h/g; # and also 0 and O
940: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
941: if ($existing{$newkey}) {
942: $i--;
943: } else {
1.364 www 944: if (&put('accesskeys',
945: { $newkey => '# generated '.localtime().
1.620 albertel 946: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 947: '; '.$logentry },
948: $cdom,$cnum) eq 'ok') {
1.344 www 949: $total++;
950: }
951: }
952: }
1.620 albertel 953: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 954: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
955: return $total;
956: }
957:
958: # ------------------------------------------------------- Validate an accesskey
959:
960: sub validate_access_key {
961: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
962: $cdom=
1.620 albertel 963: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 964: $cnum=
1.620 albertel 965: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
966: $udom=$env{'user.domain'} unless (defined($udom));
967: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 968: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 969: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 970: }
971:
972: # ------------------------------------- Find the section of student in a course
1.652 albertel 973: sub devalidate_getsection_cache {
974: my ($udom,$unam,$courseid)=@_;
975: my $hashid="$udom:$unam:$courseid";
976: &devalidate_cache_new('getsection',$hashid);
977: }
1.298 matthew 978:
1.815 albertel 979: sub courseid_to_courseurl {
980: my ($courseid) = @_;
981: #already url style courseid
982: return $courseid if ($courseid =~ m{^/});
983:
984: if (exists($env{'course.'.$courseid.'.num'})) {
985: my $cnum = $env{'course.'.$courseid.'.num'};
986: my $cdom = $env{'course.'.$courseid.'.domain'};
987: return "/$cdom/$cnum";
988: }
989:
990: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
991: if (exists($courseinfo{'num'})) {
992: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
993: }
994:
995: return undef;
996: }
997:
1.298 matthew 998: sub getsection {
999: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1000: my $cachetime=1800;
1.551 albertel 1001:
1002: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1003: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1004: if (defined($cached)) { return $result; }
1005:
1.298 matthew 1006: my %Pending;
1007: my %Expired;
1008: #
1009: # Each role can either have not started yet (pending), be active,
1010: # or have expired.
1011: #
1012: # If there is an active role, we are done.
1013: #
1014: # If there is more than one role which has not started yet,
1015: # choose the one which will start sooner
1016: # If there is one role which has not started yet, return it.
1017: #
1018: # If there is more than one expired role, choose the one which ended last.
1019: # If there is a role which has expired, return it.
1020: #
1.815 albertel 1021: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1022: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1023: foreach my $key (keys(%roleshash)) {
1.479 albertel 1024: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1025: my $section=$1;
1026: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1027: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1028: my $now=time;
1.548 albertel 1029: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1030: $Expired{$end}=$section;
1031: next;
1032: }
1.548 albertel 1033: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1034: $Pending{$start}=$section;
1035: next;
1036: }
1.599 albertel 1037: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1038: }
1039: #
1040: # Presumedly there will be few matching roles from the above
1041: # loop and the sorting time will be negligible.
1042: if (scalar(keys(%Pending))) {
1043: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1044: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1045: }
1046: if (scalar(keys(%Expired))) {
1047: my @sorted = sort {$a <=> $b} keys(%Expired);
1048: my $time = pop(@sorted);
1.599 albertel 1049: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1050: }
1.599 albertel 1051: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1052: }
1.70 www 1053:
1.599 albertel 1054: sub save_cache {
1055: &purge_remembered();
1.722 albertel 1056: #&Apache::loncommon::validate_page();
1.620 albertel 1057: undef(%env);
1.780 albertel 1058: undef($env_loaded);
1.599 albertel 1059: }
1.452 albertel 1060:
1.599 albertel 1061: my $to_remember=-1;
1062: my %remembered;
1063: my %accessed;
1064: my $kicks=0;
1065: my $hits=0;
1.849 albertel 1066: sub make_key {
1067: my ($name,$id) = @_;
1068: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1069: return &escape($name.':'.$id);
1070: }
1071:
1.599 albertel 1072: sub devalidate_cache_new {
1073: my ($name,$id,$debug) = @_;
1074: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1075: $id=&make_key($name,$id);
1.599 albertel 1076: $memcache->delete($id);
1077: delete($remembered{$id});
1078: delete($accessed{$id});
1079: }
1080:
1081: sub is_cached_new {
1082: my ($name,$id,$debug) = @_;
1.849 albertel 1083: $id=&make_key($name,$id);
1.599 albertel 1084: if (exists($remembered{$id})) {
1085: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1086: $accessed{$id}=[&gettimeofday()];
1087: $hits++;
1088: return ($remembered{$id},1);
1089: }
1090: my $value = $memcache->get($id);
1091: if (!(defined($value))) {
1092: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1093: return (undef,undef);
1.416 albertel 1094: }
1.599 albertel 1095: if ($value eq '__undef__') {
1096: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1097: $value=undef;
1098: }
1099: &make_room($id,$value,$debug);
1100: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1101: return ($value,1);
1102: }
1103:
1104: sub do_cache_new {
1105: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1106: $id=&make_key($name,$id);
1.599 albertel 1107: my $setvalue=$value;
1108: if (!defined($setvalue)) {
1109: $setvalue='__undef__';
1110: }
1.623 albertel 1111: if (!defined($time) ) {
1112: $time=600;
1113: }
1.599 albertel 1114: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 1115: $memcache->set($id,$setvalue,$time);
1116: # need to make a copy of $value
1117: #&make_room($id,$value,$debug);
1.599 albertel 1118: return $value;
1119: }
1120:
1121: sub make_room {
1122: my ($id,$value,$debug)=@_;
1123: $remembered{$id}=$value;
1124: if ($to_remember<0) { return; }
1125: $accessed{$id}=[&gettimeofday()];
1126: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1127: my $to_kick;
1128: my $max_time=0;
1129: foreach my $other (keys(%accessed)) {
1130: if (&tv_interval($accessed{$other}) > $max_time) {
1131: $to_kick=$other;
1132: $max_time=&tv_interval($accessed{$other});
1133: }
1134: }
1135: delete($remembered{$to_kick});
1136: delete($accessed{$to_kick});
1137: $kicks++;
1138: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1139: return;
1140: }
1141:
1.599 albertel 1142: sub purge_remembered {
1.604 albertel 1143: #&logthis("Tossing ".scalar(keys(%remembered)));
1144: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1145: undef(%remembered);
1146: undef(%accessed);
1.428 albertel 1147: }
1.70 www 1148: # ------------------------------------- Read an entry from a user's environment
1149:
1150: sub userenvironment {
1151: my ($udom,$unam,@what)=@_;
1152: my %returnhash=();
1153: my @answer=split(/\&/,
1154: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1155: &homeserver($unam,$udom)));
1156: my $i;
1157: for ($i=0;$i<=$#what;$i++) {
1158: $returnhash{$what[$i]}=&unescape($answer[$i]);
1159: }
1160: return %returnhash;
1.1 albertel 1161: }
1162:
1.617 albertel 1163: # ---------------------------------------------------------- Get a studentphoto
1164: sub studentphoto {
1165: my ($udom,$unam,$ext) = @_;
1166: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1167: if (defined($env{'request.course.id'})) {
1.708 raeburn 1168: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1169: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1170: return(&retrievestudentphoto($udom,$unam,$ext));
1171: } else {
1172: my ($result,$perm_reqd)=
1.707 albertel 1173: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1174: if ($result eq 'ok') {
1175: if (!($perm_reqd eq 'yes')) {
1176: return(&retrievestudentphoto($udom,$unam,$ext));
1177: }
1178: }
1179: }
1180: }
1181: } else {
1182: my ($result,$perm_reqd) =
1.707 albertel 1183: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1184: if ($result eq 'ok') {
1185: if (!($perm_reqd eq 'yes')) {
1186: return(&retrievestudentphoto($udom,$unam,$ext));
1187: }
1188: }
1189: }
1190: return '/adm/lonKaputt/lonlogo_broken.gif';
1191: }
1192:
1193: sub retrievestudentphoto {
1194: my ($udom,$unam,$ext,$type) = @_;
1195: my $home=&Apache::lonnet::homeserver($unam,$udom);
1196: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1197: if ($ret eq 'ok') {
1198: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1199: if ($type eq 'thumbnail') {
1200: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1201: }
1202: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1203: return $tokenurl;
1204: } else {
1205: if ($type eq 'thumbnail') {
1206: return '/adm/lonKaputt/genericstudent_tn.gif';
1207: } else {
1208: return '/adm/lonKaputt/lonlogo_broken.gif';
1209: }
1.617 albertel 1210: }
1211: }
1212:
1.263 www 1213: # -------------------------------------------------------------------- New chat
1214:
1215: sub chatsend {
1.724 raeburn 1216: my ($newentry,$anon,$group)=@_;
1.620 albertel 1217: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1218: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1219: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1220: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1221: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1222: &escape($newentry)).':'.$group,$chome);
1.292 www 1223: }
1224:
1225: # ------------------------------------------ Find current version of a resource
1226:
1227: sub getversion {
1228: my $fname=&clutter(shift);
1229: unless ($fname=~/^\/res\//) { return -1; }
1230: return ¤tversion(&filelocation('',$fname));
1231: }
1232:
1233: sub currentversion {
1234: my $fname=shift;
1.599 albertel 1235: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1236: if (defined($cached)) { return $result; }
1.292 www 1237: my $author=$fname;
1238: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1239: my ($udom,$uname)=split(/\//,$author);
1240: my $home=homeserver($uname,$udom);
1241: if ($home eq 'no_host') {
1242: return -1;
1243: }
1244: my $answer=reply("currentversion:$fname",$home);
1245: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1246: return -1;
1247: }
1.599 albertel 1248: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1249: }
1250:
1.1 albertel 1251: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1252:
1.1 albertel 1253: sub subscribe {
1254: my $fname=shift;
1.761 raeburn 1255: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1256: $fname=~s/[\n\r]//g;
1.1 albertel 1257: my $author=$fname;
1258: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1259: my ($udom,$uname)=split(/\//,$author);
1260: my $home=homeserver($uname,$udom);
1.335 albertel 1261: if ($home eq 'no_host') {
1262: return 'not_found';
1.1 albertel 1263: }
1264: my $answer=reply("sub:$fname",$home);
1.64 www 1265: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1266: $answer.=' by '.$home;
1267: }
1.1 albertel 1268: return $answer;
1269: }
1270:
1.8 www 1271: # -------------------------------------------------------------- Replicate file
1272:
1273: sub repcopy {
1274: my $filename=shift;
1.23 www 1275: $filename=~s/\/+/\//g;
1.607 raeburn 1276: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1277: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1278: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1279: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1280: return &repcopy_userfile($filename);
1281: }
1.532 albertel 1282: $filename=~s/[\n\r]//g;
1.8 www 1283: my $transname="$filename.in.transfer";
1.828 www 1284: # FIXME: this should flock
1.607 raeburn 1285: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1286: my $remoteurl=subscribe($filename);
1.64 www 1287: if ($remoteurl =~ /^con_lost by/) {
1288: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1289: return 'unavailable';
1.8 www 1290: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1291: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1292: return 'not_found';
1.64 www 1293: } elsif ($remoteurl =~ /^rejected by/) {
1294: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1295: return 'forbidden';
1.20 www 1296: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1297: return 'ok';
1.8 www 1298: } else {
1.290 www 1299: my $author=$filename;
1300: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1301: my ($udom,$uname)=split(/\//,$author);
1302: my $home=homeserver($uname,$udom);
1303: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1304: my @parts=split(/\//,$filename);
1305: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1306: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1307: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1308: return 'bad_request';
1.8 www 1309: }
1310: my $count;
1311: for ($count=5;$count<$#parts;$count++) {
1312: $path.="/$parts[$count]";
1313: if ((-e $path)!=1) {
1314: mkdir($path,0777);
1315: }
1316: }
1317: my $ua=new LWP::UserAgent;
1318: my $request=new HTTP::Request('GET',"$remoteurl");
1319: my $response=$ua->request($request,$transname);
1320: if ($response->is_error()) {
1321: unlink($transname);
1322: my $message=$response->status_line;
1.672 albertel 1323: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1324: ." LWP get: $message: $filename</font>");
1.607 raeburn 1325: return 'unavailable';
1.8 www 1326: } else {
1.16 www 1327: if ($remoteurl!~/\.meta$/) {
1328: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1329: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1330: if ($mresponse->is_error()) {
1331: unlink($filename.'.meta');
1332: &logthis(
1.672 albertel 1333: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1334: }
1335: }
1.8 www 1336: rename($transname,$filename);
1.607 raeburn 1337: return 'ok';
1.8 www 1338: }
1.290 www 1339: }
1.8 www 1340: }
1.330 www 1341: }
1342:
1343: # ------------------------------------------------ Get server side include body
1344: sub ssi_body {
1.381 albertel 1345: my ($filelink,%form)=@_;
1.606 matthew 1346: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1347: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1348: }
1.330 www 1349: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1350: &ssi($filelink,%form));
1.778 albertel 1351: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1352: $output=~s/^.*?\<body[^\>]*\>//si;
1353: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1354: return $output;
1.8 www 1355: }
1356:
1.15 www 1357: # --------------------------------------------------------- Server Side Include
1358:
1.782 albertel 1359: sub absolute_url {
1360: my ($host_name) = @_;
1361: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1362: if ($host_name eq '') {
1363: $host_name = $ENV{'SERVER_NAME'};
1364: }
1365: return $protocol.$host_name;
1366: }
1367:
1.15 www 1368: sub ssi {
1369:
1.23 www 1370: my ($fn,%form)=@_;
1.15 www 1371:
1372: my $ua=new LWP::UserAgent;
1.23 www 1373:
1374: my $request;
1.711 albertel 1375:
1376: $form{'no_update_last_known'}=1;
1377:
1.23 www 1378: if (%form) {
1.782 albertel 1379: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1380: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1381: } else {
1.782 albertel 1382: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1383: }
1384:
1.15 www 1385: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1386: my $response=$ua->request($request);
1387:
1.324 www 1388: return $response->content;
1389: }
1390:
1391: sub externalssi {
1392: my ($url)=@_;
1393: my $ua=new LWP::UserAgent;
1394: my $request=new HTTP::Request('GET',$url);
1395: my $response=$ua->request($request);
1.15 www 1396: return $response->content;
1397: }
1.254 www 1398:
1.492 albertel 1399: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1400:
1401: sub allowuploaded {
1402: my ($srcurl,$url)=@_;
1403: $url=&clutter(&declutter($url));
1404: my $dir=$url;
1405: $dir=~s/\/[^\/]+$//;
1406: my %httpref=();
1407: my $httpurl=&hreflocation('',$url);
1408: $httpref{'httpref.'.$httpurl}=$srcurl;
1409: &Apache::lonnet::appenv(%httpref);
1.254 www 1410: }
1.477 raeburn 1411:
1.478 albertel 1412: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1413: # input: action, courseID, current domain, intended
1.637 raeburn 1414: # path to file, source of file, instruction to parse file for objects,
1415: # ref to hash for embedded objects,
1416: # ref to hash for codebase of java objects.
1417: #
1.485 raeburn 1418: # output: url to file (if action was uploaddoc),
1419: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1420: #
1.478 albertel 1421: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1422: # course.
1.477 raeburn 1423: #
1.478 albertel 1424: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1425: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1426: # course's home server.
1.477 raeburn 1427: #
1.478 albertel 1428: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1429: # be copied from $source (current location) to
1430: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1431: # and will then be copied to
1432: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1433: # course's home server.
1.485 raeburn 1434: #
1.481 raeburn 1435: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1436: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1437: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1438: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1439: # in course's home server.
1.637 raeburn 1440: #
1.477 raeburn 1441:
1442: sub process_coursefile {
1.638 albertel 1443: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1444: my $fetchresult;
1.638 albertel 1445: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1446: if ($action eq 'propagate') {
1.638 albertel 1447: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1448: $home);
1.481 raeburn 1449: } else {
1.477 raeburn 1450: my $fpath = '';
1451: my $fname = $file;
1.478 albertel 1452: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1453: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1454: my $filepath = &build_filepath($fpath);
1.481 raeburn 1455: if ($action eq 'copy') {
1456: if ($source eq '') {
1457: $fetchresult = 'no source file';
1458: return $fetchresult;
1459: } else {
1460: my $destination = $filepath.'/'.$fname;
1461: rename($source,$destination);
1462: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1463: $home);
1.481 raeburn 1464: }
1465: } elsif ($action eq 'uploaddoc') {
1466: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1467: print $fh $env{'form.'.$source};
1.481 raeburn 1468: close($fh);
1.637 raeburn 1469: if ($parser eq 'parse') {
1470: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1471: unless ($parse_result eq 'ok') {
1472: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1473: }
1474: }
1.477 raeburn 1475: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1476: $home);
1.481 raeburn 1477: if ($fetchresult eq 'ok') {
1478: return '/uploaded/'.$fpath.'/'.$fname;
1479: } else {
1480: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1481: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1482: return '/adm/notfound.html';
1483: }
1.477 raeburn 1484: }
1485: }
1.485 raeburn 1486: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1487: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1488: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1489: }
1490: return $fetchresult;
1491: }
1492:
1.637 raeburn 1493: sub build_filepath {
1494: my ($fpath) = @_;
1495: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1496: unless ($fpath eq '') {
1497: my @parts=split('/',$fpath);
1498: foreach my $part (@parts) {
1499: $filepath.= '/'.$part;
1500: if ((-e $filepath)!=1) {
1501: mkdir($filepath,0777);
1502: }
1503: }
1504: }
1505: return $filepath;
1506: }
1507:
1508: sub store_edited_file {
1.638 albertel 1509: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1510: my $file = $primary_url;
1511: $file =~ s#^/uploaded/$docudom/$docuname/##;
1512: my $fpath = '';
1513: my $fname = $file;
1514: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1515: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1516: my $filepath = &build_filepath($fpath);
1517: open(my $fh,'>'.$filepath.'/'.$fname);
1518: print $fh $content;
1519: close($fh);
1.638 albertel 1520: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1521: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1522: $home);
1.637 raeburn 1523: if ($$fetchresult eq 'ok') {
1524: return '/uploaded/'.$fpath.'/'.$fname;
1525: } else {
1.638 albertel 1526: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1527: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1528: return '/adm/notfound.html';
1529: }
1530: }
1531:
1.531 albertel 1532: sub clean_filename {
1.831 albertel 1533: my ($fname,$args)=@_;
1.315 www 1534: # Replace Windows backslashes by forward slashes
1.257 www 1535: $fname=~s/\\/\//g;
1.831 albertel 1536: if (!$args->{'keep_path'}) {
1537: # Get rid of everything but the actual filename
1538: $fname=~s/^.*\/([^\/]+)$/$1/;
1539: }
1.315 www 1540: # Replace spaces by underscores
1541: $fname=~s/\s+/\_/g;
1542: # Replace all other weird characters by nothing
1.831 albertel 1543: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1544: # Replace all .\d. sequences with _\d. so they no longer look like version
1545: # numbers
1546: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1547: return $fname;
1548: }
1549:
1.608 albertel 1550: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1551: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1552: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1553: # $coursedoc - if true up to the current course
1554: # if false
1555: # $subdir - directory in userfile to store the file into
1.858 raeburn 1556: # $parser - instruction to parse file for objects ($parser = parse)
1557: # $allfiles - reference to hash for embedded objects
1558: # $codebase - reference to hash for codebase of java objects
1559: # $desuname - username for permanent storage of uploaded file
1560: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1561: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1562: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1563: #
1.686 albertel 1564: # output: url of file in userspace, or error: <message>
1565: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1566:
1567:
1.531 albertel 1568: sub userfileupload {
1.860 raeburn 1569: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1570: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1571: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1572: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1573: $fname=&clean_filename($fname);
1.315 www 1574: # See if there is anything left
1.257 www 1575: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1576: chop($env{'form.'.$formname});
1.523 raeburn 1577: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1578: my $now = time;
1579: my $filepath = 'tmp/helprequests/'.$now;
1580: my @parts=split(/\//,$filepath);
1581: my $fullpath = $perlvar{'lonDaemons'};
1582: for (my $i=0;$i<@parts;$i++) {
1583: $fullpath .= '/'.$parts[$i];
1584: if ((-e $fullpath)!=1) {
1585: mkdir($fullpath,0777);
1586: }
1587: }
1588: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1589: print $fh $env{'form.'.$formname};
1.523 raeburn 1590: close($fh);
1.741 raeburn 1591: return $fullpath.'/'.$fname;
1592: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1593: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1594: '_'.$env{'user.domain'}.'/pending';
1595: my @parts=split(/\//,$filepath);
1596: my $fullpath = $perlvar{'lonDaemons'};
1597: for (my $i=0;$i<@parts;$i++) {
1598: $fullpath .= '/'.$parts[$i];
1599: if ((-e $fullpath)!=1) {
1600: mkdir($fullpath,0777);
1601: }
1602: }
1603: open(my $fh,'>'.$fullpath.'/'.$fname);
1604: print $fh $env{'form.'.$formname};
1605: close($fh);
1606: return $fullpath.'/'.$fname;
1.523 raeburn 1607: }
1.719 banghart 1608:
1.258 www 1609: # Create the directory if not present
1.493 albertel 1610: $fname="$subdir/$fname";
1.259 www 1611: if ($coursedoc) {
1.638 albertel 1612: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1613: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1614: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1615: return &finishuserfileupload($docuname,$docudom,
1616: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1617: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1618: } else {
1.620 albertel 1619: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1620: return &process_coursefile('uploaddoc',$docuname,$docudom,
1621: $fname,$formname,$parser,
1622: $allfiles,$codebase);
1.481 raeburn 1623: }
1.719 banghart 1624: } elsif (defined($destuname)) {
1625: my $docuname=$destuname;
1626: my $docudom=$destudom;
1.860 raeburn 1627: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1628: $parser,$allfiles,$codebase,
1629: $thumbwidth,$thumbheight);
1.719 banghart 1630:
1.259 www 1631: } else {
1.638 albertel 1632: my $docuname=$env{'user.name'};
1633: my $docudom=$env{'user.domain'};
1.714 raeburn 1634: if (exists($env{'form.group'})) {
1635: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1636: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1637: }
1.860 raeburn 1638: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1639: $parser,$allfiles,$codebase,
1640: $thumbwidth,$thumbheight);
1.259 www 1641: }
1.271 www 1642: }
1643:
1644: sub finishuserfileupload {
1.860 raeburn 1645: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1646: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1647: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1648: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1649: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1650: $file=$fname;
1651: if ($fname=~m|/|) {
1652: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1653: $path.=$fnamepath.'/';
1654: }
1.259 www 1655: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1656: my $count;
1657: for ($count=4;$count<=$#parts;$count++) {
1658: $filepath.="/$parts[$count]";
1659: if ((-e $filepath)!=1) {
1660: mkdir($filepath,0777);
1661: }
1662: }
1663: # Save the file
1664: {
1.701 albertel 1665: if (!open(FH,'>'.$filepath.'/'.$file)) {
1666: &logthis('Failed to create '.$filepath.'/'.$file);
1667: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1668: return '/adm/notfound.html';
1669: }
1670: if (!print FH ($env{'form.'.$formname})) {
1671: &logthis('Failed to write to '.$filepath.'/'.$file);
1672: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1673: return '/adm/notfound.html';
1674: }
1.570 albertel 1675: close(FH);
1.258 www 1676: }
1.637 raeburn 1677: if ($parser eq 'parse') {
1.638 albertel 1678: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1679: $codebase);
1.637 raeburn 1680: unless ($parse_result eq 'ok') {
1.638 albertel 1681: &logthis('Failed to parse '.$filepath.$file.
1682: ' for embedded media: '.$parse_result);
1.637 raeburn 1683: }
1684: }
1.860 raeburn 1685: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1686: my $input = $filepath.'/'.$file;
1687: my $output = $filepath.'/'.'tn-'.$file;
1688: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1689: system("convert -sample $thumbsize $input $output");
1690: if (-e $filepath.'/'.'tn-'.$file) {
1691: $fetchthumb = 1;
1692: }
1693: }
1.858 raeburn 1694:
1.259 www 1695: # Notify homeserver to grep it
1696: #
1.638 albertel 1697: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1698: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1699: if ($fetchresult eq 'ok') {
1.860 raeburn 1700: if ($fetchthumb) {
1701: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1702: if ($thumbresult ne 'ok') {
1703: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1704: $docuhome.': '.$thumbresult);
1705: }
1706: }
1.259 www 1707: #
1.258 www 1708: # Return the URL to it
1.494 albertel 1709: return '/uploaded/'.$path.$file;
1.263 www 1710: } else {
1.494 albertel 1711: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1712: ': '.$fetchresult);
1.263 www 1713: return '/adm/notfound.html';
1.858 raeburn 1714: }
1.493 albertel 1715: }
1716:
1.637 raeburn 1717: sub extract_embedded_items {
1.648 raeburn 1718: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1719: my @state = ();
1720: my %javafiles = (
1721: codebase => '',
1722: code => '',
1723: archive => ''
1724: );
1725: my %mediafiles = (
1726: src => '',
1727: movie => '',
1728: );
1.648 raeburn 1729: my $p;
1730: if ($content) {
1731: $p = HTML::LCParser->new($content);
1732: } else {
1733: $p = HTML::LCParser->new($filepath.'/'.$file);
1734: }
1.641 albertel 1735: while (my $t=$p->get_token()) {
1.640 albertel 1736: if ($t->[0] eq 'S') {
1737: my ($tagname, $attr) = ($t->[1],$t->[2]);
1738: push (@state, $tagname);
1.648 raeburn 1739: if (lc($tagname) eq 'allow') {
1740: &add_filetype($allfiles,$attr->{'src'},'src');
1741: }
1.640 albertel 1742: if (lc($tagname) eq 'img') {
1743: &add_filetype($allfiles,$attr->{'src'},'src');
1744: }
1.645 raeburn 1745: if (lc($tagname) eq 'script') {
1746: if ($attr->{'archive'} =~ /\.jar$/i) {
1747: &add_filetype($allfiles,$attr->{'archive'},'archive');
1748: } else {
1749: &add_filetype($allfiles,$attr->{'src'},'src');
1750: }
1751: }
1752: if (lc($tagname) eq 'link') {
1753: if (lc($attr->{'rel'}) eq 'stylesheet') {
1754: &add_filetype($allfiles,$attr->{'href'},'href');
1755: }
1756: }
1.640 albertel 1757: if (lc($tagname) eq 'object' ||
1758: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1759: foreach my $item (keys(%javafiles)) {
1760: $javafiles{$item} = '';
1761: }
1762: }
1763: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1764: my $name = lc($attr->{'name'});
1765: foreach my $item (keys(%javafiles)) {
1766: if ($name eq $item) {
1767: $javafiles{$item} = $attr->{'value'};
1768: last;
1769: }
1770: }
1771: foreach my $item (keys(%mediafiles)) {
1772: if ($name eq $item) {
1773: &add_filetype($allfiles, $attr->{'value'}, 'value');
1774: last;
1775: }
1776: }
1777: }
1778: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1779: foreach my $item (keys(%javafiles)) {
1780: if ($attr->{$item}) {
1781: $javafiles{$item} = $attr->{$item};
1782: last;
1783: }
1784: }
1785: foreach my $item (keys(%mediafiles)) {
1786: if ($attr->{$item}) {
1787: &add_filetype($allfiles,$attr->{$item},$item);
1788: last;
1789: }
1790: }
1791: }
1792: } elsif ($t->[0] eq 'E') {
1793: my ($tagname) = ($t->[1]);
1794: if ($javafiles{'codebase'} ne '') {
1795: $javafiles{'codebase'} .= '/';
1796: }
1797: if (lc($tagname) eq 'applet' ||
1798: lc($tagname) eq 'object' ||
1799: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1800: ) {
1801: foreach my $item (keys(%javafiles)) {
1802: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1803: my $file=$javafiles{'codebase'}.$javafiles{$item};
1804: &add_filetype($allfiles,$file,$item);
1805: }
1806: }
1807: }
1808: pop @state;
1809: }
1810: }
1.637 raeburn 1811: return 'ok';
1812: }
1813:
1.639 albertel 1814: sub add_filetype {
1815: my ($allfiles,$file,$type)=@_;
1816: if (exists($allfiles->{$file})) {
1817: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1818: push(@{$allfiles->{$file}}, &escape($type));
1819: }
1820: } else {
1821: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1822: }
1823: }
1824:
1.493 albertel 1825: sub removeuploadedurl {
1826: my ($url)=@_;
1827: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1828: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1829: }
1830:
1831: sub removeuserfile {
1832: my ($docuname,$docudom,$fname)=@_;
1833: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1834: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1835: if ($result eq 'ok') {
1836: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1837: my $metafile = $fname.'.meta';
1838: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 1839: my $url = "/uploaded/$docudom/$docuname/$fname";
1840: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1841: my $sqlresult =
1.823 albertel 1842: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1843: 'portfolio_metadata',$group,
1844: 'delete');
1.798 raeburn 1845: }
1846: }
1847: return $result;
1.257 www 1848: }
1.15 www 1849:
1.530 albertel 1850: sub mkdiruserfile {
1851: my ($docuname,$docudom,$dir)=@_;
1852: my $home=&homeserver($docuname,$docudom);
1853: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1854: }
1855:
1.531 albertel 1856: sub renameuserfile {
1857: my ($docuname,$docudom,$old,$new)=@_;
1858: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1859: my $result = &reply("renameuserfile:$docudom:$docuname:".
1860: &escape("$old").':'.&escape("$new"),$home);
1861: if ($result eq 'ok') {
1862: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1863: my $oldmeta = $old.'.meta';
1864: my $newmeta = $new.'.meta';
1865: my $metaresult =
1866: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 1867: my $url = "/uploaded/$docudom/$docuname/$old";
1868: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1869: my $sqlresult =
1.823 albertel 1870: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1871: 'portfolio_metadata',$group,
1872: 'delete');
1.798 raeburn 1873: }
1874: }
1875: return $result;
1.531 albertel 1876: }
1877:
1.14 www 1878: # ------------------------------------------------------------------------- Log
1879:
1880: sub log {
1881: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1882: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1883: }
1884:
1885: # ------------------------------------------------------------------ Course Log
1.352 www 1886: #
1887: # This routine flushes several buffers of non-mission-critical nature
1888: #
1.157 www 1889:
1890: sub flushcourselogs {
1.352 www 1891: &logthis('Flushing log buffers');
1892: #
1893: # course logs
1894: # This is a log of all transactions in a course, which can be used
1895: # for data mining purposes
1896: #
1897: # It also collects the courseid database, which lists last transaction
1898: # times and course titles for all courseids
1899: #
1900: my %courseidbuffer=();
1.800 albertel 1901: foreach my $crsid (keys %courselogs) {
1.352 www 1902: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1903: &escape($courselogs{$crsid}),
1904: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1905: delete $courselogs{$crsid};
1906: } else {
1907: &logthis('Failed to flush log buffer for '.$crsid);
1908: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1909: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1910: " exceeded maximum size, deleting.</font>");
1911: delete $courselogs{$crsid};
1912: }
1.352 www 1913: }
1914: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1915: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1916: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1917: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1918: } else {
1919: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1920: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1921: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1922: }
1.191 harris41 1923: }
1.352 www 1924: #
1925: # Write course id database (reverse lookup) to homeserver of courses
1926: # Is used in pickcourse
1927: #
1.840 albertel 1928: foreach my $crs_home (keys(%courseidbuffer)) {
1.844 albertel 1929: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840 albertel 1930: $crs_home);
1.352 www 1931: }
1932: #
1933: # File accesses
1934: # Writes to the dynamic metadata of resources to get hit counts, etc.
1935: #
1.449 matthew 1936: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1937: if ($entry =~ /___count$/) {
1938: my ($dom,$name);
1.807 albertel 1939: ($dom,$name,undef)=
1.811 albertel 1940: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 1941: if (! defined($dom) || $dom eq '' ||
1942: ! defined($name) || $name eq '') {
1.620 albertel 1943: my $cid = $env{'request.course.id'};
1944: $dom = $env{'request.'.$cid.'.domain'};
1945: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1946: }
1.450 matthew 1947: my $value = $accesshash{$entry};
1948: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1949: my %temphash=($url => $value);
1.449 matthew 1950: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1951: if ($result eq 'ok') {
1952: delete $accesshash{$entry};
1953: } elsif ($result eq 'unknown_cmd') {
1954: # Target server has old code running on it.
1.450 matthew 1955: my %temphash=($entry => $value);
1.449 matthew 1956: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1957: delete $accesshash{$entry};
1958: }
1959: }
1960: } else {
1.811 albertel 1961: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 1962: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1963: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1964: delete $accesshash{$entry};
1965: }
1.185 www 1966: }
1.191 harris41 1967: }
1.352 www 1968: #
1969: # Roles
1970: # Reverse lookup of user roles for course faculty/staff and co-authorship
1971: #
1.800 albertel 1972: foreach my $entry (keys(%userrolehash)) {
1.351 www 1973: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1974: split(/\:/,$entry);
1975: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1976: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1977: $rudom,$runame) eq 'ok') {
1978: delete $userrolehash{$entry};
1979: }
1980: }
1.662 raeburn 1981: #
1982: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1983: #
1984: my %domrolebuffer = ();
1985: foreach my $entry (keys %domainrolehash) {
1986: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1987: if ($domrolebuffer{$rudom}) {
1988: $domrolebuffer{$rudom}.='&'.&escape($entry).
1989: '='.&escape($domainrolehash{$entry});
1990: } else {
1991: $domrolebuffer{$rudom}.=&escape($entry).
1992: '='.&escape($domainrolehash{$entry});
1993: }
1994: delete $domainrolehash{$entry};
1995: }
1996: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 1997: my %servers = &get_servers($dom,'library');
1998: foreach my $tryserver (keys(%servers)) {
1999: unless (&reply('domroleput:'.$dom.':'.
2000: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2001: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2002: }
1.662 raeburn 2003: }
2004: }
1.186 www 2005: $dumpcount++;
1.157 www 2006: }
2007:
2008: sub courselog {
2009: my $what=shift;
1.158 www 2010: $what=time.':'.$what;
1.620 albertel 2011: unless ($env{'request.course.id'}) { return ''; }
2012: $coursedombuf{$env{'request.course.id'}}=
2013: $env{'course.'.$env{'request.course.id'}.'.domain'};
2014: $coursenumbuf{$env{'request.course.id'}}=
2015: $env{'course.'.$env{'request.course.id'}.'.num'};
2016: $coursehombuf{$env{'request.course.id'}}=
2017: $env{'course.'.$env{'request.course.id'}.'.home'};
2018: $coursedescrbuf{$env{'request.course.id'}}=
2019: $env{'course.'.$env{'request.course.id'}.'.description'};
2020: $courseinstcodebuf{$env{'request.course.id'}}=
2021: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2022: $courseownerbuf{$env{'request.course.id'}}=
2023: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2024: $coursetypebuf{$env{'request.course.id'}}=
2025: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2026: if (defined $courselogs{$env{'request.course.id'}}) {
2027: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2028: } else {
1.620 albertel 2029: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2030: }
1.620 albertel 2031: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2032: &flushcourselogs();
2033: }
1.158 www 2034: }
2035:
2036: sub courseacclog {
2037: my $fnsymb=shift;
1.620 albertel 2038: unless ($env{'request.course.id'}) { return ''; }
2039: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2040: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2041: $what.=':POST';
1.583 matthew 2042: # FIXME: Probably ought to escape things....
1.800 albertel 2043: foreach my $key (keys(%env)) {
2044: if ($key=~/^form\.(.*)/) {
2045: $what.=':'.$1.'='.$env{$key};
1.158 www 2046: }
1.191 harris41 2047: }
1.583 matthew 2048: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2049: # FIXME: We should not be depending on a form parameter that someone
2050: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2051: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2052: $what.= ':POST';
2053: # FIXME: Probably ought to escape things....
2054: foreach my $element ('courseexp','crsfulltext','crsrelated',
2055: 'crsdiscuss') {
1.620 albertel 2056: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2057: }
2058: }
1.158 www 2059: }
2060: &courselog($what);
1.149 www 2061: }
2062:
1.185 www 2063: sub countacc {
2064: my $url=&declutter(shift);
1.458 matthew 2065: return if (! defined($url) || $url eq '');
1.620 albertel 2066: unless ($env{'request.course.id'}) { return ''; }
2067: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2068: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2069: $accesshash{$key}++;
1.185 www 2070: }
1.349 www 2071:
1.361 www 2072: sub linklog {
2073: my ($from,$to)=@_;
2074: $from=&declutter($from);
2075: $to=&declutter($to);
2076: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2077: $accesshash{$to.'___'.$from.'___goto'}=1;
2078: }
2079:
1.349 www 2080: sub userrolelog {
2081: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2082: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2083: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2084: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2085: ($trole=~/^ta/)) {
1.350 www 2086: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2087: $userrolehash
2088: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2089: =$tend.':'.$tstart;
1.662 raeburn 2090: }
2091: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2092: ($trole=~/^li/) || ($trole=~/^li/) ||
2093: ($trole=~/^au/) || ($trole=~/^dg/) ||
2094: ($trole=~/^sc/)) {
2095: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2096: $domainrolehash
2097: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2098: = $tend.':'.$tstart;
2099: }
1.351 www 2100: }
2101:
2102: sub get_course_adv_roles {
2103: my $cid=shift;
1.620 albertel 2104: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2105: my %coursehash=&coursedescription($cid);
1.470 www 2106: my %nothide=();
1.800 albertel 2107: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2108: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2109: }
1.351 www 2110: my %returnhash=();
2111: my %dumphash=
2112: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2113: my $now=time;
1.800 albertel 2114: foreach my $entry (keys %dumphash) {
2115: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2116: if (($tstart) && ($tstart<0)) { next; }
2117: if (($tend) && ($tend<$now)) { next; }
2118: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2119: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2120: if ($username eq '' || $domain eq '') { next; }
1.470 www 2121: if ((&privileged($username,$domain)) &&
2122: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2123: if ($role eq 'cr') { next; }
1.351 www 2124: my $key=&plaintext($role);
2125: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2126: if ($returnhash{$key}) {
2127: $returnhash{$key}.=','.$username.':'.$domain;
2128: } else {
2129: $returnhash{$key}=$username.':'.$domain;
2130: }
1.400 www 2131: }
2132: return %returnhash;
2133: }
2134:
2135: sub get_my_roles {
1.858 raeburn 2136: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2137: unless (defined($uname)) { $uname=$env{'user.name'}; }
2138: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2139: my %dumphash;
2140: if ($context eq 'userroles') {
2141: %dumphash = &dump('roles',$udom,$uname);
2142: } else {
2143: %dumphash=
1.400 www 2144: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2145: }
1.400 www 2146: my %returnhash=();
2147: my $now=time;
1.800 albertel 2148: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2149: my ($role,$tend,$tstart);
2150: if ($context eq 'userroles') {
2151: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2152: } else {
2153: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2154: }
1.400 www 2155: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2156: my $status = 'active';
2157: if (($tend) && ($tend<$now)) {
2158: $status = 'previous';
2159: }
2160: if (($tstart) && ($now<$tstart)) {
2161: $status = 'future';
2162: }
2163: if (ref($types) eq 'ARRAY') {
2164: if (!grep(/^\Q$status\E$/,@{$types})) {
2165: next;
2166: }
2167: } else {
2168: if ($status ne 'active') {
2169: next;
2170: }
2171: }
1.867 raeburn 2172: my ($rolecode,$username,$domain,$section,$area);
2173: if ($context eq 'userroles') {
2174: ($area,$rolecode) = split(/_/,$entry);
2175: (undef,$domain,$username,$section) = split(/\//,$area);
2176: } else {
2177: ($role,$username,$domain,$section) = split(/\:/,$entry);
2178: }
1.832 raeburn 2179: if (ref($roledoms) eq 'ARRAY') {
2180: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2181: next;
2182: }
2183: }
2184: if (ref($roles) eq 'ARRAY') {
2185: if (!grep(/^\Q$role\E$/,@{$roles})) {
2186: next;
2187: }
1.867 raeburn 2188: }
1.400 www 2189: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2190: }
1.373 www 2191: return %returnhash;
1.399 www 2192: }
2193:
2194: # ----------------------------------------------------- Frontpage Announcements
2195: #
2196: #
2197:
2198: sub postannounce {
2199: my ($server,$text)=@_;
1.844 albertel 2200: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2201: unless ($text=~/\w/) { $text=''; }
2202: return &reply('setannounce:'.&escape($text),$server);
2203: }
2204:
2205: sub getannounce {
1.448 albertel 2206:
2207: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2208: my $announcement='';
1.800 albertel 2209: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2210: close($fh);
1.399 www 2211: if ($announcement=~/\w/) {
2212: return
2213: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2214: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2215: } else {
2216: return '';
2217: }
2218: } else {
2219: return '';
2220: }
1.351 www 2221: }
1.353 www 2222:
2223: # ---------------------------------------------------------- Course ID routines
2224: # Deal with domain's nohist_courseid.db files
2225: #
2226:
2227: sub courseidput {
2228: my ($domain,$what,$coursehome)=@_;
2229: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2230: }
2231:
2232: sub courseiddump {
1.791 raeburn 2233: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353 www 2234: my %returnhash=();
1.355 www 2235: unless ($domfilter) { $domfilter=''; }
1.845 albertel 2236: my %libserv = &all_library();
2237: foreach my $tryserver (keys(%libserv)) {
2238: if ( ( $hostidflag == 1
2239: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2240: || (!defined($hostidflag)) ) {
2241:
2242: if ($domfilter eq ''
2243: || (&host_domain($tryserver) eq $domfilter)) {
1.800 albertel 2244: foreach my $line (
1.844 albertel 2245: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571 raeburn 2246: $sincefilter.':'.&escape($descfilter).':'.
1.791 raeburn 2247: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354 www 2248: $tryserver))) {
1.800 albertel 2249: my ($key,$value)=split(/\=/,$line,2);
1.506 raeburn 2250: if (($key) && ($value)) {
1.516 raeburn 2251: $returnhash{&unescape($key)}=$value;
1.506 raeburn 2252: }
1.353 www 2253: }
2254: }
2255: }
2256: }
2257: return %returnhash;
2258: }
2259:
1.658 raeburn 2260: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2261:
2262: sub dcmailput {
1.685 raeburn 2263: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2264: my $status = &Apache::lonnet::critical(
1.740 www 2265: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2266: &escape($message),$server);
1.662 raeburn 2267: return $status;
2268: }
2269:
1.658 raeburn 2270: sub dcmaildump {
2271: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2272: my %returnhash=();
1.846 albertel 2273:
2274: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2275: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2276: &escape($enddate).':';
2277: my @esc_senders=map { &escape($_)} @$senders;
2278: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2279: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2280: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2281: if (($key) && ($value)) {
2282: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2283: }
2284: }
2285: }
2286: return %returnhash;
2287: }
1.662 raeburn 2288: # ---------------------------------------------------------- Domain roles
2289:
2290: sub get_domain_roles {
2291: my ($dom,$roles,$startdate,$enddate)=@_;
2292: if (undef($startdate) || $startdate eq '') {
2293: $startdate = '.';
2294: }
2295: if (undef($enddate) || $enddate eq '') {
2296: $enddate = '.';
2297: }
2298: my $rolelist = join(':',@{$roles});
2299: my %personnel = ();
1.841 albertel 2300:
2301: my %servers = &get_servers($dom,'library');
2302: foreach my $tryserver (keys(%servers)) {
2303: %{$personnel{$tryserver}}=();
2304: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2305: &escape($startdate).':'.
2306: &escape($enddate).':'.
2307: &escape($rolelist), $tryserver))) {
2308: my ($key,$value) = split(/\=/,$line,2);
2309: if (($key) && ($value)) {
2310: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2311: }
2312: }
1.662 raeburn 2313: }
2314: return %personnel;
2315: }
1.658 raeburn 2316:
1.149 www 2317: # ----------------------------------------------------------- Check out an item
2318:
1.504 albertel 2319: sub get_first_access {
2320: my ($type,$argsymb)=@_;
1.790 albertel 2321: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2322: if ($argsymb) { $symb=$argsymb; }
2323: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2324: if ($type eq 'map') {
2325: $res=&symbread($map);
2326: } else {
2327: $res=$symb;
2328: }
2329: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2330: return $times{"$courseid\0$res"};
1.504 albertel 2331: }
2332:
2333: sub set_first_access {
2334: my ($type)=@_;
1.790 albertel 2335: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2336: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2337: if ($type eq 'map') {
2338: $res=&symbread($map);
2339: } else {
2340: $res=$symb;
2341: }
2342: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2343: if (!$firstaccess) {
1.588 albertel 2344: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2345: }
2346: return 'already_set';
1.504 albertel 2347: }
2348:
1.149 www 2349: sub checkout {
2350: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2351: my $now=time;
2352: my $lonhost=$perlvar{'lonHostID'};
2353: my $infostr=&escape(
1.234 www 2354: 'CHECKOUTTOKEN&'.
1.149 www 2355: $tuname.'&'.
2356: $tudom.'&'.
2357: $tcrsid.'&'.
2358: $symb.'&'.
2359: $now.'&'.$ENV{'REMOTE_ADDR'});
2360: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2361: if ($token=~/^error\:/) {
1.672 albertel 2362: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2363: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2364: "</font>");
2365: return '';
2366: }
2367:
1.149 www 2368: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2369: $token=~tr/a-z/A-Z/;
2370:
1.153 www 2371: my %infohash=('resource.0.outtoken' => $token,
2372: 'resource.0.checkouttime' => $now,
2373: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2374:
2375: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2376: return '';
1.151 www 2377: } else {
1.672 albertel 2378: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2379: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2380: "</font>");
1.149 www 2381: }
2382:
2383: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2384: &escape('Checkout '.$infostr.' - '.
2385: $token)) ne 'ok') {
2386: return '';
1.151 www 2387: } else {
1.672 albertel 2388: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2389: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2390: "</font>");
1.149 www 2391: }
1.151 www 2392: return $token;
1.149 www 2393: }
2394:
2395: # ------------------------------------------------------------ Check in an item
2396:
2397: sub checkin {
2398: my $token=shift;
1.150 www 2399: my $now=time;
2400: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2401: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2402: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2403: $dtoken=~s/\W/\_/g;
1.234 www 2404: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2405: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2406:
1.154 www 2407: unless (($tuname) && ($tudom)) {
2408: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2409: return '';
2410: }
2411:
2412: unless (&allowed('mgr',$tcrsid)) {
2413: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2414: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2415: return '';
2416: }
2417:
1.153 www 2418: my %infohash=('resource.0.intoken' => $token,
2419: 'resource.0.checkintime' => $now,
2420: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2421:
2422: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2423: return '';
2424: }
2425:
2426: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2427: &escape('Checkin - '.$token)) ne 'ok') {
2428: return '';
2429: }
2430:
2431: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2432: }
2433:
2434: # --------------------------------------------- Set Expire Date for Spreadsheet
2435:
2436: sub expirespread {
2437: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2438: my $cid=$env{'request.course.id'};
1.110 www 2439: if ($cid) {
2440: my $now=time;
2441: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2442: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2443: $env{'course.'.$cid.'.num'}.
1.110 www 2444: ':nohist_expirationdates:'.
2445: &escape($key).'='.$now,
1.620 albertel 2446: $env{'course.'.$cid.'.home'})
1.110 www 2447: }
2448: return 'ok';
1.14 www 2449: }
2450:
1.109 www 2451: # ----------------------------------------------------- Devalidate Spreadsheets
2452:
2453: sub devalidate {
1.325 www 2454: my ($symb,$uname,$udom)=@_;
1.620 albertel 2455: my $cid=$env{'request.course.id'};
1.109 www 2456: if ($cid) {
1.391 matthew 2457: # delete the stored spreadsheets for
2458: # - the student level sheet of this user in course's homespace
2459: # - the assessment level sheet for this resource
2460: # for this user in user's homespace
1.553 albertel 2461: # - current conditional state info
1.325 www 2462: my $key=$uname.':'.$udom.':';
1.109 www 2463: my $status=
1.299 matthew 2464: &del('nohist_calculatedsheets',
1.391 matthew 2465: [$key.'studentcalc:'],
1.620 albertel 2466: $env{'course.'.$cid.'.domain'},
2467: $env{'course.'.$cid.'.num'})
1.133 albertel 2468: .' '.
2469: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2470: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2471: unless ($status eq 'ok ok') {
2472: &logthis('Could not devalidate spreadsheet '.
1.325 www 2473: $uname.' at '.$udom.' for '.
1.109 www 2474: $symb.': '.$status);
1.133 albertel 2475: }
1.553 albertel 2476: &delenv('user.state.'.$cid);
1.109 www 2477: }
2478: }
2479:
1.265 albertel 2480: sub get_scalar {
2481: my ($string,$end) = @_;
2482: my $value;
2483: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2484: $value = $1;
2485: } elsif ($$string =~ s/^([^&]*?)&//) {
2486: $value = $1;
2487: }
2488: return &unescape($value);
2489: }
2490:
2491: sub array2str {
2492: my (@array) = @_;
2493: my $result=&arrayref2str(\@array);
2494: $result=~s/^__ARRAY_REF__//;
2495: $result=~s/__END_ARRAY_REF__$//;
2496: return $result;
2497: }
2498:
1.204 albertel 2499: sub arrayref2str {
2500: my ($arrayref) = @_;
1.265 albertel 2501: my $result='__ARRAY_REF__';
1.204 albertel 2502: foreach my $elem (@$arrayref) {
1.265 albertel 2503: if(ref($elem) eq 'ARRAY') {
2504: $result.=&arrayref2str($elem).'&';
2505: } elsif(ref($elem) eq 'HASH') {
2506: $result.=&hashref2str($elem).'&';
2507: } elsif(ref($elem)) {
2508: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2509: } else {
2510: $result.=&escape($elem).'&';
2511: }
2512: }
2513: $result=~s/\&$//;
1.265 albertel 2514: $result .= '__END_ARRAY_REF__';
1.204 albertel 2515: return $result;
2516: }
2517:
1.168 albertel 2518: sub hash2str {
1.204 albertel 2519: my (%hash) = @_;
2520: my $result=&hashref2str(\%hash);
1.265 albertel 2521: $result=~s/^__HASH_REF__//;
2522: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2523: return $result;
2524: }
2525:
2526: sub hashref2str {
2527: my ($hashref)=@_;
1.265 albertel 2528: my $result='__HASH_REF__';
1.800 albertel 2529: foreach my $key (sort(keys(%$hashref))) {
2530: if (ref($key) eq 'ARRAY') {
2531: $result.=&arrayref2str($key).'=';
2532: } elsif (ref($key) eq 'HASH') {
2533: $result.=&hashref2str($key).'=';
2534: } elsif (ref($key)) {
1.265 albertel 2535: $result.='=';
1.800 albertel 2536: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2537: } else {
1.800 albertel 2538: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2539: }
2540:
1.800 albertel 2541: if(ref($hashref->{$key}) eq 'ARRAY') {
2542: $result.=&arrayref2str($hashref->{$key}).'&';
2543: } elsif(ref($hashref->{$key}) eq 'HASH') {
2544: $result.=&hashref2str($hashref->{$key}).'&';
2545: } elsif(ref($hashref->{$key})) {
1.265 albertel 2546: $result.='&';
1.800 albertel 2547: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2548: } else {
1.800 albertel 2549: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2550: }
2551: }
1.168 albertel 2552: $result=~s/\&$//;
1.265 albertel 2553: $result .= '__END_HASH_REF__';
1.168 albertel 2554: return $result;
2555: }
2556:
2557: sub str2hash {
1.265 albertel 2558: my ($string)=@_;
2559: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2560: return %$hash;
2561: }
2562:
2563: sub str2hashref {
1.168 albertel 2564: my ($string) = @_;
1.265 albertel 2565:
2566: my %hash;
2567:
2568: if($string !~ /^__HASH_REF__/) {
2569: if (! ($string eq '' || !defined($string))) {
2570: $hash{'error'}='Not hash reference';
2571: }
2572: return (\%hash, $string);
2573: }
2574:
2575: $string =~ s/^__HASH_REF__//;
2576:
2577: while($string !~ /^__END_HASH_REF__/) {
2578: #key
2579: my $key='';
2580: if($string =~ /^__HASH_REF__/) {
2581: ($key, $string)=&str2hashref($string);
2582: if(defined($key->{'error'})) {
2583: $hash{'error'}='Bad data';
2584: return (\%hash, $string);
2585: }
2586: } elsif($string =~ /^__ARRAY_REF__/) {
2587: ($key, $string)=&str2arrayref($string);
2588: if($key->[0] eq 'Array reference error') {
2589: $hash{'error'}='Bad data';
2590: return (\%hash, $string);
2591: }
2592: } else {
2593: $string =~ s/^(.*?)=//;
1.267 albertel 2594: $key=&unescape($1);
1.265 albertel 2595: }
2596: $string =~ s/^=//;
2597:
2598: #value
2599: my $value='';
2600: if($string =~ /^__HASH_REF__/) {
2601: ($value, $string)=&str2hashref($string);
2602: if(defined($value->{'error'})) {
2603: $hash{'error'}='Bad data';
2604: return (\%hash, $string);
2605: }
2606: } elsif($string =~ /^__ARRAY_REF__/) {
2607: ($value, $string)=&str2arrayref($string);
2608: if($value->[0] eq 'Array reference error') {
2609: $hash{'error'}='Bad data';
2610: return (\%hash, $string);
2611: }
2612: } else {
2613: $value=&get_scalar(\$string,'__END_HASH_REF__');
2614: }
2615: $string =~ s/^&//;
2616:
2617: $hash{$key}=$value;
1.204 albertel 2618: }
1.265 albertel 2619:
2620: $string =~ s/^__END_HASH_REF__//;
2621:
2622: return (\%hash, $string);
1.204 albertel 2623: }
2624:
2625: sub str2array {
1.265 albertel 2626: my ($string)=@_;
2627: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2628: return @$array;
2629: }
2630:
2631: sub str2arrayref {
1.204 albertel 2632: my ($string) = @_;
1.265 albertel 2633: my @array;
2634:
2635: if($string !~ /^__ARRAY_REF__/) {
2636: if (! ($string eq '' || !defined($string))) {
2637: $array[0]='Array reference error';
2638: }
2639: return (\@array, $string);
2640: }
2641:
2642: $string =~ s/^__ARRAY_REF__//;
2643:
2644: while($string !~ /^__END_ARRAY_REF__/) {
2645: my $value='';
2646: if($string =~ /^__HASH_REF__/) {
2647: ($value, $string)=&str2hashref($string);
2648: if(defined($value->{'error'})) {
2649: $array[0] ='Array reference error';
2650: return (\@array, $string);
2651: }
2652: } elsif($string =~ /^__ARRAY_REF__/) {
2653: ($value, $string)=&str2arrayref($string);
2654: if($value->[0] eq 'Array reference error') {
2655: $array[0] ='Array reference error';
2656: return (\@array, $string);
2657: }
2658: } else {
2659: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2660: }
2661: $string =~ s/^&//;
2662:
2663: push(@array, $value);
1.191 harris41 2664: }
1.265 albertel 2665:
2666: $string =~ s/^__END_ARRAY_REF__//;
2667:
2668: return (\@array, $string);
1.168 albertel 2669: }
2670:
1.167 albertel 2671: # -------------------------------------------------------------------Temp Store
2672:
1.168 albertel 2673: sub tmpreset {
2674: my ($symb,$namespace,$domain,$stuname) = @_;
2675: if (!$symb) {
2676: $symb=&symbread();
1.620 albertel 2677: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2678: }
2679: $symb=escape($symb);
2680:
1.620 albertel 2681: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2682: $namespace=~s/\//\_/g;
2683: $namespace=~s/\W//g;
2684:
1.620 albertel 2685: if (!$domain) { $domain=$env{'user.domain'}; }
2686: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2687: if ($domain eq 'public' && $stuname eq 'public') {
2688: $stuname=$ENV{'REMOTE_ADDR'};
2689: }
1.168 albertel 2690: my $path=$perlvar{'lonDaemons'}.'/tmp';
2691: my %hash;
2692: if (tie(%hash,'GDBM_File',
2693: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2694: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2695: foreach my $key (keys %hash) {
1.180 albertel 2696: if ($key=~ /:$symb/) {
1.168 albertel 2697: delete($hash{$key});
2698: }
2699: }
2700: }
2701: }
2702:
1.167 albertel 2703: sub tmpstore {
1.168 albertel 2704: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2705:
2706: if (!$symb) {
2707: $symb=&symbread();
1.620 albertel 2708: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2709: }
2710: $symb=escape($symb);
2711:
2712: if (!$namespace) {
2713: # I don't think we would ever want to store this for a course.
2714: # it seems this will only be used if we don't have a course.
1.620 albertel 2715: #$namespace=$env{'request.course.id'};
1.168 albertel 2716: #if (!$namespace) {
1.620 albertel 2717: $namespace=$env{'request.state'};
1.168 albertel 2718: #}
2719: }
2720: $namespace=~s/\//\_/g;
2721: $namespace=~s/\W//g;
1.620 albertel 2722: if (!$domain) { $domain=$env{'user.domain'}; }
2723: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2724: if ($domain eq 'public' && $stuname eq 'public') {
2725: $stuname=$ENV{'REMOTE_ADDR'};
2726: }
1.168 albertel 2727: my $now=time;
2728: my %hash;
2729: my $path=$perlvar{'lonDaemons'}.'/tmp';
2730: if (tie(%hash,'GDBM_File',
2731: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2732: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2733: $hash{"version:$symb"}++;
2734: my $version=$hash{"version:$symb"};
2735: my $allkeys='';
2736: foreach my $key (keys(%$storehash)) {
2737: $allkeys.=$key.':';
1.591 albertel 2738: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2739: }
2740: $hash{"$version:$symb:timestamp"}=$now;
2741: $allkeys.='timestamp';
2742: $hash{"$version:keys:$symb"}=$allkeys;
2743: if (untie(%hash)) {
2744: return 'ok';
2745: } else {
2746: return "error:$!";
2747: }
2748: } else {
2749: return "error:$!";
2750: }
2751: }
1.167 albertel 2752:
1.168 albertel 2753: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2754:
1.168 albertel 2755: sub tmprestore {
2756: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2757:
1.168 albertel 2758: if (!$symb) {
2759: $symb=&symbread();
1.620 albertel 2760: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2761: }
2762: $symb=escape($symb);
2763:
1.620 albertel 2764: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2765:
1.620 albertel 2766: if (!$domain) { $domain=$env{'user.domain'}; }
2767: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2768: if ($domain eq 'public' && $stuname eq 'public') {
2769: $stuname=$ENV{'REMOTE_ADDR'};
2770: }
1.168 albertel 2771: my %returnhash;
2772: $namespace=~s/\//\_/g;
2773: $namespace=~s/\W//g;
2774: my %hash;
2775: my $path=$perlvar{'lonDaemons'}.'/tmp';
2776: if (tie(%hash,'GDBM_File',
2777: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2778: &GDBM_READER(),0640)) {
1.168 albertel 2779: my $version=$hash{"version:$symb"};
2780: $returnhash{'version'}=$version;
2781: my $scope;
2782: for ($scope=1;$scope<=$version;$scope++) {
2783: my $vkeys=$hash{"$scope:keys:$symb"};
2784: my @keys=split(/:/,$vkeys);
2785: my $key;
2786: $returnhash{"$scope:keys"}=$vkeys;
2787: foreach $key (@keys) {
1.591 albertel 2788: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2789: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2790: }
2791: }
1.168 albertel 2792: if (!(untie(%hash))) {
2793: return "error:$!";
2794: }
2795: } else {
2796: return "error:$!";
2797: }
2798: return %returnhash;
1.167 albertel 2799: }
2800:
1.9 www 2801: # ----------------------------------------------------------------------- Store
2802:
2803: sub store {
1.124 www 2804: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2805: my $home='';
2806:
1.168 albertel 2807: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2808:
1.213 www 2809: $symb=&symbclean($symb);
1.122 albertel 2810: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2811:
1.620 albertel 2812: if (!$domain) { $domain=$env{'user.domain'}; }
2813: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2814:
2815: &devalidate($symb,$stuname,$domain);
1.109 www 2816:
2817: $symb=escape($symb);
1.187 www 2818: if (!$namespace) {
1.620 albertel 2819: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2820: return '';
2821: }
2822: }
1.620 albertel 2823: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2824:
2825: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2826: $$storehash{'host'}=$perlvar{'lonHostID'};
2827:
1.12 www 2828: my $namevalue='';
1.800 albertel 2829: foreach my $key (keys(%$storehash)) {
2830: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2831: }
1.12 www 2832: $namevalue=~s/\&$//;
1.187 www 2833: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2834: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2835: }
2836:
1.47 www 2837: # -------------------------------------------------------------- Critical Store
2838:
2839: sub cstore {
1.124 www 2840: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2841: my $home='';
2842:
1.168 albertel 2843: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2844:
1.213 www 2845: $symb=&symbclean($symb);
1.122 albertel 2846: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2847:
1.620 albertel 2848: if (!$domain) { $domain=$env{'user.domain'}; }
2849: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2850:
2851: &devalidate($symb,$stuname,$domain);
1.109 www 2852:
2853: $symb=escape($symb);
1.187 www 2854: if (!$namespace) {
1.620 albertel 2855: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2856: return '';
2857: }
2858: }
1.620 albertel 2859: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2860:
2861: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2862: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2863:
1.47 www 2864: my $namevalue='';
1.800 albertel 2865: foreach my $key (keys(%$storehash)) {
2866: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2867: }
1.47 www 2868: $namevalue=~s/\&$//;
1.187 www 2869: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2870: return critical
2871: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2872: }
2873:
1.9 www 2874: # --------------------------------------------------------------------- Restore
2875:
2876: sub restore {
1.124 www 2877: my ($symb,$namespace,$domain,$stuname) = @_;
2878: my $home='';
2879:
1.168 albertel 2880: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2881:
1.122 albertel 2882: if (!$symb) {
2883: unless ($symb=escape(&symbread())) { return ''; }
2884: } else {
1.213 www 2885: $symb=&escape(&symbclean($symb));
1.122 albertel 2886: }
1.188 www 2887: if (!$namespace) {
1.620 albertel 2888: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2889: return '';
2890: }
2891: }
1.620 albertel 2892: if (!$domain) { $domain=$env{'user.domain'}; }
2893: if (!$stuname) { $stuname=$env{'user.name'}; }
2894: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2895: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2896:
1.12 www 2897: my %returnhash=();
1.800 albertel 2898: foreach my $line (split(/\&/,$answer)) {
2899: my ($name,$value)=split(/\=/,$line);
1.591 albertel 2900: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2901: }
1.75 www 2902: my $version;
2903: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 2904: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2905: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 2906: }
1.75 www 2907: }
1.13 www 2908: return %returnhash;
1.34 www 2909: }
2910:
2911: # ---------------------------------------------------------- Course Description
2912:
2913: sub coursedescription {
1.731 albertel 2914: my ($courseid,$args)=@_;
1.34 www 2915: $courseid=~s/^\///;
1.49 www 2916: $courseid=~s/\_/\//g;
1.34 www 2917: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2918: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2919: my $normalid=$cdomain.'_'.$cnum;
2920: # need to always cache even if we get errors otherwise we keep
2921: # trying and trying and trying to get the course description.
2922: my %envhash=();
2923: my %returnhash=();
1.731 albertel 2924:
2925: my $expiretime=600;
2926: if ($env{'request.course.id'} eq $normalid) {
2927: $expiretime=120;
2928: }
2929:
2930: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2931: if (!$args->{'freshen_cache'}
2932: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2933: foreach my $key (keys(%env)) {
2934: next if ($key !~ /^\Q$prefix\E(.*)/);
2935: my ($setting) = $1;
2936: $returnhash{$setting} = $env{$key};
2937: }
2938: return %returnhash;
2939: }
2940:
2941: # get the data agin
2942: if (!$args->{'one_time'}) {
2943: $envhash{'course.'.$normalid.'.last_cache'}=time;
2944: }
1.811 albertel 2945:
1.34 www 2946: if ($chome ne 'no_host') {
1.302 albertel 2947: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2948: if (!exists($returnhash{'con_lost'})) {
2949: $returnhash{'home'}= $chome;
2950: $returnhash{'domain'} = $cdomain;
2951: $returnhash{'num'} = $cnum;
1.741 raeburn 2952: if (!defined($returnhash{'type'})) {
2953: $returnhash{'type'} = 'Course';
2954: }
1.130 albertel 2955: while (my ($name,$value) = each %returnhash) {
1.53 www 2956: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2957: }
1.270 www 2958: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2959: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2960: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2961: $envhash{'course.'.$normalid.'.home'}=$chome;
2962: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2963: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2964: }
2965: }
1.731 albertel 2966: if (!$args->{'one_time'}) {
2967: &appenv(%envhash);
2968: }
1.302 albertel 2969: return %returnhash;
1.461 www 2970: }
2971:
2972: # -------------------------------------------------See if a user is privileged
2973:
2974: sub privileged {
2975: my ($username,$domain)=@_;
2976: my $rolesdump=&reply("dump:$domain:$username:roles",
2977: &homeserver($username,$domain));
2978: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2979: my $now=time;
2980: if ($rolesdump ne '') {
1.800 albertel 2981: foreach my $entry (split(/&/,$rolesdump)) {
2982: if ($entry!~/^rolesdef_/) {
2983: my ($area,$role)=split(/=/,$entry);
1.461 www 2984: $area=~s/\_\w\w$//;
2985: my ($trole,$tend,$tstart)=split(/_/,$role);
2986: if (($trole eq 'dc') || ($trole eq 'su')) {
2987: my $active=1;
2988: if ($tend) {
2989: if ($tend<$now) { $active=0; }
2990: }
2991: if ($tstart) {
2992: if ($tstart>$now) { $active=0; }
2993: }
2994: if ($active) { return 1; }
2995: }
2996: }
2997: }
2998: }
2999: return 0;
1.9 www 3000: }
1.1 albertel 3001:
1.103 harris41 3002: # -------------------------------------------------------- Get user privileges
1.11 www 3003:
3004: sub rolesinit {
3005: my ($domain,$username,$authhost)=@_;
3006: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3007: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3008: my %allroles=();
1.678 raeburn 3009: my %allgroups=();
1.11 www 3010: my $now=time;
1.743 albertel 3011: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3012: my $group_privs;
1.11 www 3013:
3014: if ($rolesdump ne '') {
1.800 albertel 3015: foreach my $entry (split(/&/,$rolesdump)) {
3016: if ($entry!~/^rolesdef_/) {
3017: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3018: $area=~s/\_\w\w$//;
1.678 raeburn 3019: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3020: if ($role=~/^cr/) {
1.807 albertel 3021: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3022: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3023: ($tend,$tstart)=split('_',$trest);
3024: } else {
3025: $trole=$role;
3026: }
1.678 raeburn 3027: } elsif ($role =~ m|^gr/|) {
3028: ($trole,$tend,$tstart) = split(/_/,$role);
3029: ($trole,$group_privs) = split(/\//,$trole);
3030: $group_privs = &unescape($group_privs);
1.587 albertel 3031: } else {
3032: ($trole,$tend,$tstart)=split(/_/,$role);
3033: }
1.743 albertel 3034: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3035: $username);
3036: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3037: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3038: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3039: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3040: my $spec=$trole.'.'.$area;
3041: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3042: if ($trole =~ /^cr\//) {
1.567 raeburn 3043: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3044: } elsif ($trole eq 'gr') {
3045: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3046: } else {
1.567 raeburn 3047: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3048: }
1.12 www 3049: }
1.662 raeburn 3050: }
1.191 harris41 3051: }
1.743 albertel 3052: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3053: $userroles{'user.adv'} = $adv;
3054: $userroles{'user.author'} = $author;
1.620 albertel 3055: $env{'user.adv'}=$adv;
1.11 www 3056: }
1.743 albertel 3057: return \%userroles;
1.11 www 3058: }
3059:
1.567 raeburn 3060: sub set_arearole {
3061: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3062: # log the associated role with the area
3063: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3064: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3065: }
3066:
3067: sub custom_roleprivs {
3068: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3069: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3070: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3071: if (&hostname($homsvr) ne '') {
1.567 raeburn 3072: my ($rdummy,$roledef)=
3073: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3074: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3075: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3076: if (defined($syspriv)) {
3077: $$allroles{'cm./'}.=':'.$syspriv;
3078: $$allroles{$spec.'./'}.=':'.$syspriv;
3079: }
3080: if ($tdomain ne '') {
3081: if (defined($dompriv)) {
3082: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3083: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3084: }
3085: if (($trest ne '') && (defined($coursepriv))) {
3086: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3087: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3088: }
3089: }
3090: }
3091: }
3092: }
3093:
1.678 raeburn 3094: sub group_roleprivs {
3095: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3096: my $access = 1;
3097: my $now = time;
3098: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3099: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3100: if ($access) {
1.811 albertel 3101: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3102: $$allgroups{$course}{$group} .=':'.$group_privs;
3103: }
3104: }
1.567 raeburn 3105:
3106: sub standard_roleprivs {
3107: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3108: if (defined($pr{$trole.':s'})) {
3109: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3110: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3111: }
3112: if ($tdomain ne '') {
3113: if (defined($pr{$trole.':d'})) {
3114: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3115: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3116: }
3117: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3118: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3119: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3120: }
3121: }
3122: }
3123:
3124: sub set_userprivs {
1.678 raeburn 3125: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3126: my $author=0;
3127: my $adv=0;
1.678 raeburn 3128: my %grouproles = ();
3129: if (keys(%{$allgroups}) > 0) {
3130: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3131: my ($trole,$area,$sec,$extendedarea);
1.811 albertel 3132: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678 raeburn 3133: $trole = $1;
3134: $area = $2;
1.681 raeburn 3135: $sec = $3;
3136: $extendedarea = $area.$sec;
3137: if (exists($$allgroups{$area})) {
3138: foreach my $group (keys(%{$$allgroups{$area}})) {
3139: my $spec = $trole.'.'.$extendedarea;
3140: $grouproles{$spec.'.'.$area.'/'.$group} =
3141: $$allgroups{$area}{$group};
1.678 raeburn 3142: }
3143: }
3144: }
3145: }
3146: }
1.800 albertel 3147: foreach my $group (keys(%grouproles)) {
3148: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3149: }
1.800 albertel 3150: foreach my $role (keys(%{$allroles})) {
3151: my %thesepriv;
3152: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3153: foreach my $item (split(/:/,$$allroles{$role})) {
3154: if ($item ne '') {
3155: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3156: if ($restrictions eq '') {
3157: $thesepriv{$privilege}='F';
3158: } elsif ($thesepriv{$privilege} ne 'F') {
3159: $thesepriv{$privilege}.=$restrictions;
3160: }
3161: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3162: }
3163: }
3164: my $thesestr='';
1.800 albertel 3165: foreach my $priv (keys(%thesepriv)) {
3166: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3167: }
3168: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3169: }
3170: return ($author,$adv);
3171: }
3172:
1.12 www 3173: # --------------------------------------------------------------- get interface
3174:
3175: sub get {
1.131 albertel 3176: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3177: my $items='';
1.800 albertel 3178: foreach my $item (@$storearr) {
3179: $items.=&escape($item).'&';
1.191 harris41 3180: }
1.12 www 3181: $items=~s/\&$//;
1.620 albertel 3182: if (!$udomain) { $udomain=$env{'user.domain'}; }
3183: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3184: my $uhome=&homeserver($uname,$udomain);
3185:
1.133 albertel 3186: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3187: my @pairs=split(/\&/,$rep);
1.273 albertel 3188: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3189: return @pairs;
3190: }
1.15 www 3191: my %returnhash=();
1.42 www 3192: my $i=0;
1.800 albertel 3193: foreach my $item (@$storearr) {
3194: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3195: $i++;
1.191 harris41 3196: }
1.15 www 3197: return %returnhash;
1.27 www 3198: }
3199:
3200: # --------------------------------------------------------------- del interface
3201:
3202: sub del {
1.133 albertel 3203: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3204: my $items='';
1.800 albertel 3205: foreach my $item (@$storearr) {
3206: $items.=&escape($item).'&';
1.191 harris41 3207: }
1.27 www 3208: $items=~s/\&$//;
1.620 albertel 3209: if (!$udomain) { $udomain=$env{'user.domain'}; }
3210: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3211: my $uhome=&homeserver($uname,$udomain);
3212:
3213: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3214: }
3215:
3216: # -------------------------------------------------------------- dump interface
3217:
3218: sub dump {
1.755 albertel 3219: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3220: if (!$udomain) { $udomain=$env{'user.domain'}; }
3221: if (!$uname) { $uname=$env{'user.name'}; }
3222: my $uhome=&homeserver($uname,$udomain);
3223: if ($regexp) {
3224: $regexp=&escape($regexp);
3225: } else {
3226: $regexp='.';
3227: }
3228: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3229: my @pairs=split(/\&/,$rep);
3230: my %returnhash=();
3231: foreach my $item (@pairs) {
3232: my ($key,$value)=split(/=/,$item,2);
3233: $key = &unescape($key);
3234: next if ($key =~ /^error: 2 /);
3235: $returnhash{$key}=&thaw_unescape($value);
3236: }
3237: return %returnhash;
1.407 www 3238: }
3239:
1.717 albertel 3240: # --------------------------------------------------------- dumpstore interface
3241:
3242: sub dumpstore {
3243: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3244: if (!$udomain) { $udomain=$env{'user.domain'}; }
3245: if (!$uname) { $uname=$env{'user.name'}; }
3246: my $uhome=&homeserver($uname,$udomain);
3247: if ($regexp) {
3248: $regexp=&escape($regexp);
3249: } else {
3250: $regexp='.';
3251: }
3252: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3253: my @pairs=split(/\&/,$rep);
3254: my %returnhash=();
3255: foreach my $item (@pairs) {
3256: my ($key,$value)=split(/=/,$item,2);
3257: next if ($key =~ /^error: 2 /);
3258: $returnhash{$key}=&thaw_unescape($value);
3259: }
3260: return %returnhash;
1.717 albertel 3261: }
3262:
1.407 www 3263: # -------------------------------------------------------------- keys interface
3264:
3265: sub getkeys {
3266: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3267: if (!$udomain) { $udomain=$env{'user.domain'}; }
3268: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3269: my $uhome=&homeserver($uname,$udomain);
3270: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3271: my @keyarray=();
1.800 albertel 3272: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3273: next if ($key =~ /^error: 2 /);
1.800 albertel 3274: push(@keyarray,&unescape($key));
1.407 www 3275: }
3276: return @keyarray;
1.318 matthew 3277: }
3278:
1.319 matthew 3279: # --------------------------------------------------------------- currentdump
3280: sub currentdump {
1.328 matthew 3281: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3282: $courseid = $env{'request.course.id'} if (! defined($courseid));
3283: $sdom = $env{'user.domain'} if (! defined($sdom));
3284: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3285: my $uhome = &homeserver($sname,$sdom);
3286: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3287: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3288: #
1.318 matthew 3289: my %returnhash=();
1.319 matthew 3290: #
3291: if ($rep eq "unknown_cmd") {
3292: # an old lond will not know currentdump
3293: # Do a dump and make it look like a currentdump
1.822 albertel 3294: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3295: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3296: my %hash = @tmp;
3297: @tmp=();
1.424 matthew 3298: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3299: } else {
3300: my @pairs=split(/\&/,$rep);
1.800 albertel 3301: foreach my $pair (@pairs) {
3302: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3303: my ($symb,$param) = split(/:/,$key);
3304: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3305: &thaw_unescape($value);
1.319 matthew 3306: }
1.191 harris41 3307: }
1.12 www 3308: return %returnhash;
1.424 matthew 3309: }
3310:
3311: sub convert_dump_to_currentdump{
3312: my %hash = %{shift()};
3313: my %returnhash;
3314: # Code ripped from lond, essentially. The only difference
3315: # here is the unescaping done by lonnet::dump(). Conceivably
3316: # we might run in to problems with parameter names =~ /^v\./
3317: while (my ($key,$value) = each(%hash)) {
3318: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3319: $symb = &unescape($symb);
3320: $param = &unescape($param);
1.424 matthew 3321: next if ($v eq 'version' || $symb eq 'keys');
3322: next if (exists($returnhash{$symb}) &&
3323: exists($returnhash{$symb}->{$param}) &&
3324: $returnhash{$symb}->{'v.'.$param} > $v);
3325: $returnhash{$symb}->{$param}=$value;
3326: $returnhash{$symb}->{'v.'.$param}=$v;
3327: }
3328: #
3329: # Remove all of the keys in the hashes which keep track of
3330: # the version of the parameter.
3331: while (my ($symb,$param_hash) = each(%returnhash)) {
3332: # use a foreach because we are going to delete from the hash.
3333: foreach my $key (keys(%$param_hash)) {
3334: delete($param_hash->{$key}) if ($key =~ /^v\./);
3335: }
3336: }
3337: return \%returnhash;
1.12 www 3338: }
3339:
1.627 albertel 3340: # ------------------------------------------------------ critical inc interface
3341:
3342: sub cinc {
3343: return &inc(@_,'critical');
3344: }
3345:
1.449 matthew 3346: # --------------------------------------------------------------- inc interface
3347:
3348: sub inc {
1.627 albertel 3349: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3350: if (!$udomain) { $udomain=$env{'user.domain'}; }
3351: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3352: my $uhome=&homeserver($uname,$udomain);
3353: my $items='';
3354: if (! ref($store)) {
3355: # got a single value, so use that instead
3356: $items = &escape($store).'=&';
3357: } elsif (ref($store) eq 'SCALAR') {
3358: $items = &escape($$store).'=&';
3359: } elsif (ref($store) eq 'ARRAY') {
3360: $items = join('=&',map {&escape($_);} @{$store});
3361: } elsif (ref($store) eq 'HASH') {
3362: while (my($key,$value) = each(%{$store})) {
3363: $items.= &escape($key).'='.&escape($value).'&';
3364: }
3365: }
3366: $items=~s/\&$//;
1.627 albertel 3367: if ($critical) {
3368: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3369: } else {
3370: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3371: }
1.449 matthew 3372: }
3373:
1.12 www 3374: # --------------------------------------------------------------- put interface
3375:
3376: sub put {
1.134 albertel 3377: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3378: if (!$udomain) { $udomain=$env{'user.domain'}; }
3379: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3380: my $uhome=&homeserver($uname,$udomain);
1.12 www 3381: my $items='';
1.800 albertel 3382: foreach my $item (keys(%$storehash)) {
3383: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3384: }
1.12 www 3385: $items=~s/\&$//;
1.134 albertel 3386: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3387: }
3388:
1.631 albertel 3389: # ------------------------------------------------------------ newput interface
3390:
3391: sub newput {
3392: my ($namespace,$storehash,$udomain,$uname)=@_;
3393: if (!$udomain) { $udomain=$env{'user.domain'}; }
3394: if (!$uname) { $uname=$env{'user.name'}; }
3395: my $uhome=&homeserver($uname,$udomain);
3396: my $items='';
3397: foreach my $key (keys(%$storehash)) {
3398: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3399: }
3400: $items=~s/\&$//;
3401: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3402: }
3403:
3404: # --------------------------------------------------------- putstore interface
3405:
1.524 raeburn 3406: sub putstore {
1.715 albertel 3407: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3408: if (!$udomain) { $udomain=$env{'user.domain'}; }
3409: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3410: my $uhome=&homeserver($uname,$udomain);
3411: my $items='';
1.715 albertel 3412: foreach my $key (keys(%$storehash)) {
3413: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3414: }
1.715 albertel 3415: $items=~s/\&$//;
1.716 albertel 3416: my $esc_symb=&escape($symb);
3417: my $esc_v=&escape($version);
1.715 albertel 3418: my $reply =
1.716 albertel 3419: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3420: $uhome);
3421: if ($reply eq 'unknown_cmd') {
1.716 albertel 3422: # gfall back to way things use to be done
1.715 albertel 3423: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3424: $uname);
1.524 raeburn 3425: }
1.715 albertel 3426: return $reply;
3427: }
3428:
3429: sub old_putstore {
1.716 albertel 3430: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3431: if (!$udomain) { $udomain=$env{'user.domain'}; }
3432: if (!$uname) { $uname=$env{'user.name'}; }
3433: my $uhome=&homeserver($uname,$udomain);
3434: my %newstorehash;
1.800 albertel 3435: foreach my $item (keys(%$storehash)) {
3436: my $key = $version.':'.&escape($symb).':'.$item;
3437: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3438: }
3439: my $items='';
3440: my %allitems = ();
1.800 albertel 3441: foreach my $item (keys(%newstorehash)) {
3442: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3443: my $key = $1.':keys:'.$2;
3444: $allitems{$key} .= $3.':';
3445: }
1.800 albertel 3446: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3447: }
1.800 albertel 3448: foreach my $item (keys(%allitems)) {
3449: $allitems{$item} =~ s/\:$//;
3450: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3451: }
3452: $items=~s/\&$//;
3453: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3454: }
3455:
1.47 www 3456: # ------------------------------------------------------ critical put interface
3457:
3458: sub cput {
1.134 albertel 3459: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3460: if (!$udomain) { $udomain=$env{'user.domain'}; }
3461: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3462: my $uhome=&homeserver($uname,$udomain);
1.47 www 3463: my $items='';
1.800 albertel 3464: foreach my $item (keys(%$storehash)) {
3465: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3466: }
1.47 www 3467: $items=~s/\&$//;
1.134 albertel 3468: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3469: }
3470:
3471: # -------------------------------------------------------------- eget interface
3472:
3473: sub eget {
1.133 albertel 3474: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3475: my $items='';
1.800 albertel 3476: foreach my $item (@$storearr) {
3477: $items.=&escape($item).'&';
1.191 harris41 3478: }
1.12 www 3479: $items=~s/\&$//;
1.620 albertel 3480: if (!$udomain) { $udomain=$env{'user.domain'}; }
3481: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3482: my $uhome=&homeserver($uname,$udomain);
3483: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3484: my @pairs=split(/\&/,$rep);
3485: my %returnhash=();
1.42 www 3486: my $i=0;
1.800 albertel 3487: foreach my $item (@$storearr) {
3488: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3489: $i++;
1.191 harris41 3490: }
1.12 www 3491: return %returnhash;
3492: }
3493:
1.667 albertel 3494: # ------------------------------------------------------------ tmpput interface
3495: sub tmpput {
1.802 raeburn 3496: my ($storehash,$server,$context)=@_;
1.667 albertel 3497: my $items='';
1.800 albertel 3498: foreach my $item (keys(%$storehash)) {
3499: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3500: }
3501: $items=~s/\&$//;
1.802 raeburn 3502: if (defined($context)) {
3503: $items .= ':'.&escape($context);
3504: }
1.667 albertel 3505: return &reply("tmpput:$items",$server);
3506: }
3507:
3508: # ------------------------------------------------------------ tmpget interface
3509: sub tmpget {
1.688 albertel 3510: my ($token,$server)=@_;
3511: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3512: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3513: my %returnhash;
3514: foreach my $item (split(/\&/,$rep)) {
3515: my ($key,$value)=split(/=/,$item);
3516: $returnhash{&unescape($key)}=&thaw_unescape($value);
3517: }
3518: return %returnhash;
3519: }
3520:
1.688 albertel 3521: # ------------------------------------------------------------ tmpget interface
3522: sub tmpdel {
3523: my ($token,$server)=@_;
3524: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3525: return &reply("tmpdel:$token",$server);
3526: }
3527:
1.765 albertel 3528: # -------------------------------------------------- portfolio access checking
3529:
3530: sub portfolio_access {
1.766 albertel 3531: my ($requrl) = @_;
1.765 albertel 3532: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3533: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3534: if ($result) {
3535: my %setters;
3536: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3537: my ($startblock,$endblock) =
3538: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3539: if ($startblock && $endblock) {
3540: return 'B';
3541: }
3542: } else {
3543: my ($startblock,$endblock) =
3544: &Apache::loncommon::blockcheck(\%setters,'port');
3545: if ($startblock && $endblock) {
3546: return 'B';
3547: }
3548: }
3549: }
1.765 albertel 3550: if ($result eq 'ok') {
1.766 albertel 3551: return 'F';
1.765 albertel 3552: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3553: return 'A';
1.765 albertel 3554: }
1.766 albertel 3555: return '';
1.765 albertel 3556: }
3557:
3558: sub get_portfolio_access {
1.767 albertel 3559: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3560:
3561: if (!ref($access_hash)) {
3562: my $current_perms = &get_portfile_permissions($udom,$unum);
3563: my %access_controls = &get_access_controls($current_perms,$group,
3564: $file_name);
3565: $access_hash = $access_controls{$file_name};
3566: }
3567:
1.765 albertel 3568: my ($public,$guest,@domains,@users,@courses,@groups);
3569: my $now = time;
3570: if (ref($access_hash) eq 'HASH') {
3571: foreach my $key (keys(%{$access_hash})) {
3572: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3573: if ($start > $now) {
3574: next;
3575: }
3576: if ($end && $end<$now) {
3577: next;
3578: }
3579: if ($scope eq 'public') {
3580: $public = $key;
3581: last;
3582: } elsif ($scope eq 'guest') {
3583: $guest = $key;
3584: } elsif ($scope eq 'domains') {
3585: push(@domains,$key);
3586: } elsif ($scope eq 'users') {
3587: push(@users,$key);
3588: } elsif ($scope eq 'course') {
3589: push(@courses,$key);
3590: } elsif ($scope eq 'group') {
3591: push(@groups,$key);
3592: }
3593: }
3594: if ($public) {
3595: return 'ok';
3596: }
3597: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3598: if ($guest) {
3599: return $guest;
3600: }
3601: } else {
3602: if (@domains > 0) {
3603: foreach my $domkey (@domains) {
3604: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3605: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3606: return 'ok';
3607: }
3608: }
3609: }
3610: }
3611: if (@users > 0) {
3612: foreach my $userkey (@users) {
1.865 raeburn 3613: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3614: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3615: if (ref($item) eq 'HASH') {
3616: if (($item->{'uname'} eq $env{'user.name'}) &&
3617: ($item->{'udom'} eq $env{'user.domain'})) {
3618: return 'ok';
3619: }
3620: }
3621: }
3622: }
1.765 albertel 3623: }
3624: }
3625: my %roleshash;
3626: my @courses_and_groups = @courses;
3627: push(@courses_and_groups,@groups);
3628: if (@courses_and_groups > 0) {
3629: my (%allgroups,%allroles);
3630: my ($start,$end,$role,$sec,$group);
3631: foreach my $envkey (%env) {
1.811 albertel 3632: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3633: my $cid = $2.'_'.$3;
3634: if ($1 eq 'gr') {
3635: $group = $4;
3636: $allgroups{$cid}{$group} = $env{$envkey};
3637: } else {
3638: if ($4 eq '') {
3639: $sec = 'none';
3640: } else {
3641: $sec = $4;
3642: }
3643: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3644: }
1.811 albertel 3645: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3646: my $cid = $2.'_'.$3;
3647: if ($4 eq '') {
3648: $sec = 'none';
3649: } else {
3650: $sec = $4;
3651: }
3652: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3653: }
3654: }
3655: if (keys(%allroles) == 0) {
3656: return;
3657: }
3658: foreach my $key (@courses_and_groups) {
3659: my %content = %{$$access_hash{$key}};
3660: my $cnum = $content{'number'};
3661: my $cdom = $content{'domain'};
3662: my $cid = $cdom.'_'.$cnum;
3663: if (!exists($allroles{$cid})) {
3664: next;
3665: }
3666: foreach my $role_id (keys(%{$content{'roles'}})) {
3667: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3668: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3669: my @status = @{$content{'roles'}{$role_id}{'access'}};
3670: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3671: foreach my $role (keys(%{$allroles{$cid}})) {
3672: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3673: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3674: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3675: if (grep/^all$/,@sections) {
3676: return 'ok';
3677: } else {
3678: if (grep/^$sec$/,@sections) {
3679: return 'ok';
3680: }
3681: }
3682: }
3683: }
3684: if (keys(%{$allgroups{$cid}}) == 0) {
3685: if (grep/^none$/,@groups) {
3686: return 'ok';
3687: }
3688: } else {
3689: if (grep/^all$/,@groups) {
3690: return 'ok';
3691: }
3692: foreach my $group (keys(%{$allgroups{$cid}})) {
3693: if (grep/^$group$/,@groups) {
3694: return 'ok';
3695: }
3696: }
3697: }
3698: }
3699: }
3700: }
3701: }
3702: }
3703: if ($guest) {
3704: return $guest;
3705: }
3706: }
3707: }
3708: return;
3709: }
3710:
3711: sub course_group_datechecker {
3712: my ($dates,$now,$status) = @_;
3713: my ($start,$end) = split(/\./,$dates);
3714: if (!$start && !$end) {
3715: return 'ok';
3716: }
3717: if (grep/^active$/,@{$status}) {
3718: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3719: return 'ok';
3720: }
3721: }
3722: if (grep/^previous$/,@{$status}) {
3723: if ($end > $now ) {
3724: return 'ok';
3725: }
3726: }
3727: if (grep/^future$/,@{$status}) {
3728: if ($start > $now) {
3729: return 'ok';
3730: }
3731: }
3732: return;
3733: }
3734:
3735: sub parse_portfolio_url {
3736: my ($url) = @_;
3737:
3738: my ($type,$udom,$unum,$group,$file_name);
3739:
1.823 albertel 3740: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 3741: $type = 1;
3742: $udom = $1;
3743: $unum = $2;
3744: $file_name = $3;
1.823 albertel 3745: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 3746: $type = 2;
3747: $udom = $1;
3748: $unum = $2;
3749: $group = $3;
3750: $file_name = $3.'/'.$4;
3751: }
3752: if (wantarray) {
3753: return ($type,$udom,$unum,$file_name,$group);
3754: }
3755: return $type;
3756: }
3757:
3758: sub is_portfolio_url {
3759: my ($url) = @_;
3760: return scalar(&parse_portfolio_url($url));
3761: }
3762:
1.798 raeburn 3763: sub is_portfolio_file {
3764: my ($file) = @_;
1.820 raeburn 3765: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 3766: return 1;
3767: }
3768: return;
3769: }
3770:
3771:
1.341 www 3772: # ---------------------------------------------- Custom access rule evaluation
3773:
3774: sub customaccess {
3775: my ($priv,$uri)=@_;
1.807 albertel 3776: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 3777: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 3778: $udom = &LONCAPA::clean_domain($udom);
3779: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 3780: my $access=0;
1.800 albertel 3781: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3782: my ($effect,$realm,$role)=split(/\:/,$right);
1.343 www 3783: if ($role) {
3784: if ($role ne $urole) { next; }
3785: }
1.800 albertel 3786: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3787: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343 www 3788: if ($tdom) {
3789: if ($tdom ne $udom) { next; }
3790: }
3791: if ($tcrs) {
3792: if ($tcrs ne $ucrs) { next; }
3793: }
3794: if ($tsec) {
3795: if ($tsec ne $usec) { next; }
3796: }
3797: $access=($effect eq 'allow');
3798: last;
1.342 www 3799: }
1.402 bowersj2 3800: if ($realm eq '' && $role eq '') {
3801: $access=($effect eq 'allow');
3802: }
1.341 www 3803: }
3804: return $access;
3805: }
3806:
1.103 harris41 3807: # ------------------------------------------------- Check for a user privilege
1.12 www 3808:
3809: sub allowed {
1.810 raeburn 3810: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 3811: my $ver_orguri=$uri;
1.439 www 3812: $uri=&deversion($uri);
1.152 www 3813: my $orguri=$uri;
1.52 www 3814: $uri=&declutter($uri);
1.809 raeburn 3815:
1.810 raeburn 3816: if ($priv eq 'evb') {
3817: # Evade communication block restrictions for specified role in a course
3818: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3819: return $1;
3820: } else {
3821: return;
3822: }
3823: }
3824:
1.620 albertel 3825: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3826: # Free bre access to adm and meta resources
1.775 albertel 3827: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3828: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3829: && ($priv eq 'bre')) {
1.14 www 3830: return 'F';
1.159 www 3831: }
3832:
1.545 banghart 3833: # Free bre access to user's own portfolio contents
1.714 raeburn 3834: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3835: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3836: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 3837: my %setters;
3838: my ($startblock,$endblock) =
3839: &Apache::loncommon::blockcheck(\%setters,'port');
3840: if ($startblock && $endblock) {
3841: return 'B';
3842: } else {
3843: return 'F';
3844: }
1.545 banghart 3845: }
3846:
1.762 raeburn 3847: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3848: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3849: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3850: if (exists($env{'request.course.id'})) {
3851: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3852: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3853: if (($domain eq $cdom) && ($name eq $cnum)) {
3854: my $courseprivid=$env{'request.course.id'};
3855: $courseprivid=~s/\_/\//;
3856: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3857: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3858: return $1;
1.762 raeburn 3859: } else {
3860: if ($env{'request.course.sec'}) {
3861: $courseprivid.='/'.$env{'request.course.sec'};
3862: }
3863: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3864: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3865: return $2;
3866: }
1.714 raeburn 3867: }
3868: }
3869: }
3870: }
3871:
1.159 www 3872: # Free bre to public access
3873:
3874: if ($priv eq 'bre') {
1.238 www 3875: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3876: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3877: return 'F';
3878: }
1.238 www 3879: if ($copyright eq 'priv') {
3880: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3881: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3882: return '';
3883: }
3884: }
3885: if ($copyright eq 'domain') {
3886: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3887: unless (($env{'user.domain'} eq $1) ||
3888: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3889: return '';
3890: }
1.262 matthew 3891: }
1.620 albertel 3892: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3893: # Library role, so allow browsing of resources in this domain.
3894: return 'F';
1.238 www 3895: }
1.341 www 3896: if ($copyright eq 'custom') {
3897: unless (&customaccess($priv,$uri)) { return ''; }
3898: }
1.14 www 3899: }
1.264 matthew 3900: # Domain coordinator is trying to create a course
1.620 albertel 3901: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3902: # uri is the requested domain in this case.
3903: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3904: # a role of dc for the domain in question.
1.620 albertel 3905: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3906: }
1.29 www 3907:
1.52 www 3908: my $thisallowed='';
3909: my $statecond=0;
3910: my $courseprivid='';
3911:
3912: # Course
3913:
1.620 albertel 3914: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3915: $thisallowed.=$1;
3916: }
1.29 www 3917:
1.52 www 3918: # Domain
3919:
1.620 albertel 3920: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3921: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3922: $thisallowed.=$1;
3923: }
1.52 www 3924:
3925: # Course: uri itself is a course
1.66 www 3926: my $courseuri=$uri;
3927: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3928: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3929:
1.620 albertel 3930: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3931: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3932: $thisallowed.=$1;
3933: }
1.29 www 3934:
1.665 albertel 3935: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3936: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3937: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3938: $thisallowed='';
1.671 raeburn 3939: my ($match)=&is_on_map($uri);
3940: if ($match) {
3941: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3942: =~/\Q$priv\E\&([^\:]*)/) {
3943: $thisallowed.=$1;
3944: }
3945: } else {
1.705 albertel 3946: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3947: if ($refuri) {
3948: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3949: $thisallowed='F';
1.671 raeburn 3950: } else {
3951: $refuri=&declutter($refuri);
3952: my ($match) = &is_on_map($refuri);
3953: if ($match) {
3954: $thisallowed='F';
3955: }
1.669 raeburn 3956: }
1.671 raeburn 3957: }
3958: }
1.314 www 3959: }
1.492 albertel 3960:
1.766 albertel 3961: if ($priv eq 'bre'
3962: && $thisallowed ne 'F'
3963: && $thisallowed ne '2'
3964: && &is_portfolio_url($uri)) {
3965: $thisallowed = &portfolio_access($uri);
3966: }
3967:
1.52 www 3968: # Full access at system, domain or course-wide level? Exit.
1.29 www 3969:
3970: if ($thisallowed=~/F/) {
3971: return 'F';
3972: }
3973:
1.52 www 3974: # If this is generating or modifying users, exit with special codes
1.29 www 3975:
1.643 www 3976: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3977: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 3978: my ($audom,$auname)=split('/',$uri);
1.643 www 3979: # no author name given, so this just checks on the general right to make a co-author in this domain
3980: unless ($auname) { return $thisallowed; }
3981: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 3982: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3983: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3984: ($audom ne $env{'request.role.domain'}))) { return ''; }
3985: }
1.52 www 3986: return $thisallowed;
3987: }
3988: #
1.103 harris41 3989: # Gathered so far: system, domain and course wide privileges
1.52 www 3990: #
3991: # Course: See if uri or referer is an individual resource that is part of
3992: # the course
3993:
1.620 albertel 3994: if ($env{'request.course.id'}) {
1.232 www 3995:
1.620 albertel 3996: $courseprivid=$env{'request.course.id'};
3997: if ($env{'request.course.sec'}) {
3998: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 3999: }
4000: $courseprivid=~s/\_/\//;
4001: my $checkreferer=1;
1.232 www 4002: my ($match,$cond)=&is_on_map($uri);
4003: if ($match) {
4004: $statecond=$cond;
1.620 albertel 4005: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4006: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4007: $thisallowed.=$1;
4008: $checkreferer=0;
4009: }
1.29 www 4010: }
1.83 www 4011:
1.148 www 4012: if ($checkreferer) {
1.620 albertel 4013: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4014: unless ($refuri) {
1.800 albertel 4015: foreach my $key (keys(%env)) {
4016: if ($key=~/^httpref\..*\*/) {
4017: my $pattern=$key;
1.156 www 4018: $pattern=~s/^httpref\.\/res\///;
1.148 www 4019: $pattern=~s/\*/\[\^\/\]\+/g;
4020: $pattern=~s/\//\\\//g;
1.152 www 4021: if ($orguri=~/$pattern/) {
1.800 albertel 4022: $refuri=$env{$key};
1.148 www 4023: }
4024: }
1.191 harris41 4025: }
1.148 www 4026: }
1.232 www 4027:
1.148 www 4028: if ($refuri) {
1.152 www 4029: $refuri=&declutter($refuri);
1.232 www 4030: my ($match,$cond)=&is_on_map($refuri);
4031: if ($match) {
4032: my $refstatecond=$cond;
1.620 albertel 4033: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4034: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4035: $thisallowed.=$1;
1.53 www 4036: $uri=$refuri;
4037: $statecond=$refstatecond;
1.52 www 4038: }
4039: }
1.148 www 4040: }
1.29 www 4041: }
1.52 www 4042: }
1.29 www 4043:
1.52 www 4044: #
1.103 harris41 4045: # Gathered now: all privileges that could apply, and condition number
1.52 www 4046: #
4047: #
4048: # Full or no access?
4049: #
1.29 www 4050:
1.52 www 4051: if ($thisallowed=~/F/) {
4052: return 'F';
4053: }
1.29 www 4054:
1.52 www 4055: unless ($thisallowed) {
4056: return '';
4057: }
1.29 www 4058:
1.52 www 4059: # Restrictions exist, deal with them
4060: #
4061: # C:according to course preferences
4062: # R:according to resource settings
4063: # L:unless locked
4064: # X:according to user session state
4065: #
4066:
4067: # Possibly locked functionality, check all courses
1.54 www 4068: # Locks might take effect only after 10 minutes cache expiration for other
4069: # courses, and 2 minutes for current course
1.52 www 4070:
4071: my $envkey;
4072: if ($thisallowed=~/L/) {
1.620 albertel 4073: foreach $envkey (keys %env) {
1.54 www 4074: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4075: my $courseid=$2;
4076: my $roleid=$1.'.'.$2;
1.92 www 4077: $courseid=~s/^\///;
1.54 www 4078: my $expiretime=600;
1.620 albertel 4079: if ($env{'request.role'} eq $roleid) {
1.54 www 4080: $expiretime=120;
4081: }
4082: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4083: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4084: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4085: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4086: }
1.620 albertel 4087: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4088: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4089: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4090: &log($env{'user.domain'},$env{'user.name'},
4091: $env{'user.home'},
1.57 www 4092: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4093: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4094: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4095: return '';
4096: }
4097: }
1.620 albertel 4098: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4099: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4100: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4101: &log($env{'user.domain'},$env{'user.name'},
4102: $env{'user.home'},
1.57 www 4103: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4104: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4105: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4106: return '';
4107: }
4108: }
4109: }
1.29 www 4110: }
1.52 www 4111: }
4112:
4113: #
4114: # Rest of the restrictions depend on selected course
4115: #
4116:
1.620 albertel 4117: unless ($env{'request.course.id'}) {
1.766 albertel 4118: if ($thisallowed eq 'A') {
4119: return 'A';
1.814 raeburn 4120: } elsif ($thisallowed eq 'B') {
4121: return 'B';
1.766 albertel 4122: } else {
4123: return '1';
4124: }
1.52 www 4125: }
1.29 www 4126:
1.52 www 4127: #
4128: # Now user is definitely in a course
4129: #
1.53 www 4130:
4131:
4132: # Course preferences
4133:
4134: if ($thisallowed=~/C/) {
1.620 albertel 4135: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4136: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4137: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4138: =~/\Q$rolecode\E/) {
1.689 albertel 4139: if ($priv ne 'pch') {
4140: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4141: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4142: $env{'request.course.id'});
4143: }
1.237 www 4144: return '';
4145: }
4146:
1.620 albertel 4147: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4148: =~/\Q$unamedom\E/) {
1.689 albertel 4149: if ($priv ne 'pch') {
4150: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4151: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4152: $env{'request.course.id'});
4153: }
1.54 www 4154: return '';
4155: }
1.53 www 4156: }
4157:
4158: # Resource preferences
4159:
4160: if ($thisallowed=~/R/) {
1.620 albertel 4161: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4162: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4163: if ($priv ne 'pch') {
4164: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4165: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4166: }
4167: return '';
1.54 www 4168: }
1.53 www 4169: }
1.30 www 4170:
1.246 www 4171: # Restricted by state or randomout?
1.30 www 4172:
1.52 www 4173: if ($thisallowed=~/X/) {
1.620 albertel 4174: if ($env{'acc.randomout'}) {
1.579 albertel 4175: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4176: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4177: return '';
4178: }
1.247 www 4179: }
4180: if (&condval($statecond)) {
1.52 www 4181: return '2';
4182: } else {
4183: return '';
4184: }
4185: }
1.30 www 4186:
1.766 albertel 4187: if ($thisallowed eq 'A') {
4188: return 'A';
1.814 raeburn 4189: } elsif ($thisallowed eq 'B') {
4190: return 'B';
1.766 albertel 4191: }
1.52 www 4192: return 'F';
1.232 www 4193: }
4194:
1.710 albertel 4195: sub split_uri_for_cond {
4196: my $uri=&deversion(&declutter(shift));
4197: my @uriparts=split(/\//,$uri);
4198: my $filename=pop(@uriparts);
4199: my $pathname=join('/',@uriparts);
4200: return ($pathname,$filename);
4201: }
1.232 www 4202: # --------------------------------------------------- Is a resource on the map?
4203:
4204: sub is_on_map {
1.710 albertel 4205: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4206: #Trying to find the conditional for the file
1.620 albertel 4207: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4208: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4209: if ($match) {
1.289 bowersj2 4210: return (1,$1);
4211: } else {
1.434 www 4212: return (0,0);
1.289 bowersj2 4213: }
1.12 www 4214: }
4215:
1.427 www 4216: # --------------------------------------------------------- Get symb from alias
4217:
4218: sub get_symb_from_alias {
4219: my $symb=shift;
4220: my ($map,$resid,$url)=&decode_symb($symb);
4221: # Already is a symb
4222: if ($url) { return $symb; }
4223: # Must be an alias
4224: my $aliassymb='';
4225: my %bighash;
1.620 albertel 4226: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4227: &GDBM_READER(),0640)) {
4228: my $rid=$bighash{'mapalias_'.$symb};
4229: if ($rid) {
4230: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4231: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4232: $resid,$bighash{'src_'.$rid});
1.427 www 4233: }
4234: untie %bighash;
4235: }
4236: return $aliassymb;
4237: }
4238:
1.12 www 4239: # ----------------------------------------------------------------- Define Role
4240:
4241: sub definerole {
4242: if (allowed('mcr','/')) {
4243: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4244: foreach my $role (split(':',$sysrole)) {
4245: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4246: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4247: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4248: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4249: return "refused:s:$crole&$cqual";
4250: }
4251: }
1.191 harris41 4252: }
1.800 albertel 4253: foreach my $role (split(':',$domrole)) {
4254: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4255: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4256: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4257: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4258: return "refused:d:$crole&$cqual";
4259: }
4260: }
1.191 harris41 4261: }
1.800 albertel 4262: foreach my $role (split(':',$courole)) {
4263: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4264: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4265: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4266: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4267: return "refused:c:$crole&$cqual";
4268: }
4269: }
1.191 harris41 4270: }
1.620 albertel 4271: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4272: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4273: "rolesdef_$rolename=".
4274: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4275: return reply($command,$env{'user.home'});
1.12 www 4276: } else {
4277: return 'refused';
4278: }
1.105 harris41 4279: }
4280:
4281: # ---------------- Make a metadata query against the network of library servers
4282:
4283: sub metadata_query {
1.244 matthew 4284: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4285: my %rhash;
1.845 albertel 4286: my %libserv = &all_library();
1.244 matthew 4287: my @server_list = (defined($server_array) ? @$server_array
4288: : keys(%libserv) );
4289: for my $server (@server_list) {
1.118 harris41 4290: unless ($custom or $customshow) {
4291: my $reply=&reply("querysend:".&escape($query),$server);
4292: $rhash{$server}=$reply;
4293: }
4294: else {
4295: my $reply=&reply("querysend:".&escape($query).':'.
4296: &escape($custom).':'.&escape($customshow),
4297: $server);
4298: $rhash{$server}=$reply;
4299: }
1.112 harris41 4300: }
1.118 harris41 4301: return \%rhash;
1.240 www 4302: }
4303:
4304: # ----------------------------------------- Send log queries and wait for reply
4305:
4306: sub log_query {
4307: my ($uname,$udom,$query,%filters)=@_;
4308: my $uhome=&homeserver($uname,$udom);
4309: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4310: my $uhost=&hostname($uhome);
1.800 albertel 4311: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4312: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4313: $uhome);
1.479 albertel 4314: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4315: return get_query_reply($queryid);
4316: }
4317:
1.818 raeburn 4318: # -------------------------- Update MySQL table for portfolio file
4319:
4320: sub update_portfolio_table {
1.821 raeburn 4321: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4322: my $homeserver = &homeserver($uname,$udom);
4323: my $queryid=
1.821 raeburn 4324: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4325: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4326: my $reply = &get_query_reply($queryid);
4327: return $reply;
4328: }
4329:
1.508 raeburn 4330: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4331:
4332: sub fetch_enrollment_query {
1.511 raeburn 4333: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4334: my $homeserver;
1.547 raeburn 4335: my $maxtries = 1;
1.508 raeburn 4336: if ($context eq 'automated') {
4337: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4338: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4339: } else {
4340: $homeserver = &homeserver($cnum,$dom);
4341: }
1.838 albertel 4342: my $host=&hostname($homeserver);
1.506 raeburn 4343: my $cmd = '';
1.800 albertel 4344: foreach my $affiliate (keys %{$affiliatesref}) {
4345: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4346: }
4347: $cmd =~ s/%%$//;
4348: $cmd = &escape($cmd);
4349: my $query = 'fetchenrollment';
1.620 albertel 4350: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4351: unless ($queryid=~/^\Q$host\E\_/) {
4352: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4353: return 'error: '.$queryid;
4354: }
1.506 raeburn 4355: my $reply = &get_query_reply($queryid);
1.547 raeburn 4356: my $tries = 1;
4357: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4358: $reply = &get_query_reply($queryid);
4359: $tries ++;
4360: }
1.526 raeburn 4361: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4362: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4363: } else {
1.515 raeburn 4364: my @responses = split/:/,$reply;
4365: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4366: foreach my $line (@responses) {
4367: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4368: $$replyref{$key} = $value;
4369: }
4370: } else {
1.506 raeburn 4371: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4372: foreach my $line (@responses) {
4373: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4374: $$replyref{$key} = $value;
4375: if ($value > 0) {
1.800 albertel 4376: foreach my $item (@{$$affiliatesref{$key}}) {
4377: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4378: my $destname = $pathname.'/'.$filename;
4379: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4380: if ($xml_classlist =~ /^error/) {
4381: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4382: } else {
1.506 raeburn 4383: if ( open(FILE,">$destname") ) {
4384: print FILE &unescape($xml_classlist);
4385: close(FILE);
1.526 raeburn 4386: } else {
4387: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4388: }
4389: }
4390: }
4391: }
4392: }
4393: }
4394: return 'ok';
4395: }
4396: return 'error';
4397: }
4398:
1.242 www 4399: sub get_query_reply {
4400: my $queryid=shift;
1.240 www 4401: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4402: my $reply='';
4403: for (1..100) {
4404: sleep 2;
4405: if (-e $replyfile.'.end') {
1.448 albertel 4406: if (open(my $fh,$replyfile)) {
1.240 www 4407: $reply.=<$fh>;
1.448 albertel 4408: close($fh);
1.240 www 4409: } else { return 'error: reply_file_error'; }
1.242 www 4410: return &unescape($reply);
4411: }
1.240 www 4412: }
1.242 www 4413: return 'timeout:'.$queryid;
1.240 www 4414: }
4415:
4416: sub courselog_query {
1.241 www 4417: #
4418: # possible filters:
4419: # url: url or symb
4420: # username
4421: # domain
4422: # action: view, submit, grade
4423: # start: timestamp
4424: # end: timestamp
4425: #
1.240 www 4426: my (%filters)=@_;
1.620 albertel 4427: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4428: if ($filters{'url'}) {
4429: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4430: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4431: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4432: }
1.620 albertel 4433: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4434: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4435: return &log_query($cname,$cdom,'courselog',%filters);
4436: }
4437:
4438: sub userlog_query {
1.858 raeburn 4439: #
4440: # possible filters:
4441: # action: log check role
4442: # start: timestamp
4443: # end: timestamp
4444: #
1.240 www 4445: my ($uname,$udom,%filters)=@_;
4446: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4447: }
4448:
1.506 raeburn 4449: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4450:
4451: sub auto_run {
1.508 raeburn 4452: my ($cnum,$cdom) = @_;
4453: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4454: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4455: return $response;
4456: }
1.776 albertel 4457:
1.506 raeburn 4458: sub auto_get_sections {
1.508 raeburn 4459: my ($cnum,$cdom,$inst_coursecode) = @_;
4460: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4461: my @secs = ();
1.511 raeburn 4462: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4463: unless ($response eq 'refused') {
4464: @secs = split/:/,$response;
4465: }
4466: return @secs;
4467: }
1.776 albertel 4468:
1.506 raeburn 4469: sub auto_new_course {
1.508 raeburn 4470: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4471: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4472: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4473: return $response;
4474: }
1.776 albertel 4475:
1.506 raeburn 4476: sub auto_validate_courseID {
1.508 raeburn 4477: my ($cnum,$cdom,$inst_course_id) = @_;
4478: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4479: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4480: return $response;
4481: }
1.776 albertel 4482:
1.506 raeburn 4483: sub auto_create_password {
1.508 raeburn 4484: my ($cnum,$cdom,$authparam) = @_;
4485: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4486: my $create_passwd = 0;
4487: my $authchk = '';
1.511 raeburn 4488: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4489: if ($response eq 'refused') {
4490: $authchk = 'refused';
4491: } else {
4492: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4493: }
4494: return ($authparam,$create_passwd,$authchk);
4495: }
4496:
1.706 raeburn 4497: sub auto_photo_permission {
4498: my ($cnum,$cdom,$students) = @_;
4499: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4500: my ($outcome,$perm_reqd,$conditions) =
4501: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4502: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4503: return (undef,undef);
4504: }
1.706 raeburn 4505: return ($outcome,$perm_reqd,$conditions);
4506: }
4507:
4508: sub auto_checkphotos {
4509: my ($uname,$udom,$pid) = @_;
4510: my $homeserver = &homeserver($uname,$udom);
4511: my ($result,$resulttype);
4512: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4513: &escape($uname).':'.&escape($pid),
4514: $homeserver));
1.709 albertel 4515: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4516: return (undef,undef);
4517: }
1.706 raeburn 4518: if ($outcome) {
4519: ($result,$resulttype) = split(/:/,$outcome);
4520: }
4521: return ($result,$resulttype);
4522: }
4523:
4524: sub auto_photochoice {
4525: my ($cnum,$cdom) = @_;
4526: my $homeserver = &homeserver($cnum,$cdom);
4527: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4528: &escape($cdom),
4529: $homeserver)));
1.709 albertel 4530: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4531: return (undef,undef);
4532: }
1.706 raeburn 4533: return ($update,$comment);
4534: }
4535:
4536: sub auto_photoupdate {
4537: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4538: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4539: my $host=&hostname($homeserver);
1.706 raeburn 4540: my $cmd = '';
4541: my $maxtries = 1;
1.800 albertel 4542: foreach my $affiliate (keys(%{$affiliatesref})) {
4543: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4544: }
4545: $cmd =~ s/%%$//;
4546: $cmd = &escape($cmd);
4547: my $query = 'institutionalphotos';
4548: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4549: unless ($queryid=~/^\Q$host\E\_/) {
4550: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4551: return 'error: '.$queryid;
4552: }
4553: my $reply = &get_query_reply($queryid);
4554: my $tries = 1;
4555: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4556: $reply = &get_query_reply($queryid);
4557: $tries ++;
4558: }
4559: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4560: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4561: } else {
4562: my @responses = split(/:/,$reply);
4563: my $outcome = shift(@responses);
4564: foreach my $item (@responses) {
4565: my ($key,$value) = split(/=/,$item);
4566: $$photo{$key} = $value;
4567: }
4568: return $outcome;
4569: }
4570: return 'error';
4571: }
4572:
1.521 raeburn 4573: sub auto_instcode_format {
1.793 albertel 4574: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4575: $cat_order) = @_;
1.521 raeburn 4576: my $courses = '';
1.772 raeburn 4577: my @homeservers;
1.521 raeburn 4578: if ($caller eq 'global') {
1.841 albertel 4579: my %servers = &get_servers($codedom,'library');
4580: foreach my $tryserver (keys(%servers)) {
4581: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4582: push(@homeservers,$tryserver);
4583: }
1.584 raeburn 4584: }
1.521 raeburn 4585: } else {
1.772 raeburn 4586: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4587: }
1.793 albertel 4588: foreach my $code (keys(%{$instcodes})) {
4589: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4590: }
4591: chop($courses);
1.772 raeburn 4592: my $ok_response = 0;
4593: my $response;
4594: while (@homeservers > 0 && $ok_response == 0) {
4595: my $server = shift(@homeservers);
4596: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4597: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4598: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.793 albertel 4599: split/:/,$response;
1.772 raeburn 4600: %{$codes} = (%{$codes},&str2hash($codes_str));
4601: push(@{$codetitles},&str2array($codetitles_str));
4602: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4603: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4604: $ok_response = 1;
4605: }
4606: }
4607: if ($ok_response) {
1.521 raeburn 4608: return 'ok';
1.772 raeburn 4609: } else {
4610: return $response;
1.521 raeburn 4611: }
4612: }
4613:
1.792 raeburn 4614: sub auto_instcode_defaults {
4615: my ($domain,$returnhash,$code_order) = @_;
4616: my @homeservers;
1.841 albertel 4617:
4618: my %servers = &get_servers($domain,'library');
4619: foreach my $tryserver (keys(%servers)) {
4620: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4621: push(@homeservers,$tryserver);
4622: }
1.792 raeburn 4623: }
1.841 albertel 4624:
1.792 raeburn 4625: my $response;
1.841 albertel 4626: foreach my $server (@homeservers) {
1.792 raeburn 4627: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 4628: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4629:
4630: foreach my $pair (split(/\&/,$response)) {
4631: my ($name,$value)=split(/\=/,$pair);
4632: if ($name eq 'code_order') {
4633: @{$code_order} = split(/\&/,&unescape($value));
4634: } else {
4635: $returnhash->{&unescape($name)}=&unescape($value);
4636: }
4637: }
4638: return 'ok';
1.792 raeburn 4639: }
1.841 albertel 4640:
4641: return $response;
1.792 raeburn 4642: }
4643:
1.777 albertel 4644: sub auto_validate_class_sec {
1.773 raeburn 4645: my ($cdom,$cnum,$owner,$inst_class) = @_;
4646: my $homeserver = &homeserver($cnum,$cdom);
4647: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4648: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4649: return $response;
4650: }
4651:
1.679 raeburn 4652: # ------------------------------------------------------- Course Group routines
4653:
4654: sub get_coursegroups {
1.809 raeburn 4655: my ($cdom,$cnum,$group,$namespace) = @_;
4656: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 4657: }
4658:
1.679 raeburn 4659: sub modify_coursegroup {
4660: my ($cdom,$cnum,$groupsettings) = @_;
4661: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4662: }
4663:
1.809 raeburn 4664: sub toggle_coursegroup_status {
4665: my ($cdom,$cnum,$group,$action) = @_;
4666: my ($from_namespace,$to_namespace);
4667: if ($action eq 'delete') {
4668: $from_namespace = 'coursegroups';
4669: $to_namespace = 'deleted_groups';
4670: } else {
4671: $from_namespace = 'deleted_groups';
4672: $to_namespace = 'coursegroups';
4673: }
4674: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 4675: if (my $tmp = &error(%curr_group)) {
4676: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4677: return ('read error',$tmp);
4678: } else {
4679: my %savedsettings = %curr_group;
1.809 raeburn 4680: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 4681: my $deloutcome;
4682: if ($result eq 'ok') {
1.809 raeburn 4683: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 4684: } else {
4685: return ('write error',$result);
4686: }
4687: if ($deloutcome eq 'ok') {
4688: return 'ok';
4689: } else {
4690: return ('delete error',$deloutcome);
4691: }
4692: }
4693: }
4694:
1.679 raeburn 4695: sub modify_group_roles {
4696: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4697: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4698: my $role = 'gr/'.&escape($userprivs);
4699: my ($uname,$udom) = split(/:/,$user);
4700: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4701: if ($result eq 'ok') {
4702: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4703: }
1.679 raeburn 4704: return $result;
4705: }
4706:
4707: sub modify_coursegroup_membership {
4708: my ($cdom,$cnum,$membership) = @_;
4709: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4710: return $result;
4711: }
4712:
1.682 raeburn 4713: sub get_active_groups {
4714: my ($udom,$uname,$cdom,$cnum) = @_;
4715: my $now = time;
4716: my %groups = ();
4717: foreach my $key (keys(%env)) {
1.811 albertel 4718: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 4719: my ($start,$end) = split(/\./,$env{$key});
4720: if (($end!=0) && ($end<$now)) { next; }
4721: if (($start!=0) && ($start>$now)) { next; }
4722: if ($1 eq $cdom && $2 eq $cnum) {
4723: $groups{$3} = $env{$key} ;
4724: }
4725: }
4726: }
4727: return %groups;
4728: }
4729:
1.683 raeburn 4730: sub get_group_membership {
4731: my ($cdom,$cnum,$group) = @_;
4732: return(&dump('groupmembership',$cdom,$cnum,$group));
4733: }
4734:
4735: sub get_users_groups {
4736: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4737: my @usersgroups;
1.683 raeburn 4738: my $cachetime=1800;
4739:
4740: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4741: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4742: if (defined($cached)) {
1.734 albertel 4743: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4744: } else {
4745: $grouplist = '';
1.816 raeburn 4746: my $courseurl = &courseid_to_courseurl($courseid);
4747: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 4748: my $access_end = $env{'course.'.$courseid.
4749: '.default_enrollment_end_date'};
4750: my $now = time;
4751: foreach my $key (keys(%roleshash)) {
4752: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4753: my $group = $1;
4754: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4755: my $start = $2;
4756: my $end = $1;
4757: if ($start == -1) { next; } # deleted from group
4758: if (($start!=0) && ($start>$now)) { next; }
4759: if (($end!=0) && ($end<$now)) {
4760: if ($access_end && $access_end < $now) {
4761: if ($access_end - $end < 86400) {
4762: push(@usersgroups,$group);
1.733 raeburn 4763: }
4764: }
1.817 raeburn 4765: next;
1.733 raeburn 4766: }
1.817 raeburn 4767: push(@usersgroups,$group);
1.683 raeburn 4768: }
4769: }
4770: }
1.817 raeburn 4771: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4772: $grouplist = join(':',@usersgroups);
4773: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4774: }
1.733 raeburn 4775: return @usersgroups;
1.683 raeburn 4776: }
4777:
4778: sub devalidate_getgroups_cache {
4779: my ($udom,$uname,$cdom,$cnum)=@_;
4780: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 4781:
1.683 raeburn 4782: my $hashid="$udom:$uname:$courseid";
4783: &devalidate_cache_new('getgroups',$hashid);
4784: }
4785:
1.12 www 4786: # ------------------------------------------------------------------ Plain Text
4787:
4788: sub plaintext {
1.742 raeburn 4789: my ($short,$type,$cid) = @_;
1.758 albertel 4790: if ($short =~ /^cr/) {
4791: return (split('/',$short))[-1];
4792: }
1.742 raeburn 4793: if (!defined($cid)) {
4794: $cid = $env{'request.course.id'};
4795: }
4796: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4797: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4798: '.plaintext'});
4799: }
4800: my %rolenames = (
4801: Course => 'std',
4802: Group => 'alt1',
4803: );
4804: if (defined($type) &&
4805: defined($rolenames{$type}) &&
4806: defined($prp{$short}{$rolenames{$type}})) {
4807: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4808: } else {
4809: return &Apache::lonlocal::mt($prp{$short}{'std'});
4810: }
1.12 www 4811: }
4812:
4813: # ----------------------------------------------------------------- Assign Role
4814:
4815: sub assignrole {
1.357 www 4816: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4817: my $mrole;
4818: if ($role =~ /^cr\//) {
1.393 www 4819: my $cwosec=$url;
1.811 albertel 4820: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 4821: unless (&allowed('ccr',$cwosec)) {
1.104 www 4822: &logthis('Refused custom assignrole: '.
4823: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4824: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4825: return 'refused';
4826: }
1.21 www 4827: $mrole='cr';
1.678 raeburn 4828: } elsif ($role =~ /^gr\//) {
4829: my $cwogrp=$url;
1.811 albertel 4830: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 4831: unless (&allowed('mdg',$cwogrp)) {
4832: &logthis('Refused group assignrole: '.
4833: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4834: $env{'user.name'}.' at '.$env{'user.domain'});
4835: return 'refused';
4836: }
4837: $mrole='gr';
1.21 www 4838: } else {
1.82 www 4839: my $cwosec=$url;
1.811 albertel 4840: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 4841: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4842: &logthis('Refused assignrole: '.
4843: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4844: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4845: return 'refused';
4846: }
1.21 www 4847: $mrole=$role;
4848: }
1.620 albertel 4849: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4850: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4851: if ($end) { $command.='_'.$end; }
1.21 www 4852: if ($start) {
4853: if ($end) {
1.81 www 4854: $command.='_'.$start;
1.21 www 4855: } else {
1.81 www 4856: $command.='_0_'.$start;
1.21 www 4857: }
4858: }
1.739 raeburn 4859: my $origstart = $start;
4860: my $origend = $end;
1.357 www 4861: # actually delete
4862: if ($deleteflag) {
1.373 www 4863: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4864: # modify command to delete the role
1.620 albertel 4865: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4866: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4867: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4868: # set start and finish to negative values for userrolelog
4869: $start=-1;
4870: $end=-1;
4871: }
4872: }
4873: # send command
1.349 www 4874: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4875: # log new user role if status is ok
1.349 www 4876: if ($answer eq 'ok') {
1.663 raeburn 4877: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4878: # for course roles, perform group memberships changes triggered by role change.
4879: unless ($role =~ /^gr/) {
4880: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4881: $origstart);
4882: }
1.349 www 4883: }
4884: return $answer;
1.169 harris41 4885: }
4886:
4887: # -------------------------------------------------- Modify user authentication
1.197 www 4888: # Overrides without validation
4889:
1.169 harris41 4890: sub modifyuserauth {
4891: my ($udom,$uname,$umode,$upass)=@_;
4892: my $uhome=&homeserver($uname,$udom);
1.197 www 4893: unless (&allowed('mau',$udom)) { return 'refused'; }
4894: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4895: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4896: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4897: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4898: &escape($upass),$uhome);
1.620 albertel 4899: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4900: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4901: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4902: &log($udom,,$uname,$uhome,
1.620 albertel 4903: 'Authentication changed by '.$env{'user.domain'}.', '.
4904: $env{'user.name'}.', '.$umode.
1.197 www 4905: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4906: unless ($reply eq 'ok') {
1.197 www 4907: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4908: return 'error: '.$reply;
4909: }
1.170 harris41 4910: return 'ok';
1.80 www 4911: }
4912:
1.81 www 4913: # --------------------------------------------------------------- Modify a user
1.80 www 4914:
1.81 www 4915: sub modifyuser {
1.206 matthew 4916: my ($udom, $uname, $uid,
4917: $umode, $upass, $first,
4918: $middle, $last, $gene,
1.387 www 4919: $forceid, $desiredhome, $email)=@_;
1.807 albertel 4920: $udom= &LONCAPA::clean_domain($udom);
4921: $uname=&LONCAPA::clean_username($uname);
1.81 www 4922: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4923: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4924: $last.', '.$gene.'(forceid: '.$forceid.')'.
4925: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4926: ' desiredhome not specified').
1.620 albertel 4927: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4928: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4929: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4930: # ----------------------------------------------------------------- Create User
1.406 albertel 4931: if (($uhome eq 'no_host') &&
4932: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4933: my $unhome='';
1.844 albertel 4934: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 4935: $unhome = $desiredhome;
1.620 albertel 4936: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4937: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4938: } else { # load balancing routine for determining $unhome
1.81 www 4939: my $loadm=10000000;
1.841 albertel 4940: my %servers = &get_servers($udom,'library');
4941: foreach my $tryserver (keys(%servers)) {
4942: my $answer=reply('load',$tryserver);
4943: if (($answer=~/\d+/) && ($answer<$loadm)) {
4944: $loadm=$answer;
4945: $unhome=$tryserver;
4946: }
1.80 www 4947: }
4948: }
4949: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4950: return 'error: unable to find a home server for '.$uname.
4951: ' in domain '.$udom;
1.80 www 4952: }
4953: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4954: &escape($upass),$unhome);
4955: unless ($reply eq 'ok') {
4956: return 'error: '.$reply;
4957: }
1.230 stredwic 4958: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4959: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4960: return 'error: unable verify users home machine.';
1.80 www 4961: }
1.209 matthew 4962: } # End of creation of new user
1.80 www 4963: # ---------------------------------------------------------------------- Add ID
4964: if ($uid) {
4965: $uid=~tr/A-Z/a-z/;
4966: my %uidhash=&idrget($udom,$uname);
1.196 www 4967: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4968: && (!$forceid)) {
1.80 www 4969: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4970: return 'error: user id "'.$uid.'" does not match '.
4971: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4972: }
4973: } else {
4974: &idput($udom,($uname => $uid));
4975: }
4976: }
4977: # -------------------------------------------------------------- Add names, etc
1.313 matthew 4978: my @tmp=&get('environment',
1.134 albertel 4979: ['firstname','middlename','lastname','generation'],
4980: $udom,$uname);
1.313 matthew 4981: my %names;
4982: if ($tmp[0] =~ m/^error:.*/) {
4983: %names=();
4984: } else {
4985: %names = @tmp;
4986: }
1.388 www 4987: #
4988: # Make sure to not trash student environment if instructor does not bother
4989: # to supply name and email information
4990: #
4991: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 4992: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 4993: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 4994: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 4995: if ($email) {
4996: $email=~s/[^\w\@\.\-\,]//gs;
4997: if ($email=~/\@/) { $names{'notification'} = $email;
4998: $names{'critnotification'} = $email;
4999: $names{'permanentemail'} = $email; }
5000: }
1.134 albertel 5001: my $reply = &put('environment', \%names, $udom,$uname);
5002: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 5003: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5004: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5005: $umode.', '.$first.', '.$middle.', '.
5006: $last.', '.$gene.' by '.
1.620 albertel 5007: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5008: return 'ok';
1.80 www 5009: }
5010:
1.81 www 5011: # -------------------------------------------------------------- Modify student
1.80 www 5012:
1.81 www 5013: sub modifystudent {
5014: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5015: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5016: if (!$cid) {
1.620 albertel 5017: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5018: return 'not_in_class';
5019: }
1.80 www 5020: }
5021: # --------------------------------------------------------------- Make the user
1.81 www 5022: my $reply=&modifyuser
1.209 matthew 5023: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5024: $desiredhome,$email);
1.80 www 5025: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5026: # This will cause &modify_student_enrollment to get the uid from the
5027: # students environment
5028: $uid = undef if (!$forceid);
1.455 albertel 5029: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5030: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5031: return $reply;
5032: }
5033:
5034: sub modify_student_enrollment {
1.515 raeburn 5035: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5036: my ($cdom,$cnum,$chome);
5037: if (!$cid) {
1.620 albertel 5038: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5039: return 'not_in_class';
5040: }
1.620 albertel 5041: $cdom=$env{'course.'.$cid.'.domain'};
5042: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5043: } else {
5044: ($cdom,$cnum)=split(/_/,$cid);
5045: }
1.620 albertel 5046: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5047: if (!$chome) {
1.457 raeburn 5048: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5049: }
1.455 albertel 5050: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5051: # Make sure the user exists
1.81 www 5052: my $uhome=&homeserver($uname,$udom);
5053: if (($uhome eq '') || ($uhome eq 'no_host')) {
5054: return 'error: no such user';
5055: }
1.297 matthew 5056: # Get student data if we were not given enough information
5057: if (!defined($first) || $first eq '' ||
5058: !defined($last) || $last eq '' ||
5059: !defined($uid) || $uid eq '' ||
5060: !defined($middle) || $middle eq '' ||
5061: !defined($gene) || $gene eq '') {
1.294 matthew 5062: # They did not supply us with enough data to enroll the student, so
5063: # we need to pick up more information.
1.297 matthew 5064: my %tmp = &get('environment',
1.294 matthew 5065: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5066: ,$udom,$uname);
5067:
1.800 albertel 5068: #foreach my $key (keys(%tmp)) {
5069: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5070: #}
1.294 matthew 5071: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5072: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5073: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5074: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5075: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5076: }
1.556 albertel 5077: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5078: my $reply=cput('classlist',
5079: {"$uname:$udom" =>
1.515 raeburn 5080: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5081: $cdom,$cnum);
1.81 www 5082: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5083: return 'error: '.$reply;
1.652 albertel 5084: } else {
5085: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5086: }
1.297 matthew 5087: # Add student role to user
1.83 www 5088: my $uurl='/'.$cid;
1.81 www 5089: $uurl=~s/\_/\//g;
5090: if ($usec) {
5091: $uurl.='/'.$usec;
5092: }
5093: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5094: }
5095:
1.556 albertel 5096: sub format_name {
5097: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5098: my $name;
5099: if ($first ne 'lastname') {
5100: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5101: } else {
5102: if ($lastname=~/\S/) {
5103: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5104: $name=~s/\s+,/,/;
5105: } else {
5106: $name.= $firstname.' '.$middlename.' '.$generation;
5107: }
5108: }
5109: $name=~s/^\s+//;
5110: $name=~s/\s+$//;
5111: $name=~s/\s+/ /g;
5112: return $name;
5113: }
5114:
1.84 www 5115: # ------------------------------------------------- Write to course preferences
5116:
5117: sub writecoursepref {
5118: my ($courseid,%prefs)=@_;
5119: $courseid=~s/^\///;
5120: $courseid=~s/\_/\//g;
5121: my ($cdomain,$cnum)=split(/\//,$courseid);
5122: my $chome=homeserver($cnum,$cdomain);
5123: if (($chome eq '') || ($chome eq 'no_host')) {
5124: return 'error: no such course';
5125: }
5126: my $cstring='';
1.800 albertel 5127: foreach my $pref (keys(%prefs)) {
5128: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5129: }
1.84 www 5130: $cstring=~s/\&$//;
5131: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5132: }
5133:
5134: # ---------------------------------------------------------- Make/modify course
5135:
5136: sub createcourse {
1.741 raeburn 5137: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5138: $course_owner,$crstype)=@_;
1.84 www 5139: $url=&declutter($url);
5140: my $cid='';
1.264 matthew 5141: unless (&allowed('ccc',$udom)) {
1.84 www 5142: return 'refused';
5143: }
5144: # ------------------------------------------------------------------- Create ID
1.674 www 5145: my $uname=int(1+rand(9)).
5146: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5147: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5148: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5149: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5150: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5151: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5152: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5153: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5154: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5155: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5156: return 'error: unable to generate unique course-ID';
5157: }
5158: }
1.264 matthew 5159: # ------------------------------------------------ Check supplied server name
1.620 albertel 5160: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5161: if (! &is_library($course_server)) {
1.264 matthew 5162: return 'error:bad server name '.$course_server;
5163: }
1.84 www 5164: # ------------------------------------------------------------- Make the course
5165: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5166: $course_server);
1.84 www 5167: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5168: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5169: if (($uhome eq '') || ($uhome eq 'no_host')) {
5170: return 'error: no such course';
5171: }
1.271 www 5172: # ----------------------------------------------------------------- Course made
1.516 raeburn 5173: # log existence
5174: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 5175: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5176: &escape($crstype),$uhome);
1.358 www 5177: &flushcourselogs();
5178: # set toplevel url
1.271 www 5179: my $topurl=$url;
5180: unless ($nonstandard) {
5181: # ------------------------------------------ For standard courses, make top url
5182: my $mapurl=&clutter($url);
1.278 www 5183: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5184: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5185: <map>
5186: <resource id="1" type="start"></resource>
5187: <resource id="2" src="$mapurl"></resource>
5188: <resource id="3" type="finish"></resource>
5189: <link index="1" from="1" to="2"></link>
5190: <link index="2" from="2" to="3"></link>
5191: </map>
5192: ENDINITMAP
5193: $topurl=&declutter(
1.638 albertel 5194: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5195: );
5196: }
5197: # ----------------------------------------------------------- Write preferences
1.84 www 5198: &writecoursepref($udom.'_'.$uname,
5199: ('description' => $description,
1.271 www 5200: 'url' => $topurl));
1.84 www 5201: return '/'.$udom.'/'.$uname;
5202: }
5203:
1.813 albertel 5204: sub is_course {
5205: my ($cdom,$cnum) = @_;
5206: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5207: undef,'.');
5208: if (exists($courses{$cdom.'_'.$cnum})) {
5209: return 1;
5210: }
5211: return 0;
5212: }
5213:
1.21 www 5214: # ---------------------------------------------------------- Assign Custom Role
5215:
5216: sub assigncustomrole {
1.357 www 5217: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5218: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5219: $end,$start,$deleteflag);
1.21 www 5220: }
5221:
5222: # ----------------------------------------------------------------- Revoke Role
5223:
5224: sub revokerole {
1.357 www 5225: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5226: my $now=time;
1.357 www 5227: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5228: }
5229:
5230: # ---------------------------------------------------------- Revoke Custom Role
5231:
5232: sub revokecustomrole {
1.357 www 5233: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5234: my $now=time;
1.357 www 5235: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5236: $deleteflag);
1.17 www 5237: }
5238:
1.533 banghart 5239: # ------------------------------------------------------------ Disk usage
1.535 albertel 5240: sub diskusage {
1.533 banghart 5241: my ($udom,$uname,$directoryRoot)=@_;
5242: $directoryRoot =~ s/\/$//;
1.535 albertel 5243: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5244: return $listing;
1.512 banghart 5245: }
5246:
1.566 banghart 5247: sub is_locked {
5248: my ($file_name, $domain, $user) = @_;
5249: my @check;
5250: my $is_locked;
5251: push @check, $file_name;
1.613 albertel 5252: my %locked = &get('file_permissions',\@check,
1.620 albertel 5253: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5254: my ($tmp)=keys(%locked);
5255: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5256:
1.566 banghart 5257: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5258: $is_locked = 'false';
5259: foreach my $entry (@{$locked{$file_name}}) {
5260: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5261: $is_locked = 'true';
5262: last;
1.745 raeburn 5263: }
5264: }
1.566 banghart 5265: } else {
5266: $is_locked = 'false';
5267: }
5268: }
5269:
1.759 albertel 5270: sub declutter_portfile {
5271: my ($file) = @_;
1.833 albertel 5272: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5273: return $file;
5274: }
5275:
1.559 banghart 5276: # ------------------------------------------------------------- Mark as Read Only
5277:
5278: sub mark_as_readonly {
5279: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5280: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5281: my ($tmp)=keys(%current_permissions);
5282: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5283: foreach my $file (@{$files}) {
1.759 albertel 5284: $file = &declutter_portfile($file);
1.561 banghart 5285: push(@{$current_permissions{$file}},$what);
1.559 banghart 5286: }
1.613 albertel 5287: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5288: return;
5289: }
5290:
1.572 banghart 5291: # ------------------------------------------------------------Save Selected Files
5292:
5293: sub save_selected_files {
5294: my ($user, $path, @files) = @_;
5295: my $filename = $user."savedfiles";
1.573 banghart 5296: my @other_files = &files_not_in_path($user, $path);
1.871 ! albertel 5297: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5298: foreach my $file (@files) {
1.620 albertel 5299: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5300: }
5301: foreach my $file (@other_files) {
1.574 banghart 5302: print (OUT $file."\n");
1.572 banghart 5303: }
1.574 banghart 5304: close (OUT);
1.572 banghart 5305: return 'ok';
5306: }
5307:
1.574 banghart 5308: sub clear_selected_files {
5309: my ($user) = @_;
5310: my $filename = $user."savedfiles";
5311: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5312: print (OUT undef);
5313: close (OUT);
5314: return ("ok");
5315: }
5316:
1.572 banghart 5317: sub files_in_path {
5318: my ($user, $path) = @_;
5319: my $filename = $user."savedfiles";
5320: my %return_files;
1.574 banghart 5321: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5322: while (my $line_in = <IN>) {
1.574 banghart 5323: chomp ($line_in);
5324: my @paths_and_file = split (m!/!, $line_in);
5325: my $file_part = pop (@paths_and_file);
5326: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5327: $path_part.='/';
5328: my $path_and_file = $path_part.$file_part;
5329: if ($path_part eq $path) {
5330: $return_files{$file_part}= 'selected';
5331: }
5332: }
1.574 banghart 5333: close (IN);
5334: return (\%return_files);
1.572 banghart 5335: }
5336:
5337: # called in portfolio select mode, to show files selected NOT in current directory
5338: sub files_not_in_path {
5339: my ($user, $path) = @_;
5340: my $filename = $user."savedfiles";
5341: my @return_files;
5342: my $path_part;
1.800 albertel 5343: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5344: while (my $line = <IN>) {
1.572 banghart 5345: #ok, I know it's clunky, but I want it to work
1.800 albertel 5346: my @paths_and_file = split(m|/|, $line);
5347: my $file_part = pop(@paths_and_file);
5348: chomp($file_part);
5349: my $path_part = join('/', @paths_and_file);
1.572 banghart 5350: $path_part .= '/';
5351: my $path_and_file = $path_part.$file_part;
5352: if ($path_part ne $path) {
1.800 albertel 5353: push(@return_files, ($path_and_file));
1.572 banghart 5354: }
5355: }
1.800 albertel 5356: close(OUT);
1.574 banghart 5357: return (@return_files);
1.572 banghart 5358: }
5359:
1.745 raeburn 5360: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5361:
1.745 raeburn 5362: sub get_portfile_permissions {
5363: my ($domain,$user) = @_;
1.613 albertel 5364: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5365: my ($tmp)=keys(%current_permissions);
5366: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5367: return \%current_permissions;
5368: }
5369:
5370: #---------------------------------------------Get portfolio file access controls
5371:
1.749 raeburn 5372: sub get_access_controls {
1.745 raeburn 5373: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5374: my %access;
5375: my $real_file = $file;
5376: $file =~ s/\.meta$//;
1.745 raeburn 5377: if (defined($file)) {
1.749 raeburn 5378: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5379: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5380: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5381: }
5382: }
1.745 raeburn 5383: } else {
1.749 raeburn 5384: foreach my $key (keys(%{$current_permissions})) {
5385: if ($key =~ /\0accesscontrol$/) {
5386: if (defined($group)) {
5387: if ($key !~ m-^\Q$group\E/-) {
5388: next;
5389: }
5390: }
5391: my ($fullpath) = split(/\0/,$key);
5392: if (ref($$current_permissions{$key}) eq 'HASH') {
5393: foreach my $control (keys(%{$$current_permissions{$key}})) {
5394: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5395: }
5396: }
5397: }
5398: }
5399: }
5400: return %access;
5401: }
5402:
5403: sub modify_access_controls {
5404: my ($file_name,$changes,$domain,$user)=@_;
5405: my ($outcome,$deloutcome);
5406: my %store_permissions;
5407: my %new_values;
5408: my %new_control;
5409: my %translation;
5410: my @deletions = ();
5411: my $now = time;
5412: if (exists($$changes{'activate'})) {
5413: if (ref($$changes{'activate'}) eq 'HASH') {
5414: my @newitems = sort(keys(%{$$changes{'activate'}}));
5415: my $numnew = scalar(@newitems);
5416: for (my $i=0; $i<$numnew; $i++) {
5417: my $newkey = $newitems[$i];
5418: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5419: if ($newkey =~ /^\d+:/) {
5420: $newkey =~ s/^(\d+)/$newid/;
5421: $translation{$1} = $newid;
5422: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5423: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5424: $translation{$1} = $newid;
5425: }
1.749 raeburn 5426: $new_values{$file_name."\0".$newkey} =
5427: $$changes{'activate'}{$newitems[$i]};
5428: $new_control{$newkey} = $now;
5429: }
5430: }
5431: }
5432: my %todelete;
5433: my %changed_items;
5434: foreach my $action ('delete','update') {
5435: if (exists($$changes{$action})) {
5436: if (ref($$changes{$action}) eq 'HASH') {
5437: foreach my $key (keys(%{$$changes{$action}})) {
5438: my ($itemnum) = ($key =~ /^([^:]+):/);
5439: if ($action eq 'delete') {
5440: $todelete{$itemnum} = 1;
5441: } else {
5442: $changed_items{$itemnum} = $key;
5443: }
5444: }
1.745 raeburn 5445: }
5446: }
1.749 raeburn 5447: }
5448: # get lock on access controls for file.
5449: my $lockhash = {
5450: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5451: ':'.$env{'user.domain'},
5452: };
5453: my $tries = 0;
5454: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5455:
5456: while (($gotlock ne 'ok') && $tries <3) {
5457: $tries ++;
5458: sleep 1;
5459: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5460: }
5461: if ($gotlock eq 'ok') {
5462: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5463: my ($tmp)=keys(%curr_permissions);
5464: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5465: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5466: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5467: if (ref($curr_controls) eq 'HASH') {
5468: foreach my $control_item (keys(%{$curr_controls})) {
5469: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5470: if (defined($todelete{$itemnum})) {
5471: push(@deletions,$file_name."\0".$control_item);
5472: } else {
5473: if (defined($changed_items{$itemnum})) {
5474: $new_control{$changed_items{$itemnum}} = $now;
5475: push(@deletions,$file_name."\0".$control_item);
5476: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5477: } else {
5478: $new_control{$control_item} = $$curr_controls{$control_item};
5479: }
5480: }
1.745 raeburn 5481: }
5482: }
5483: }
1.749 raeburn 5484: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5485: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5486: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5487: # remove lock
5488: my @del_lock = ($file_name."\0".'locked_access_records');
5489: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5490: my ($file,$group);
5491: if (&is_course($domain,$user)) {
5492: ($group,$file) = split(/\//,$file_name,2);
5493: } else {
5494: $file = $file_name;
5495: }
5496: my $sqlresult =
5497: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5498: $group);
1.749 raeburn 5499: } else {
5500: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5501: }
1.749 raeburn 5502: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5503: }
5504:
1.827 raeburn 5505: sub make_public_indefinitely {
5506: my ($requrl) = @_;
5507: my $now = time;
5508: my $action = 'activate';
5509: my $aclnum = 0;
5510: if (&is_portfolio_url($requrl)) {
5511: my (undef,$udom,$unum,$file_name,$group) =
5512: &parse_portfolio_url($requrl);
5513: my $current_perms = &get_portfile_permissions($udom,$unum);
5514: my %access_controls = &get_access_controls($current_perms,
5515: $group,$file_name);
5516: foreach my $key (keys(%{$access_controls{$file_name}})) {
5517: my ($num,$scope,$end,$start) =
5518: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5519: if ($scope eq 'public') {
5520: if ($start <= $now && $end == 0) {
5521: $action = 'none';
5522: } else {
5523: $action = 'update';
5524: $aclnum = $num;
5525: }
5526: last;
5527: }
5528: }
5529: if ($action eq 'none') {
5530: return 'ok';
5531: } else {
5532: my %changes;
5533: my $newend = 0;
5534: my $newstart = $now;
5535: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5536: $changes{$action}{$newkey} = {
5537: type => 'public',
5538: time => {
5539: start => $newstart,
5540: end => $newend,
5541: },
5542: };
5543: my ($outcome,$deloutcome,$new_values,$translation) =
5544: &modify_access_controls($file_name,\%changes,$udom,$unum);
5545: return $outcome;
5546: }
5547: } else {
5548: return 'invalid';
5549: }
5550: }
5551:
1.745 raeburn 5552: #------------------------------------------------------Get Marked as Read Only
5553:
5554: sub get_marked_as_readonly {
5555: my ($domain,$user,$what,$group) = @_;
5556: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5557: my @readonly_files;
1.629 banghart 5558: my $cmp1=$what;
5559: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5560: while (my ($file_name,$value) = each(%{$current_permissions})) {
5561: if (defined($group)) {
5562: if ($file_name !~ m-^\Q$group\E/-) {
5563: next;
5564: }
5565: }
1.561 banghart 5566: if (ref($value) eq "ARRAY"){
5567: foreach my $stored_what (@{$value}) {
1.629 banghart 5568: my $cmp2=$stored_what;
1.759 albertel 5569: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5570: $cmp2=join('',@{$stored_what});
1.745 raeburn 5571: }
1.629 banghart 5572: if ($cmp1 eq $cmp2) {
1.561 banghart 5573: push(@readonly_files, $file_name);
1.745 raeburn 5574: last;
1.563 banghart 5575: } elsif (!defined($what)) {
5576: push(@readonly_files, $file_name);
1.745 raeburn 5577: last;
1.561 banghart 5578: }
5579: }
1.745 raeburn 5580: }
1.561 banghart 5581: }
5582: return @readonly_files;
5583: }
1.577 banghart 5584: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5585:
1.577 banghart 5586: sub get_marked_as_readonly_hash {
1.745 raeburn 5587: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5588: my %readonly_files;
1.745 raeburn 5589: while (my ($file_name,$value) = each(%{$current_permissions})) {
5590: if (defined($group)) {
5591: if ($file_name !~ m-^\Q$group\E/-) {
5592: next;
5593: }
5594: }
1.577 banghart 5595: if (ref($value) eq "ARRAY"){
5596: foreach my $stored_what (@{$value}) {
1.745 raeburn 5597: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5598: foreach my $lock_descriptor(@{$stored_what}) {
5599: if ($lock_descriptor eq 'graded') {
5600: $readonly_files{$file_name} = 'graded';
5601: } elsif ($lock_descriptor eq 'handback') {
5602: $readonly_files{$file_name} = 'handback';
5603: } else {
5604: if (!exists($readonly_files{$file_name})) {
5605: $readonly_files{$file_name} = 'locked';
5606: }
5607: }
1.745 raeburn 5608: }
1.750 banghart 5609: }
1.577 banghart 5610: }
5611: }
5612: }
5613: return %readonly_files;
5614: }
1.559 banghart 5615: # ------------------------------------------------------------ Unmark as Read Only
5616:
5617: sub unmark_as_readonly {
1.629 banghart 5618: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5619: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5620: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5621: $file_name = &declutter_portfile($file_name);
1.634 albertel 5622: my $symb_crs = $what;
5623: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5624: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5625: my ($tmp)=keys(%current_permissions);
5626: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5627: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5628: foreach my $file (@readonly_files) {
1.759 albertel 5629: my $clean_file = &declutter_portfile($file);
5630: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5631: my $current_locks = $current_permissions{$file};
1.563 banghart 5632: my @new_locks;
5633: my @del_keys;
5634: if (ref($current_locks) eq "ARRAY"){
5635: foreach my $locker (@{$current_locks}) {
1.632 albertel 5636: my $compare=$locker;
1.749 raeburn 5637: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5638: $compare=join('',@{$locker});
1.746 raeburn 5639: if ($compare ne $symb_crs) {
5640: push(@new_locks, $locker);
5641: }
1.563 banghart 5642: }
5643: }
1.650 albertel 5644: if (scalar(@new_locks) > 0) {
1.563 banghart 5645: $current_permissions{$file} = \@new_locks;
5646: } else {
5647: push(@del_keys, $file);
1.613 albertel 5648: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5649: delete($current_permissions{$file});
1.563 banghart 5650: }
5651: }
1.561 banghart 5652: }
1.613 albertel 5653: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5654: return;
5655: }
1.512 banghart 5656:
1.17 www 5657: # ------------------------------------------------------------ Directory lister
5658:
5659: sub dirlist {
1.253 stredwic 5660: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5661:
1.18 www 5662: $uri=~s/^\///;
5663: $uri=~s/\/$//;
1.253 stredwic 5664: my ($udom, $uname);
5665: (undef,$udom,$uname)=split(/\//,$uri);
5666: if(defined($userdomain)) {
5667: $udom = $userdomain;
5668: }
5669: if(defined($username)) {
5670: $uname = $username;
5671: }
5672:
5673: my $dirRoot = $perlvar{'lonDocRoot'};
5674: if(defined($alternateDirectoryRoot)) {
5675: $dirRoot = $alternateDirectoryRoot;
5676: $dirRoot =~ s/\/$//;
1.751 banghart 5677: }
1.253 stredwic 5678:
5679: if($udom) {
5680: if($uname) {
1.800 albertel 5681: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5682: &homeserver($uname,$udom));
1.605 matthew 5683: my @listing_results;
5684: if ($listing eq 'unknown_cmd') {
1.800 albertel 5685: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5686: &homeserver($uname,$udom));
1.605 matthew 5687: @listing_results = split(/:/,$listing);
5688: } else {
5689: @listing_results = map { &unescape($_); } split(/:/,$listing);
5690: }
5691: return @listing_results;
1.253 stredwic 5692: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 5693: my %allusers;
1.841 albertel 5694: my %servers = &get_servers($udom,'library');
5695: foreach my $tryserver (keys(%servers)) {
5696: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5697: $udom, $tryserver);
5698: my @listing_results;
5699: if ($listing eq 'unknown_cmd') {
5700: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5701: $udom, $tryserver);
5702: @listing_results = split(/:/,$listing);
5703: } else {
5704: @listing_results =
5705: map { &unescape($_); } split(/:/,$listing);
5706: }
5707: if ($listing_results[0] ne 'no_such_dir' &&
5708: $listing_results[0] ne 'empty' &&
5709: $listing_results[0] ne 'con_lost') {
5710: foreach my $line (@listing_results) {
5711: my ($entry) = split(/&/,$line,2);
5712: $allusers{$entry} = 1;
5713: }
5714: }
1.253 stredwic 5715: }
5716: my $alluserstr='';
1.800 albertel 5717: foreach my $user (sort(keys(%allusers))) {
5718: $alluserstr.=$user.'&user:';
1.253 stredwic 5719: }
5720: $alluserstr=~s/:$//;
5721: return split(/:/,$alluserstr);
5722: } else {
1.800 albertel 5723: return ('missing user name');
1.253 stredwic 5724: }
5725: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 5726: my @all_domains = sort(&all_domains());
5727: foreach my $domain (@all_domains) {
5728: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5729: }
5730: return @all_domains;
5731: } else {
1.800 albertel 5732: return ('missing domain');
1.275 stredwic 5733: }
5734: }
5735:
5736: # --------------------------------------------- GetFileTimestamp
5737: # This function utilizes dirlist and returns the date stamp for
5738: # when it was last modified. It will also return an error of -1
5739: # if an error occurs
5740:
1.410 matthew 5741: ##
5742: ## FIXME: This subroutine assumes its caller knows something about the
5743: ## directory structure of the home server for the student ($root).
5744: ## Not a good assumption to make. Since this is for looking up files
5745: ## in user directories, the full path should be constructed by lond, not
5746: ## whatever machine we request data from.
5747: ##
1.275 stredwic 5748: sub GetFileTimestamp {
5749: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 5750: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5751: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 5752: my $subdir=$studentName.'__';
5753: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5754: my $proname="$studentDomain/$subdir/$studentName";
5755: $proname .= '/'.$filename;
1.375 matthew 5756: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5757: $studentName, $root);
1.275 stredwic 5758: my @stats = split('&', $fileStat);
5759: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5760: # @stats contains first the filename, then the stat output
5761: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5762: } else {
5763: return -1;
1.253 stredwic 5764: }
1.26 www 5765: }
5766:
1.712 albertel 5767: sub stat_file {
5768: my ($uri) = @_;
1.787 albertel 5769: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5770:
1.712 albertel 5771: my ($udom,$uname,$file,$dir);
5772: if ($uri =~ m-^/(uploaded|editupload)/-) {
5773: ($udom,$uname,$file) =
1.811 albertel 5774: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 5775: $file = 'userfiles/'.$file;
1.740 www 5776: $dir = &propath($udom,$uname);
1.712 albertel 5777: }
5778: if ($uri =~ m-^/res/-) {
5779: ($udom,$uname) =
1.807 albertel 5780: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 5781: $file = $uri;
5782: }
5783:
5784: if (!$udom || !$uname || !$file) {
5785: # unable to handle the uri
5786: return ();
5787: }
5788:
5789: my ($result) = &dirlist($file,$udom,$uname,$dir);
5790: my @stats = split('&', $result);
1.721 banghart 5791:
1.712 albertel 5792: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5793: shift(@stats); #filename is first
5794: return @stats;
5795: }
5796: return ();
5797: }
5798:
1.26 www 5799: # -------------------------------------------------------- Value of a Condition
5800:
1.713 albertel 5801: # gets the value of a specific preevaluated condition
5802: # stored in the string $env{user.state.<cid>}
5803: # or looks up a condition reference in the bighash and if if hasn't
5804: # already been evaluated recurses into docondval to get the value of
5805: # the condition, then memoizing it to
5806: # $env{user.state.<cid>.<condition>}
1.40 www 5807: sub directcondval {
5808: my $number=shift;
1.620 albertel 5809: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5810: &Apache::lonuserstate::evalstate();
5811: }
1.713 albertel 5812: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5813: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5814: } elsif ($number =~ /^_/) {
5815: my $sub_condition;
5816: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5817: &GDBM_READER(),0640)) {
5818: $sub_condition=$bighash{'conditions'.$number};
5819: untie(%bighash);
5820: }
5821: my $value = &docondval($sub_condition);
5822: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5823: return $value;
5824: }
1.620 albertel 5825: if ($env{'user.state.'.$env{'request.course.id'}}) {
5826: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5827: } else {
5828: return 2;
5829: }
5830: }
5831:
1.713 albertel 5832: # get the collection of conditions for this resource
1.26 www 5833: sub condval {
5834: my $condidx=shift;
1.54 www 5835: my $allpathcond='';
1.713 albertel 5836: foreach my $cond (split(/\|/,$condidx)) {
5837: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5838: $allpathcond.=
5839: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5840: }
1.191 harris41 5841: }
1.54 www 5842: $allpathcond=~s/\|$//;
1.713 albertel 5843: return &docondval($allpathcond);
5844: }
5845:
5846: #evaluates an expression of conditions
5847: sub docondval {
5848: my ($allpathcond) = @_;
5849: my $result=0;
5850: if ($env{'request.course.id'}
5851: && defined($allpathcond)) {
5852: my $operand='|';
5853: my @stack;
5854: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5855: if ($chunk eq '(') {
5856: push @stack,($operand,$result);
5857: } elsif ($chunk eq ')') {
5858: my $before=pop @stack;
5859: if (pop @stack eq '&') {
5860: $result=$result>$before?$before:$result;
5861: } else {
5862: $result=$result>$before?$result:$before;
5863: }
5864: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5865: $operand=$chunk;
5866: } else {
5867: my $new=directcondval($chunk);
5868: if ($operand eq '&') {
5869: $result=$result>$new?$new:$result;
5870: } else {
5871: $result=$result>$new?$result:$new;
5872: }
5873: }
5874: }
1.26 www 5875: }
5876: return $result;
1.421 albertel 5877: }
5878:
5879: # ---------------------------------------------------- Devalidate courseresdata
5880:
5881: sub devalidatecourseresdata {
5882: my ($coursenum,$coursedomain)=@_;
5883: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5884: &devalidate_cache_new('courseres',$hashid);
1.28 www 5885: }
5886:
1.763 www 5887:
1.200 www 5888: # --------------------------------------------------- Course Resourcedata Query
5889:
1.624 albertel 5890: sub get_courseresdata {
5891: my ($coursenum,$coursedomain)=@_;
1.200 www 5892: my $coursehom=&homeserver($coursenum,$coursedomain);
5893: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5894: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5895: my %dumpreply;
1.417 albertel 5896: unless (defined($cached)) {
1.624 albertel 5897: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5898: $result=\%dumpreply;
1.251 albertel 5899: my ($tmp) = keys(%dumpreply);
5900: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5901: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5902: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5903: return $tmp;
1.416 albertel 5904: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5905: $result=undef;
1.599 albertel 5906: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5907: }
5908: }
1.624 albertel 5909: return $result;
5910: }
5911:
1.633 albertel 5912: sub devalidateuserresdata {
5913: my ($uname,$udom)=@_;
5914: my $hashid="$udom:$uname";
5915: &devalidate_cache_new('userres',$hashid);
5916: }
5917:
1.624 albertel 5918: sub get_userresdata {
5919: my ($uname,$udom)=@_;
5920: #most student don\'t have any data set, check if there is some data
5921: if (&EXT_cache_status($udom,$uname)) { return undef; }
5922:
5923: my $hashid="$udom:$uname";
5924: my ($result,$cached)=&is_cached_new('userres',$hashid);
5925: if (!defined($cached)) {
5926: my %resourcedata=&dump('resourcedata',$udom,$uname);
5927: $result=\%resourcedata;
5928: &do_cache_new('userres',$hashid,$result,600);
5929: }
5930: my ($tmp)=keys(%$result);
5931: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5932: return $result;
5933: }
5934: #error 2 occurs when the .db doesn't exist
5935: if ($tmp!~/error: 2 /) {
1.672 albertel 5936: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5937: " Trying to get resource data for ".
5938: $uname." at ".$udom.": ".
5939: $tmp."</font>");
5940: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5941: #&EXT_cache_set($udom,$uname);
5942: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5943: undef($tmp); # not really an error so don't send it back
1.624 albertel 5944: }
5945: return $tmp;
5946: }
5947:
5948: sub resdata {
5949: my ($name,$domain,$type,@which)=@_;
5950: my $result;
5951: if ($type eq 'course') {
5952: $result=&get_courseresdata($name,$domain);
5953: } elsif ($type eq 'user') {
5954: $result=&get_userresdata($name,$domain);
5955: }
5956: if (!ref($result)) { return $result; }
1.251 albertel 5957: foreach my $item (@which) {
1.417 albertel 5958: if (defined($result->{$item})) {
5959: return $result->{$item};
1.251 albertel 5960: }
1.250 albertel 5961: }
1.291 albertel 5962: return undef;
1.200 www 5963: }
5964:
1.379 matthew 5965: #
5966: # EXT resource caching routines
5967: #
5968:
5969: sub clear_EXT_cache_status {
1.383 albertel 5970: &delenv('cache.EXT.');
1.379 matthew 5971: }
5972:
5973: sub EXT_cache_status {
5974: my ($target_domain,$target_user) = @_;
1.383 albertel 5975: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 5976: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 5977: # We know already the user has no data
5978: return 1;
5979: } else {
5980: return 0;
5981: }
5982: }
5983:
5984: sub EXT_cache_set {
5985: my ($target_domain,$target_user) = @_;
1.383 albertel 5986: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 5987: #&appenv($cachename => time);
1.379 matthew 5988: }
5989:
1.28 www 5990: # --------------------------------------------------------- Value of a Variable
1.58 www 5991: sub EXT {
1.715 albertel 5992:
1.395 albertel 5993: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 5994: unless ($varname) { return ''; }
1.218 albertel 5995: #get real user name/domain, courseid and symb
5996: my $courseid;
1.359 albertel 5997: my $publicuser;
1.427 www 5998: if ($symbparm) {
5999: $symbparm=&get_symb_from_alias($symbparm);
6000: }
1.218 albertel 6001: if (!($uname && $udom)) {
1.790 albertel 6002: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6003: if (!$symbparm) { $symbparm=$cursymb; }
6004: } else {
1.620 albertel 6005: $courseid=$env{'request.course.id'};
1.218 albertel 6006: }
1.48 www 6007: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6008: my $rest;
1.320 albertel 6009: if (defined($therest[0])) {
1.48 www 6010: $rest=join('.',@therest);
6011: } else {
6012: $rest='';
6013: }
1.320 albertel 6014:
1.57 www 6015: my $qualifierrest=$qualifier;
6016: if ($rest) { $qualifierrest.='.'.$rest; }
6017: my $spacequalifierrest=$space;
6018: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6019: if ($realm eq 'user') {
1.48 www 6020: # --------------------------------------------------------------- user.resource
6021: if ($space eq 'resource') {
1.651 albertel 6022: if ( (defined($Apache::lonhomework::parsing_a_problem)
6023: || defined($Apache::lonhomework::parsing_a_task))
6024: &&
1.744 albertel 6025: ($symbparm eq &symbread()) ) {
6026: # if we are in the middle of processing the resource the
6027: # get the value we are planning on committing
6028: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6029: return $Apache::lonhomework::results{$qualifierrest};
6030: } else {
6031: return $Apache::lonhomework::history{$qualifierrest};
6032: }
1.335 albertel 6033: } else {
1.359 albertel 6034: my %restored;
1.620 albertel 6035: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6036: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6037: } else {
6038: %restored=&restore($symbparm,$courseid,$udom,$uname);
6039: }
1.335 albertel 6040: return $restored{$qualifierrest};
6041: }
1.48 www 6042: # ----------------------------------------------------------------- user.access
6043: } elsif ($space eq 'access') {
1.218 albertel 6044: # FIXME - not supporting calls for a specific user
1.48 www 6045: return &allowed($qualifier,$rest);
6046: # ------------------------------------------ user.preferences, user.environment
6047: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6048: if (($uname eq $env{'user.name'}) &&
6049: ($udom eq $env{'user.domain'})) {
6050: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6051: } else {
1.359 albertel 6052: my %returnhash;
6053: if (!$publicuser) {
6054: %returnhash=&userenvironment($udom,$uname,
6055: $qualifierrest);
6056: }
1.218 albertel 6057: return $returnhash{$qualifierrest};
6058: }
1.48 www 6059: # ----------------------------------------------------------------- user.course
6060: } elsif ($space eq 'course') {
1.218 albertel 6061: # FIXME - not supporting calls for a specific user
1.620 albertel 6062: return $env{join('.',('request.course',$qualifier))};
1.48 www 6063: # ------------------------------------------------------------------- user.role
6064: } elsif ($space eq 'role') {
1.218 albertel 6065: # FIXME - not supporting calls for a specific user
1.620 albertel 6066: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6067: if ($qualifier eq 'value') {
6068: return $role;
6069: } elsif ($qualifier eq 'extent') {
6070: return $where;
6071: }
6072: # ----------------------------------------------------------------- user.domain
6073: } elsif ($space eq 'domain') {
1.218 albertel 6074: return $udom;
1.48 www 6075: # ------------------------------------------------------------------- user.name
6076: } elsif ($space eq 'name') {
1.218 albertel 6077: return $uname;
1.48 www 6078: # ---------------------------------------------------- Any other user namespace
1.29 www 6079: } else {
1.359 albertel 6080: my %reply;
6081: if (!$publicuser) {
6082: %reply=&get($space,[$qualifierrest],$udom,$uname);
6083: }
6084: return $reply{$qualifierrest};
1.48 www 6085: }
1.236 www 6086: } elsif ($realm eq 'query') {
6087: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6088: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6089: [$spacequalifierrest]);
1.620 albertel 6090: return $env{'form.'.$spacequalifierrest};
1.236 www 6091: } elsif ($realm eq 'request') {
1.48 www 6092: # ------------------------------------------------------------- request.browser
6093: if ($space eq 'browser') {
1.430 www 6094: if ($qualifier eq 'textremote') {
1.676 albertel 6095: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6096: return 1;
6097: } else {
6098: return 0;
6099: }
6100: } else {
1.620 albertel 6101: return $env{'browser.'.$qualifier};
1.430 www 6102: }
1.57 www 6103: # ------------------------------------------------------------ request.filename
6104: } else {
1.620 albertel 6105: return $env{'request.'.$spacequalifierrest};
1.29 www 6106: }
1.28 www 6107: } elsif ($realm eq 'course') {
1.48 www 6108: # ---------------------------------------------------------- course.description
1.620 albertel 6109: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6110: } elsif ($realm eq 'resource') {
1.165 www 6111:
1.620 albertel 6112: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6113: if (!$symbparm) { $symbparm=&symbread(); }
6114: }
1.693 albertel 6115:
6116: if ($space eq 'title') {
6117: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6118: return &gettitle($symbparm);
6119: }
6120:
6121: if ($space eq 'map') {
6122: my ($map) = &decode_symb($symbparm);
6123: return &symbread($map);
6124: }
6125:
6126: my ($section, $group, @groups);
1.593 albertel 6127: my ($courselevelm,$courselevel);
1.539 albertel 6128: if ($symbparm && defined($courseid) &&
1.620 albertel 6129: $courseid eq $env{'request.course.id'}) {
1.165 www 6130:
1.218 albertel 6131: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6132:
1.60 www 6133: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6134: my $symbp=$symbparm;
1.735 albertel 6135: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6136:
6137: my $symbparm=$symbp.'.'.$spacequalifierrest;
6138: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6139:
1.620 albertel 6140: if (($env{'user.name'} eq $uname) &&
6141: ($env{'user.domain'} eq $udom)) {
6142: $section=$env{'request.course.sec'};
1.733 raeburn 6143: @groups = split(/:/,$env{'request.course.groups'});
6144: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6145: } else {
1.539 albertel 6146: if (! defined($usection)) {
1.551 albertel 6147: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6148: } else {
6149: $section = $usection;
6150: }
1.733 raeburn 6151: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6152: }
6153:
6154: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6155: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6156: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6157:
1.593 albertel 6158: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6159: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6160: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6161:
1.60 www 6162: # ----------------------------------------------------------- first, check user
1.624 albertel 6163:
6164: my $userreply=&resdata($uname,$udom,'user',
6165: ($courselevelr,$courselevelm,
6166: $courselevel));
6167: if (defined($userreply)) { return $userreply; }
1.95 www 6168:
1.594 albertel 6169: # ------------------------------------------------ second, check some of course
1.684 raeburn 6170: my $coursereply;
1.691 raeburn 6171: if (@groups > 0) {
6172: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6173: $mapparm,$spacequalifierrest);
1.684 raeburn 6174: if (defined($coursereply)) { return $coursereply; }
6175: }
1.96 www 6176:
1.684 raeburn 6177: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6178: $env{'course.'.$courseid.'.domain'},
6179: 'course',
6180: ($seclevelr,$seclevelm,$seclevel,
6181: $courselevelr));
1.287 albertel 6182: if (defined($coursereply)) { return $coursereply; }
1.200 www 6183:
1.60 www 6184: # ------------------------------------------------------ third, check map parms
1.218 albertel 6185: my %parmhash=();
6186: my $thisparm='';
6187: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6188: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6189: &GDBM_READER(),0640)) {
1.218 albertel 6190: $thisparm=$parmhash{$symbparm};
6191: untie(%parmhash);
6192: }
6193: if ($thisparm) { return $thisparm; }
6194: }
1.594 albertel 6195: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6196:
1.218 albertel 6197: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6198: my $filename;
6199: if (!$symbparm) { $symbparm=&symbread(); }
6200: if ($symbparm) {
1.409 www 6201: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6202: } else {
1.620 albertel 6203: $filename=$env{'request.filename'};
1.282 albertel 6204: }
6205: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6206: if (defined($metadata)) { return $metadata; }
1.282 albertel 6207: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6208: if (defined($metadata)) { return $metadata; }
1.142 www 6209:
1.594 albertel 6210: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6211: if ($symbparm && defined($courseid) &&
1.620 albertel 6212: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6213: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6214: $env{'course.'.$courseid.'.domain'},
6215: 'course',
6216: ($courselevelm,$courselevel));
1.593 albertel 6217: if (defined($coursereply)) { return $coursereply; }
6218: }
1.145 www 6219: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6220: unless ($space eq '0') {
1.336 albertel 6221: my @parts=split(/_/,$space);
6222: my $id=pop(@parts);
6223: my $part=join('_',@parts);
6224: if ($part eq '') { $part='0'; }
6225: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6226: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6227: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6228: }
1.395 albertel 6229: if ($recurse) { return undef; }
6230: my $pack_def=&packages_tab_default($filename,$varname);
6231: if (defined($pack_def)) { return $pack_def; }
1.71 www 6232:
1.48 www 6233: # ---------------------------------------------------- Any other user namespace
6234: } elsif ($realm eq 'environment') {
6235: # ----------------------------------------------------------------- environment
1.620 albertel 6236: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6237: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6238: } else {
1.770 albertel 6239: if ($uname eq 'anonymous' && $udom eq '') {
6240: return '';
6241: }
1.219 albertel 6242: my %returnhash=&userenvironment($udom,$uname,
6243: $spacequalifierrest);
6244: return $returnhash{$spacequalifierrest};
6245: }
1.28 www 6246: } elsif ($realm eq 'system') {
1.48 www 6247: # ----------------------------------------------------------------- system.time
6248: if ($space eq 'time') {
6249: return time;
6250: }
1.696 albertel 6251: } elsif ($realm eq 'server') {
6252: # ----------------------------------------------------------------- system.time
6253: if ($space eq 'name') {
6254: return $ENV{'SERVER_NAME'};
6255: }
1.28 www 6256: }
1.48 www 6257: return '';
1.61 www 6258: }
6259:
1.691 raeburn 6260: sub check_group_parms {
6261: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6262: my @groupitems = ();
6263: my $resultitem;
6264: my @levels = ($symbparm,$mapparm,$what);
6265: foreach my $group (@{$groups}) {
6266: foreach my $level (@levels) {
6267: my $item = $courseid.'.['.$group.'].'.$level;
6268: push(@groupitems,$item);
6269: }
6270: }
6271: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6272: $env{'course.'.$courseid.'.domain'},
6273: 'course',@groupitems);
6274: return $coursereply;
6275: }
6276:
6277: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6278: my ($courseid,@groups) = @_;
6279: @groups = sort(@groups);
1.691 raeburn 6280: return @groups;
6281: }
6282:
1.395 albertel 6283: sub packages_tab_default {
6284: my ($uri,$varname)=@_;
6285: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6286:
6287: my (@extension,@specifics,$do_default);
6288: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6289: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6290: if ($pack_type eq 'default') {
6291: $do_default=1;
6292: } elsif ($pack_type eq 'extension') {
6293: push(@extension,[$package,$pack_type,$pack_part]);
1.848 albertel 6294: } elsif ($pack_part eq $part) {
6295: # only look at packages defaults for packages that this id is
1.738 albertel 6296: push(@specifics,[$package,$pack_type,$pack_part]);
6297: }
6298: }
6299: # first look for a package that matches the requested part id
6300: foreach my $package (@specifics) {
6301: my (undef,$pack_type,$pack_part)=@{$package};
6302: next if ($pack_part ne $part);
6303: if (defined($packagetab{"$pack_type&$name&default"})) {
6304: return $packagetab{"$pack_type&$name&default"};
6305: }
6306: }
6307: # look for any possible matching non extension_ package
6308: foreach my $package (@specifics) {
6309: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6310: if (defined($packagetab{"$pack_type&$name&default"})) {
6311: return $packagetab{"$pack_type&$name&default"};
6312: }
1.585 albertel 6313: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6314: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6315: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6316: }
6317: }
1.738 albertel 6318: # look for any posible extension_ match
6319: foreach my $package (@extension) {
6320: my ($package,$pack_type)=@{$package};
6321: if (defined($packagetab{"$pack_type&$name&default"})) {
6322: return $packagetab{"$pack_type&$name&default"};
6323: }
6324: if (defined($packagetab{$package."&$name&default"})) {
6325: return $packagetab{$package."&$name&default"};
6326: }
6327: }
6328: # look for a global default setting
6329: if ($do_default && defined($packagetab{"default&$name&default"})) {
6330: return $packagetab{"default&$name&default"};
6331: }
1.395 albertel 6332: return undef;
6333: }
6334:
1.334 albertel 6335: sub add_prefix_and_part {
6336: my ($prefix,$part)=@_;
6337: my $keyroot;
6338: if (defined($prefix) && $prefix !~ /^__/) {
6339: # prefix that has a part already
6340: $keyroot=$prefix;
6341: } elsif (defined($prefix)) {
6342: # prefix that is missing a part
6343: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6344: } else {
6345: # no prefix at all
6346: if (defined($part)) { $keyroot='_'.$part; }
6347: }
6348: return $keyroot;
6349: }
6350:
1.71 www 6351: # ---------------------------------------------------------------- Get metadata
6352:
1.599 albertel 6353: my %metaentry;
1.71 www 6354: sub metadata {
1.176 www 6355: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6356: $uri=&declutter($uri);
1.288 albertel 6357: # if it is a non metadata possible uri return quickly
1.529 albertel 6358: if (($uri eq '') ||
6359: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6360: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6361: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6362: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6363: return undef;
1.288 albertel 6364: }
1.73 www 6365: my $filename=$uri;
6366: $uri=~s/\.meta$//;
1.172 www 6367: #
6368: # Is the metadata already cached?
1.177 www 6369: # Look at timestamp of caching
1.172 www 6370: # Everything is cached by the main uri, libraries are never directly cached
6371: #
1.428 albertel 6372: if (!defined($liburi)) {
1.599 albertel 6373: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6374: if (defined($cached)) { return $result->{':'.$what}; }
6375: }
6376: {
1.172 www 6377: #
6378: # Is this a recursive call for a library?
6379: #
1.599 albertel 6380: # if (! exists($metacache{$uri})) {
6381: # $metacache{$uri}={};
6382: # }
1.171 www 6383: if ($liburi) {
6384: $liburi=&declutter($liburi);
6385: $filename=$liburi;
1.401 bowersj2 6386: } else {
1.599 albertel 6387: &devalidate_cache_new('meta',$uri);
6388: undef(%metaentry);
1.401 bowersj2 6389: }
1.140 www 6390: my %metathesekeys=();
1.73 www 6391: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6392: my $metastring;
1.768 albertel 6393: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6394: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6395: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6396: $metastring=&getfile($file);
1.489 albertel 6397: }
1.208 albertel 6398: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6399: my $token;
1.140 www 6400: undef %metathesekeys;
1.71 www 6401: while ($token=$parser->get_token) {
1.339 albertel 6402: if ($token->[0] eq 'S') {
6403: if (defined($token->[2]->{'package'})) {
1.172 www 6404: #
6405: # This is a package - get package info
6406: #
1.339 albertel 6407: my $package=$token->[2]->{'package'};
6408: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6409: if (defined($token->[2]->{'id'})) {
6410: $keyroot.='_'.$token->[2]->{'id'};
6411: }
1.599 albertel 6412: if ($metaentry{':packages'}) {
6413: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6414: } else {
1.599 albertel 6415: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6416: }
1.736 albertel 6417: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6418: my $part=$keyroot;
6419: $part=~s/^\_//;
1.736 albertel 6420: if ($pack_entry=~/^\Q$package\E\&/ ||
6421: $pack_entry=~/^\Q$package\E_0\&/) {
6422: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6423: # ignore package.tab specified default values
6424: # here &package_tab_default() will fetch those
6425: if ($subp eq 'default') { next; }
1.736 albertel 6426: my $value=$packagetab{$pack_entry};
1.432 albertel 6427: my $unikey;
6428: if ($pack =~ /_0$/) {
6429: $unikey='parameter_0_'.$name;
6430: $part=0;
6431: } else {
6432: $unikey='parameter'.$keyroot.'_'.$name;
6433: }
1.339 albertel 6434: if ($subp eq 'display') {
6435: $value.=' [Part: '.$part.']';
6436: }
1.599 albertel 6437: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6438: $metathesekeys{$unikey}=1;
1.599 albertel 6439: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6440: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6441: }
1.599 albertel 6442: if (defined($metaentry{':'.$unikey.'.default'})) {
6443: $metaentry{':'.$unikey}=
6444: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6445: }
1.339 albertel 6446: }
6447: }
6448: } else {
1.172 www 6449: #
6450: # This is not a package - some other kind of start tag
1.339 albertel 6451: #
6452: my $entry=$token->[1];
6453: my $unikey;
6454: if ($entry eq 'import') {
6455: $unikey='';
6456: } else {
6457: $unikey=$entry;
6458: }
6459: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6460:
6461: if (defined($token->[2]->{'id'})) {
6462: $unikey.='_'.$token->[2]->{'id'};
6463: }
1.175 www 6464:
1.339 albertel 6465: if ($entry eq 'import') {
1.175 www 6466: #
6467: # Importing a library here
1.339 albertel 6468: #
6469: if ($depthcount<20) {
6470: my $location=$parser->get_text('/import');
6471: my $dir=$filename;
6472: $dir=~s|[^/]*$||;
6473: $location=&filelocation($dir,$location);
1.736 albertel 6474: my $metadata =
6475: &metadata($uri,'keys', $location,$unikey,
6476: $depthcount+1);
6477: foreach my $meta (split(',',$metadata)) {
6478: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6479: $metathesekeys{$meta}=1;
1.339 albertel 6480: }
6481: }
6482: } else {
6483:
6484: if (defined($token->[2]->{'name'})) {
6485: $unikey.='_'.$token->[2]->{'name'};
6486: }
6487: $metathesekeys{$unikey}=1;
1.736 albertel 6488: foreach my $param (@{$token->[3]}) {
6489: $metaentry{':'.$unikey.'.'.$param} =
6490: $token->[2]->{$param};
1.339 albertel 6491: }
6492: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6493: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6494: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6495: # only ws inside the tag, and not in default, so use default
6496: # as value
1.599 albertel 6497: $metaentry{':'.$unikey}=$default;
1.339 albertel 6498: } else {
1.321 albertel 6499: # either something interesting inside the tag or default
6500: # uninteresting
1.599 albertel 6501: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6502: }
1.172 www 6503: # end of not-a-package not-a-library import
1.339 albertel 6504: }
1.172 www 6505: # end of not-a-package start tag
1.339 albertel 6506: }
1.172 www 6507: # the next is the end of "start tag"
1.339 albertel 6508: }
6509: }
1.483 albertel 6510: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6511: foreach my $key (keys(%packagetab)) {
1.483 albertel 6512: #no specific packages #how's our extension
6513: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6514: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6515: \%metathesekeys);
6516: }
1.599 albertel 6517: if (!exists($metaentry{':packages'})) {
1.737 albertel 6518: foreach my $key (keys(%packagetab)) {
1.483 albertel 6519: #no specific packages well let's get default then
6520: if ($key!~/^default&/) { next; }
1.488 albertel 6521: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6522: \%metathesekeys);
6523: }
6524: }
1.338 www 6525: # are there custom rights to evaluate
1.599 albertel 6526: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6527:
1.338 www 6528: #
6529: # Importing a rights file here
1.339 albertel 6530: #
6531: unless ($depthcount) {
1.599 albertel 6532: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6533: my $dir=$filename;
6534: $dir=~s|[^/]*$||;
6535: $location=&filelocation($dir,$location);
1.736 albertel 6536: my $rights_metadata =
6537: &metadata($uri,'keys',$location,'_rights',
6538: $depthcount+1);
6539: foreach my $rights (split(',',$rights_metadata)) {
6540: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6541: $metathesekeys{$rights}=1;
1.339 albertel 6542: }
6543: }
6544: }
1.737 albertel 6545: # uniqifiy package listing
6546: my %seen;
6547: my @uniq_packages =
6548: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6549: $metaentry{':packages'} = join(',',@uniq_packages);
6550:
6551: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6552: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6553: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6554: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6555: # this is the end of "was not already recently cached
1.71 www 6556: }
1.599 albertel 6557: return $metaentry{':'.$what};
1.261 albertel 6558: }
6559:
1.488 albertel 6560: sub metadata_create_package_def {
1.483 albertel 6561: my ($uri,$key,$package,$metathesekeys)=@_;
6562: my ($pack,$name,$subp)=split(/\&/,$key);
6563: if ($subp eq 'default') { next; }
6564:
1.599 albertel 6565: if (defined($metaentry{':packages'})) {
6566: $metaentry{':packages'}.=','.$package;
1.483 albertel 6567: } else {
1.599 albertel 6568: $metaentry{':packages'}=$package;
1.483 albertel 6569: }
6570: my $value=$packagetab{$key};
6571: my $unikey;
6572: $unikey='parameter_0_'.$name;
1.599 albertel 6573: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6574: $$metathesekeys{$unikey}=1;
1.599 albertel 6575: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6576: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6577: }
1.599 albertel 6578: if (defined($metaentry{':'.$unikey.'.default'})) {
6579: $metaentry{':'.$unikey}=
6580: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6581: }
6582: }
6583:
1.261 albertel 6584: sub metadata_generate_part0 {
6585: my ($metadata,$metacache,$uri) = @_;
6586: my %allnames;
1.737 albertel 6587: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6588: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6589: my $part=$$metacache{':'.$metakey.'.part'};
6590: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6591: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6592: $allnames{$name}=$part;
6593: }
6594: }
6595: }
6596: foreach my $name (keys(%allnames)) {
6597: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6598: my $key=":parameter_0_$name";
1.261 albertel 6599: $$metacache{"$key.part"}='0';
6600: $$metacache{"$key.name"}=$name;
1.428 albertel 6601: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6602: $allnames{$name}.'_'.$name.
6603: '.type'};
1.428 albertel 6604: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6605: '.display'};
1.644 www 6606: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6607: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6608: $$metacache{"$key.display"}=$olddis;
6609: }
1.71 www 6610: }
6611:
1.764 albertel 6612: # ------------------------------------------------------ Devalidate title cache
6613:
6614: sub devalidate_title_cache {
6615: my ($url)=@_;
6616: if (!$env{'request.course.id'}) { return; }
6617: my $symb=&symbread($url);
6618: if (!$symb) { return; }
6619: my $key=$env{'request.course.id'}."\0".$symb;
6620: &devalidate_cache_new('title',$key);
6621: }
6622:
1.301 www 6623: # ------------------------------------------------- Get the title of a resource
6624:
6625: sub gettitle {
6626: my $urlsymb=shift;
6627: my $symb=&symbread($urlsymb);
1.534 albertel 6628: if ($symb) {
1.620 albertel 6629: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6630: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6631: if (defined($cached)) {
6632: return $result;
6633: }
1.534 albertel 6634: my ($map,$resid,$url)=&decode_symb($symb);
6635: my $title='';
6636: my %bighash;
1.620 albertel 6637: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6638: &GDBM_READER(),0640)) {
6639: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6640: $title=$bighash{'title_'.$mapid.'.'.$resid};
6641: untie %bighash;
6642: }
6643: $title=~s/\&colon\;/\:/gs;
6644: if ($title) {
1.599 albertel 6645: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6646: }
6647: $urlsymb=$url;
6648: }
6649: my $title=&metadata($urlsymb,'title');
6650: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6651: return $title;
1.301 www 6652: }
1.613 albertel 6653:
1.614 albertel 6654: sub get_slot {
6655: my ($which,$cnum,$cdom)=@_;
6656: if (!$cnum || !$cdom) {
1.790 albertel 6657: (undef,my $courseid)=&whichuser();
1.620 albertel 6658: $cdom=$env{'course.'.$courseid.'.domain'};
6659: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6660: }
1.703 albertel 6661: my $key=join("\0",'slots',$cdom,$cnum,$which);
6662: my %slotinfo;
6663: if (exists($remembered{$key})) {
6664: $slotinfo{$which} = $remembered{$key};
6665: } else {
6666: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6667: &Apache::lonhomework::showhash(%slotinfo);
6668: my ($tmp)=keys(%slotinfo);
6669: if ($tmp=~/^error:/) { return (); }
6670: $remembered{$key} = $slotinfo{$which};
6671: }
1.616 albertel 6672: if (ref($slotinfo{$which}) eq 'HASH') {
6673: return %{$slotinfo{$which}};
6674: }
6675: return $slotinfo{$which};
1.614 albertel 6676: }
1.31 www 6677: # ------------------------------------------------- Update symbolic store links
6678:
6679: sub symblist {
6680: my ($mapname,%newhash)=@_;
1.438 www 6681: $mapname=&deversion(&declutter($mapname));
1.31 www 6682: my %hash;
1.620 albertel 6683: if (($env{'request.course.fn'}) && (%newhash)) {
6684: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6685: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6686: foreach my $url (keys %newhash) {
6687: next if ($url eq 'last_known'
6688: && $env{'form.no_update_last_known'});
6689: $hash{declutter($url)}=&encode_symb($mapname,
6690: $newhash{$url}->[1],
6691: $newhash{$url}->[0]);
1.191 harris41 6692: }
1.31 www 6693: if (untie(%hash)) {
6694: return 'ok';
6695: }
6696: }
6697: }
6698: return 'error';
1.212 www 6699: }
6700:
6701: # --------------------------------------------------------------- Verify a symb
6702:
6703: sub symbverify {
1.510 www 6704: my ($symb,$thisurl)=@_;
6705: my $thisfn=$thisurl;
1.439 www 6706: $thisfn=&declutter($thisfn);
1.215 www 6707: # direct jump to resource in page or to a sequence - will construct own symbs
6708: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6709: # check URL part
1.409 www 6710: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6711:
1.431 www 6712: unless ($url eq $thisfn) { return 0; }
1.213 www 6713:
1.216 www 6714: $symb=&symbclean($symb);
1.510 www 6715: $thisurl=&deversion($thisurl);
1.439 www 6716: $thisfn=&deversion($thisfn);
1.213 www 6717:
6718: my %bighash;
6719: my $okay=0;
1.431 www 6720:
1.620 albertel 6721: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6722: &GDBM_READER(),0640)) {
1.510 www 6723: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6724: unless ($ids) {
1.510 www 6725: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6726: }
6727: if ($ids) {
6728: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 6729: foreach my $id (split(/\,/,$ids)) {
6730: my ($mapid,$resid)=split(/\./,$id);
1.216 www 6731: if (
6732: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6733: eq $symb) {
1.620 albertel 6734: if (($env{'request.role.adv'}) ||
1.800 albertel 6735: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 6736: $okay=1;
6737: }
6738: }
1.216 www 6739: }
6740: }
1.213 www 6741: untie(%bighash);
6742: }
6743: return $okay;
1.31 www 6744: }
6745:
1.210 www 6746: # --------------------------------------------------------------- Clean-up symb
6747:
6748: sub symbclean {
6749: my $symb=shift;
1.568 albertel 6750: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6751: # remove version from map
6752: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6753:
1.210 www 6754: # remove version from URL
6755: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6756:
1.507 www 6757: # remove wrapper
6758:
1.510 www 6759: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6760: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6761: return $symb;
1.409 www 6762: }
6763:
6764: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6765:
6766: sub encode_symb {
6767: my ($map,$resid,$url)=@_;
6768: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6769: }
1.409 www 6770:
6771: sub decode_symb {
1.568 albertel 6772: my $symb=shift;
6773: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6774: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6775: return (&fixversion($map),$resid,&fixversion($url));
6776: }
6777:
6778: sub fixversion {
6779: my $fn=shift;
1.609 banghart 6780: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6781: my %bighash;
6782: my $uri=&clutter($fn);
1.620 albertel 6783: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6784: # is this cached?
1.599 albertel 6785: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6786: if (defined($cached)) { return $result; }
6787: # unfortunately not cached, or expired
1.620 albertel 6788: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6789: &GDBM_READER(),0640)) {
6790: if ($bighash{'version_'.$uri}) {
6791: my $version=$bighash{'version_'.$uri};
1.444 www 6792: unless (($version eq 'mostrecent') ||
6793: ($version==&getversion($uri))) {
1.440 www 6794: $uri=~s/\.(\w+)$/\.$version\.$1/;
6795: }
6796: }
6797: untie %bighash;
1.413 www 6798: }
1.599 albertel 6799: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6800: }
6801:
6802: sub deversion {
6803: my $url=shift;
6804: $url=~s/\.\d+\.(\w+)$/\.$1/;
6805: return $url;
1.210 www 6806: }
6807:
1.31 www 6808: # ------------------------------------------------------ Return symb list entry
6809:
6810: sub symbread {
1.249 www 6811: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6812: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6813: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6814: # no filename provided? try from environment
1.44 www 6815: unless ($thisfn) {
1.620 albertel 6816: if ($env{'request.symb'}) {
6817: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6818: }
1.620 albertel 6819: $thisfn=$env{'request.filename'};
1.44 www 6820: }
1.569 albertel 6821: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6822: # is that filename actually a symb? Verify, clean, and return
6823: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6824: if (&symbverify($thisfn,$1)) {
1.620 albertel 6825: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6826: }
1.242 www 6827: }
1.44 www 6828: $thisfn=declutter($thisfn);
1.31 www 6829: my %hash;
1.37 www 6830: my %bighash;
6831: my $syval='';
1.620 albertel 6832: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6833: my $targetfn = $thisfn;
1.609 banghart 6834: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6835: $targetfn = 'adm/wrapper/'.$thisfn;
6836: }
1.687 albertel 6837: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6838: $targetfn=$1;
6839: }
1.620 albertel 6840: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6841: &GDBM_READER(),0640)) {
1.481 raeburn 6842: $syval=$hash{$targetfn};
1.37 www 6843: untie(%hash);
6844: }
6845: # ---------------------------------------------------------- There was an entry
6846: if ($syval) {
1.601 albertel 6847: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6848: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6849: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6850: #return $env{$cache_str}='';
1.601 albertel 6851: #}
6852: #$syval.=$1;
6853: #}
1.37 www 6854: } else {
6855: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6856: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6857: &GDBM_READER(),0640)) {
1.37 www 6858: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6859: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6860: unless ($ids) {
6861: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6862: }
6863: unless ($ids) {
6864: # alias?
6865: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6866: }
1.37 www 6867: if ($ids) {
6868: # ------------------------------------------------------------------- Has ID(s)
6869: my @possibilities=split(/\,/,$ids);
1.39 www 6870: if ($#possibilities==0) {
6871: # ----------------------------------------------- There is only one possibility
1.37 www 6872: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6873: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6874: $resid,$thisfn);
1.249 www 6875: } elsif (!$donotrecurse) {
1.39 www 6876: # ------------------------------------------ There is more than one possibility
6877: my $realpossible=0;
1.800 albertel 6878: foreach my $id (@possibilities) {
6879: my $file=$bighash{'src_'.$id};
1.39 www 6880: if (&allowed('bre',$file)) {
1.800 albertel 6881: my ($mapid,$resid)=split(/\./,$id);
1.39 www 6882: if ($bighash{'map_type_'.$mapid} ne 'page') {
6883: $realpossible++;
1.626 albertel 6884: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6885: $resid,$thisfn);
1.39 www 6886: }
6887: }
1.191 harris41 6888: }
1.39 www 6889: if ($realpossible!=1) { $syval=''; }
1.249 www 6890: } else {
6891: $syval='';
1.37 www 6892: }
6893: }
6894: untie(%bighash)
1.481 raeburn 6895: }
1.31 www 6896: }
1.62 www 6897: if ($syval) {
1.620 albertel 6898: return $env{$cache_str}=$syval;
1.62 www 6899: }
1.31 www 6900: }
1.44 www 6901: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6902: return $env{$cache_str}='';
1.31 www 6903: }
6904:
6905: # ---------------------------------------------------------- Return random seed
6906:
1.32 www 6907: sub numval {
6908: my $txt=shift;
6909: $txt=~tr/A-J/0-9/;
6910: $txt=~tr/a-j/0-9/;
6911: $txt=~tr/K-T/0-9/;
6912: $txt=~tr/k-t/0-9/;
6913: $txt=~tr/U-Z/0-5/;
6914: $txt=~tr/u-z/0-5/;
6915: $txt=~s/\D//g;
1.564 albertel 6916: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6917: return int($txt);
1.368 albertel 6918: }
6919:
1.484 albertel 6920: sub numval2 {
6921: my $txt=shift;
6922: $txt=~tr/A-J/0-9/;
6923: $txt=~tr/a-j/0-9/;
6924: $txt=~tr/K-T/0-9/;
6925: $txt=~tr/k-t/0-9/;
6926: $txt=~tr/U-Z/0-5/;
6927: $txt=~tr/u-z/0-5/;
6928: $txt=~s/\D//g;
6929: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6930: my $total;
6931: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6932: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6933: return int($total);
6934: }
6935:
1.575 albertel 6936: sub numval3 {
6937: use integer;
6938: my $txt=shift;
6939: $txt=~tr/A-J/0-9/;
6940: $txt=~tr/a-j/0-9/;
6941: $txt=~tr/K-T/0-9/;
6942: $txt=~tr/k-t/0-9/;
6943: $txt=~tr/U-Z/0-5/;
6944: $txt=~tr/u-z/0-5/;
6945: $txt=~s/\D//g;
6946: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6947: my $total;
6948: foreach my $val (@txts) { $total+=$val; }
6949: if ($_64bit) { $total=(($total<<32)>>32); }
6950: return $total;
6951: }
6952:
1.675 albertel 6953: sub digest {
6954: my ($data)=@_;
6955: my $digest=&Digest::MD5::md5($data);
6956: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6957: my ($e,$f);
6958: {
6959: use integer;
6960: $e=($a+$b);
6961: $f=($c+$d);
6962: if ($_64bit) {
6963: $e=(($e<<32)>>32);
6964: $f=(($f<<32)>>32);
6965: }
6966: }
6967: if (wantarray) {
6968: return ($e,$f);
6969: } else {
6970: my $g;
6971: {
6972: use integer;
6973: $g=($e+$f);
6974: if ($_64bit) {
6975: $g=(($g<<32)>>32);
6976: }
6977: }
6978: return $g;
6979: }
6980: }
6981:
1.368 albertel 6982: sub latest_rnd_algorithm_id {
1.675 albertel 6983: return '64bit5';
1.366 albertel 6984: }
1.32 www 6985:
1.503 albertel 6986: sub get_rand_alg {
6987: my ($courseid)=@_;
1.790 albertel 6988: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 6989: if ($courseid) {
1.620 albertel 6990: return $env{"course.$courseid.rndseed"};
1.503 albertel 6991: }
6992: return &latest_rnd_algorithm_id();
6993: }
6994:
1.562 albertel 6995: sub validCODE {
6996: my ($CODE)=@_;
6997: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6998: return 0;
6999: }
7000:
1.491 albertel 7001: sub getCODE {
1.620 albertel 7002: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7003: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7004: defined($Apache::lonhomework::parsing_a_task) ) &&
7005: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7006: return $Apache::lonhomework::history{'resource.CODE'};
7007: }
7008: return undef;
7009: }
7010:
1.31 www 7011: sub rndseed {
1.155 albertel 7012: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7013: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155 albertel 7014: if (!$symb) {
1.366 albertel 7015: unless ($symb=$wsymb) { return time; }
7016: }
7017: if (!$courseid) { $courseid=$wcourseid; }
7018: if (!$domain) { $domain=$wdomain; }
7019: if (!$username) { $username=$wusername }
1.503 albertel 7020: my $which=&get_rand_alg();
1.803 albertel 7021:
1.491 albertel 7022: if (defined(&getCODE())) {
1.675 albertel 7023: if ($which eq '64bit5') {
7024: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7025: } elsif ($which eq '64bit4') {
1.575 albertel 7026: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7027: } else {
7028: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7029: }
1.675 albertel 7030: } elsif ($which eq '64bit5') {
7031: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7032: } elsif ($which eq '64bit4') {
7033: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7034: } elsif ($which eq '64bit3') {
7035: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7036: } elsif ($which eq '64bit2') {
7037: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7038: } elsif ($which eq '64bit') {
7039: return &rndseed_64bit($symb,$courseid,$domain,$username);
7040: }
7041: return &rndseed_32bit($symb,$courseid,$domain,$username);
7042: }
7043:
7044: sub rndseed_32bit {
7045: my ($symb,$courseid,$domain,$username)=@_;
7046: {
7047: use integer;
7048: my $symbchck=unpack("%32C*",$symb) << 27;
7049: my $symbseed=numval($symb) << 22;
7050: my $namechck=unpack("%32C*",$username) << 17;
7051: my $nameseed=numval($username) << 12;
7052: my $domainseed=unpack("%32C*",$domain) << 7;
7053: my $courseseed=unpack("%32C*",$courseid);
7054: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7055: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7056: #&logthis("rndseed :$num:$symb");
1.564 albertel 7057: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7058: return $num;
7059: }
7060: }
7061:
7062: sub rndseed_64bit {
7063: my ($symb,$courseid,$domain,$username)=@_;
7064: {
7065: use integer;
7066: my $symbchck=unpack("%32S*",$symb) << 21;
7067: my $symbseed=numval($symb) << 10;
7068: my $namechck=unpack("%32S*",$username);
7069:
7070: my $nameseed=numval($username) << 21;
7071: my $domainseed=unpack("%32S*",$domain) << 10;
7072: my $courseseed=unpack("%32S*",$courseid);
7073:
7074: my $num1=$symbchck+$symbseed+$namechck;
7075: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7076: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7077: #&logthis("rndseed :$num:$symb");
1.564 albertel 7078: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7079: return "$num1,$num2";
1.155 albertel 7080: }
1.366 albertel 7081: }
7082:
1.443 albertel 7083: sub rndseed_64bit2 {
7084: my ($symb,$courseid,$domain,$username)=@_;
7085: {
7086: use integer;
7087: # strings need to be an even # of cahracters long, it it is odd the
7088: # last characters gets thrown away
7089: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7090: my $symbseed=numval($symb) << 10;
7091: my $namechck=unpack("%32S*",$username.' ');
7092:
7093: my $nameseed=numval($username) << 21;
1.501 albertel 7094: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7095: my $courseseed=unpack("%32S*",$courseid.' ');
7096:
7097: my $num1=$symbchck+$symbseed+$namechck;
7098: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7100: #&logthis("rndseed :$num:$symb");
1.803 albertel 7101: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7102: return "$num1,$num2";
7103: }
7104: }
7105:
7106: sub rndseed_64bit3 {
7107: my ($symb,$courseid,$domain,$username)=@_;
7108: {
7109: use integer;
7110: # strings need to be an even # of cahracters long, it it is odd the
7111: # last characters gets thrown away
7112: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7113: my $symbseed=numval2($symb) << 10;
7114: my $namechck=unpack("%32S*",$username.' ');
7115:
7116: my $nameseed=numval2($username) << 21;
1.443 albertel 7117: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7118: my $courseseed=unpack("%32S*",$courseid.' ');
7119:
7120: my $num1=$symbchck+$symbseed+$namechck;
7121: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7122: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7123: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7124: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7125:
1.503 albertel 7126: return "$num1:$num2";
1.443 albertel 7127: }
7128: }
7129:
1.575 albertel 7130: sub rndseed_64bit4 {
7131: my ($symb,$courseid,$domain,$username)=@_;
7132: {
7133: use integer;
7134: # strings need to be an even # of cahracters long, it it is odd the
7135: # last characters gets thrown away
7136: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7137: my $symbseed=numval3($symb) << 10;
7138: my $namechck=unpack("%32S*",$username.' ');
7139:
7140: my $nameseed=numval3($username) << 21;
7141: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7142: my $courseseed=unpack("%32S*",$courseid.' ');
7143:
7144: my $num1=$symbchck+$symbseed+$namechck;
7145: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7146: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7147: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7148: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7149:
7150: return "$num1:$num2";
7151: }
7152: }
7153:
1.675 albertel 7154: sub rndseed_64bit5 {
7155: my ($symb,$courseid,$domain,$username)=@_;
7156: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7157: return "$num1:$num2";
7158: }
7159:
1.366 albertel 7160: sub rndseed_CODE_64bit {
7161: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7162: {
1.366 albertel 7163: use integer;
1.443 albertel 7164: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7165: my $symbseed=numval2($symb);
1.491 albertel 7166: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7167: my $CODEseed=numval(&getCODE());
1.443 albertel 7168: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7169: my $num1=$symbseed+$CODEchck;
7170: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7171: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7172: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7173: if ($_64bit) { $num1=(($num1<<32)>>32); }
7174: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7175: return "$num1:$num2";
1.366 albertel 7176: }
7177: }
7178:
1.575 albertel 7179: sub rndseed_CODE_64bit4 {
7180: my ($symb,$courseid,$domain,$username)=@_;
7181: {
7182: use integer;
7183: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7184: my $symbseed=numval3($symb);
7185: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7186: my $CODEseed=numval3(&getCODE());
7187: my $courseseed=unpack("%32S*",$courseid.' ');
7188: my $num1=$symbseed+$CODEchck;
7189: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7190: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7191: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7192: if ($_64bit) { $num1=(($num1<<32)>>32); }
7193: if ($_64bit) { $num2=(($num2<<32)>>32); }
7194: return "$num1:$num2";
7195: }
7196: }
7197:
1.675 albertel 7198: sub rndseed_CODE_64bit5 {
7199: my ($symb,$courseid,$domain,$username)=@_;
7200: my $code = &getCODE();
7201: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7202: return "$num1:$num2";
7203: }
7204:
1.366 albertel 7205: sub setup_random_from_rndseed {
7206: my ($rndseed)=@_;
1.503 albertel 7207: if ($rndseed =~/([,:])/) {
7208: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7209: &Math::Random::random_set_seed(abs($num1),abs($num2));
7210: } else {
7211: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7212: }
1.36 albertel 7213: }
7214:
1.474 albertel 7215: sub latest_receipt_algorithm_id {
1.835 albertel 7216: return 'receipt3';
1.474 albertel 7217: }
7218:
1.480 www 7219: sub recunique {
7220: my $fucourseid=shift;
7221: my $unique;
1.835 albertel 7222: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7223: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7224: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7225: } else {
7226: $unique=$perlvar{'lonReceipt'};
7227: }
7228: return unpack("%32C*",$unique);
7229: }
7230:
7231: sub recprefix {
7232: my $fucourseid=shift;
7233: my $prefix;
1.835 albertel 7234: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7235: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7236: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7237: } else {
7238: $prefix=$perlvar{'lonHostID'};
7239: }
7240: return unpack("%32C*",$prefix);
7241: }
7242:
1.76 www 7243: sub ireceipt {
1.474 albertel 7244: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7245:
7246: my $return =&recprefix($fucourseid).'-';
7247:
7248: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7249: $env{'request.state'} eq 'construct') {
7250: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7251: return $return;
7252: }
7253:
1.76 www 7254: my $cuname=unpack("%32C*",$funame);
7255: my $cudom=unpack("%32C*",$fudom);
7256: my $cucourseid=unpack("%32C*",$fucourseid);
7257: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7258: my $cunique=&recunique($fucourseid);
1.474 albertel 7259: my $cpart=unpack("%32S*",$part);
1.835 albertel 7260: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7261:
1.790 albertel 7262: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7263:
7264: $return.= ($cunique%$cuname+
7265: $cunique%$cudom+
7266: $cusymb%$cuname+
7267: $cusymb%$cudom+
7268: $cucourseid%$cuname+
7269: $cucourseid%$cudom+
7270: $cpart%$cuname+
7271: $cpart%$cudom);
7272: } else {
7273: $return.= ($cunique%$cuname+
7274: $cunique%$cudom+
7275: $cusymb%$cuname+
7276: $cusymb%$cudom+
7277: $cucourseid%$cuname+
7278: $cucourseid%$cudom);
7279: }
7280: return $return;
1.76 www 7281: }
7282:
7283: sub receipt {
1.474 albertel 7284: my ($part)=@_;
1.790 albertel 7285: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7286: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7287: }
1.260 ng 7288:
1.790 albertel 7289: sub whichuser {
7290: my ($passedsymb)=@_;
7291: my ($symb,$courseid,$domain,$name,$publicuser);
7292: if (defined($env{'form.grade_symb'})) {
7293: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7294: my $allowed=&allowed('vgr',$tmp_courseid);
7295: if (!$allowed &&
7296: exists($env{'request.course.sec'}) &&
7297: $env{'request.course.sec'} !~ /^\s*$/) {
7298: $allowed=&allowed('vgr',$tmp_courseid.
7299: '/'.$env{'request.course.sec'});
7300: }
7301: if ($allowed) {
7302: ($symb)=&get_env_multiple('form.grade_symb');
7303: $courseid=$tmp_courseid;
7304: ($domain)=&get_env_multiple('form.grade_domain');
7305: ($name)=&get_env_multiple('form.grade_username');
7306: return ($symb,$courseid,$domain,$name,$publicuser);
7307: }
7308: }
7309: if (!$passedsymb) {
7310: $symb=&symbread();
7311: } else {
7312: $symb=$passedsymb;
7313: }
7314: $courseid=$env{'request.course.id'};
7315: $domain=$env{'user.domain'};
7316: $name=$env{'user.name'};
7317: if ($name eq 'public' && $domain eq 'public') {
7318: if (!defined($env{'form.username'})) {
7319: $env{'form.username'}.=time.rand(10000000);
7320: }
7321: $name.=$env{'form.username'};
7322: }
7323: return ($symb,$courseid,$domain,$name,$publicuser);
7324:
7325: }
7326:
1.36 albertel 7327: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7328: # returns either the contents of the file or
7329: # -1 if the file doesn't exist
1.481 raeburn 7330: #
7331: # if the target is a file that was uploaded via DOCS,
7332: # a check will be made to see if a current copy exists on the local server,
7333: # if it does this will be served, otherwise a copy will be retrieved from
7334: # the home server for the course and stored in /home/httpd/html/userfiles on
7335: # the local server.
1.472 albertel 7336:
1.36 albertel 7337: sub getfile {
1.538 albertel 7338: my ($file) = @_;
1.609 banghart 7339: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7340: &repcopy($file);
7341: return &readfile($file);
7342: }
7343:
7344: sub repcopy_userfile {
7345: my ($file)=@_;
1.609 banghart 7346: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7347: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7348: my ($cdom,$cnum,$filename) =
1.811 albertel 7349: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7350: my $uri="/uploaded/$cdom/$cnum/$filename";
7351: if (-e "$file") {
1.828 www 7352: # we already have a local copy, check it out
1.538 albertel 7353: my @fileinfo = stat($file);
1.828 www 7354: my $rtncode;
7355: my $info;
1.538 albertel 7356: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7357: if ($lwpresp ne 'ok') {
1.828 www 7358: # there is no such file anymore, even though we had a local copy
1.482 albertel 7359: if ($rtncode eq '404') {
1.538 albertel 7360: unlink($file);
1.482 albertel 7361: }
7362: return -1;
7363: }
7364: if ($info < $fileinfo[9]) {
1.828 www 7365: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7366: return 'ok';
1.828 www 7367: } else {
7368: # the file is outdated, get rid of it
7369: unlink($file);
1.482 albertel 7370: }
1.828 www 7371: }
7372: # one way or the other, at this point, we don't have the file
7373: # construct the correct path for the file
7374: my @parts = ($cdom,$cnum);
7375: if ($filename =~ m|^(.+)/[^/]+$|) {
7376: push @parts, split(/\//,$1);
7377: }
7378: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7379: foreach my $part (@parts) {
7380: $path .= '/'.$part;
7381: if (!-e $path) {
7382: mkdir($path,0770);
1.482 albertel 7383: }
7384: }
1.828 www 7385: # now the path exists for sure
7386: # get a user agent
7387: my $ua=new LWP::UserAgent;
7388: my $transferfile=$file.'.in.transfer';
7389: # FIXME: this should flock
7390: if (-e $transferfile) { return 'ok'; }
7391: my $request;
7392: $uri=~s/^\///;
1.838 albertel 7393: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7394: my $response=$ua->request($request,$transferfile);
7395: # did it work?
7396: if ($response->is_error()) {
7397: unlink($transferfile);
7398: &logthis("Userfile repcopy failed for $uri");
7399: return -1;
7400: }
7401: # worked, rename the transfer file
7402: rename($transferfile,$file);
1.607 raeburn 7403: return 'ok';
1.481 raeburn 7404: }
7405:
1.517 albertel 7406: sub tokenwrapper {
7407: my $uri=shift;
1.552 albertel 7408: $uri=~s|^http\://([^/]+)||;
7409: $uri=~s|^/||;
1.620 albertel 7410: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7411: my $token=$1;
1.552 albertel 7412: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7413: if ($udom && $uname && $file) {
7414: $file=~s|(\?\.*)*$||;
1.620 albertel 7415: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7416: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7417: (($uri=~/\?/)?'&':'?').'token='.$token.
7418: '&tokenissued='.$perlvar{'lonHostID'};
7419: } else {
7420: return '/adm/notfound.html';
7421: }
7422: }
7423:
1.828 www 7424: # call with reqtype HEAD: get last modification time
7425: # call with reqtype GET: get the file contents
7426: # Do not call this with reqtype GET for large files! It loads everything into memory
7427: #
1.481 raeburn 7428: sub getuploaded {
7429: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7430: $uri=~s/^\///;
1.838 albertel 7431: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7432: my $ua=new LWP::UserAgent;
7433: my $request=new HTTP::Request($reqtype,$uri);
7434: my $response=$ua->request($request);
7435: $$rtncode = $response->code;
1.482 albertel 7436: if (! $response->is_success()) {
7437: return 'failed';
7438: }
7439: if ($reqtype eq 'HEAD') {
1.486 www 7440: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7441: } elsif ($reqtype eq 'GET') {
7442: $$info = $response->content;
1.472 albertel 7443: }
1.482 albertel 7444: return 'ok';
1.36 albertel 7445: }
7446:
1.481 raeburn 7447: sub readfile {
7448: my $file = shift;
7449: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7450: my $fh;
7451: open($fh,"<$file");
7452: my $a='';
1.800 albertel 7453: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7454: return $a;
7455: }
7456:
1.36 albertel 7457: sub filelocation {
1.590 banghart 7458: my ($dir,$file) = @_;
7459: my $location;
7460: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7461:
7462: if ($file =~ m-^/adm/-) {
7463: $file=~s-^/adm/wrapper/-/-;
7464: $file=~s-^/adm/coursedocs/showdoc/-/-;
7465: }
1.590 banghart 7466: if ($file=~m:^/~:) { # is a contruction space reference
7467: $location = $file;
7468: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7469: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7470: # is a correct contruction space reference
7471: $location = $file;
1.609 banghart 7472: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7473: my ($udom,$uname,$filename)=
1.811 albertel 7474: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7475: my $home=&homeserver($uname,$udom);
7476: my $is_me=0;
7477: my @ids=¤t_machine_ids();
7478: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7479: if ($is_me) {
1.740 www 7480: $location=&propath($udom,$uname).
1.590 banghart 7481: '/userfiles/'.$filename;
7482: } else {
7483: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7484: $udom.'/'.$uname.'/'.$filename;
7485: }
7486: } else {
7487: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7488: $file=~s:^/res/:/:;
7489: if ( !( $file =~ m:^/:) ) {
7490: $location = $dir. '/'.$file;
7491: } else {
7492: $location = '/home/httpd/html/res'.$file;
7493: }
1.59 albertel 7494: }
1.590 banghart 7495: $location=~s://+:/:g; # remove duplicate /
7496: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7497: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7498: return $location;
1.46 www 7499: }
1.36 albertel 7500:
1.46 www 7501: sub hreflocation {
7502: my ($dir,$file)=@_;
1.460 albertel 7503: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7504: $file=filelocation($dir,$file);
1.700 albertel 7505: } elsif ($file=~m-^/adm/-) {
7506: $file=~s-^/adm/wrapper/-/-;
7507: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7508: }
7509: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7510: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7511: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7512: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7513: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7514: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7515: -/uploaded/$1/$2/-x;
1.46 www 7516: }
1.462 albertel 7517: return $file;
1.465 albertel 7518: }
7519:
7520: sub current_machine_domains {
1.853 albertel 7521: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7522: }
7523:
7524: sub machine_domains {
7525: my ($hostname) = @_;
1.465 albertel 7526: my @domains;
1.838 albertel 7527: my %hostname = &all_hostnames();
1.465 albertel 7528: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7529: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7530: if ($hostname eq $name) {
1.844 albertel 7531: push(@domains,&host_domain($id));
1.465 albertel 7532: }
7533: }
7534: return @domains;
7535: }
7536:
7537: sub current_machine_ids {
1.853 albertel 7538: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7539: }
7540:
7541: sub machine_ids {
7542: my ($hostname) = @_;
7543: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7544: my @ids;
1.838 albertel 7545: my %hostname = &all_hostnames();
1.465 albertel 7546: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7547: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7548: if ($hostname eq $name) {
7549: push(@ids,$id);
7550: }
7551: }
7552: return @ids;
1.31 www 7553: }
7554:
1.824 raeburn 7555: sub additional_machine_domains {
7556: my @domains;
7557: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7558: while( my $line = <$fh>) {
7559: $line =~ s/\s//g;
7560: push(@domains,$line);
7561: }
7562: return @domains;
7563: }
7564:
7565: sub default_login_domain {
7566: my $domain = $perlvar{'lonDefDomain'};
7567: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7568: foreach my $posdom (¤t_machine_domains(),
7569: &additional_machine_domains()) {
7570: if (lc($posdom) eq lc($testdomain)) {
7571: $domain=$posdom;
7572: last;
7573: }
7574: }
7575: return $domain;
7576: }
7577:
1.31 www 7578: # ------------------------------------------------------------- Declutters URLs
7579:
7580: sub declutter {
7581: my $thisfn=shift;
1.569 albertel 7582: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7583: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7584: $thisfn=~s/^\///;
1.697 albertel 7585: $thisfn=~s|^adm/wrapper/||;
7586: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7587: $thisfn=~s/^res\///;
1.235 www 7588: $thisfn=~s/\?.+$//;
1.268 www 7589: return $thisfn;
7590: }
7591:
7592: # ------------------------------------------------------------- Clutter up URLs
7593:
7594: sub clutter {
7595: my $thisfn='/'.&declutter(shift);
1.609 banghart 7596: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7597: $thisfn='/res'.$thisfn;
7598: }
1.694 albertel 7599: if ($thisfn !~m|/adm|) {
1.695 albertel 7600: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7601: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7602: } else {
7603: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7604: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7605: if ($embstyle eq 'ssi'
7606: || ($embstyle eq 'hdn')
7607: || ($embstyle eq 'rat')
7608: || ($embstyle eq 'prv')
7609: || ($embstyle eq 'ign')) {
7610: #do nothing with these
7611: } elsif (($embstyle eq 'img')
1.695 albertel 7612: || ($embstyle eq 'emb')
7613: || ($embstyle eq 'wrp')) {
7614: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7615: } elsif ($embstyle eq 'unk'
7616: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7617: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7618: } else {
1.718 www 7619: # &logthis("Got a blank emb style");
1.695 albertel 7620: }
1.694 albertel 7621: }
7622: }
1.31 www 7623: return $thisfn;
1.12 www 7624: }
7625:
1.787 albertel 7626: sub clutter_with_no_wrapper {
7627: my $uri = &clutter(shift);
7628: if ($uri =~ m-^/adm/-) {
7629: $uri =~ s-^/adm/wrapper/-/-;
7630: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7631: }
7632: return $uri;
7633: }
7634:
1.557 albertel 7635: sub freeze_escape {
7636: my ($value)=@_;
7637: if (ref($value)) {
7638: $value=&nfreeze($value);
7639: return '__FROZEN__'.&escape($value);
7640: }
7641: return &escape($value);
7642: }
7643:
1.11 www 7644:
1.557 albertel 7645: sub thaw_unescape {
7646: my ($value)=@_;
7647: if ($value =~ /^__FROZEN__/) {
7648: substr($value,0,10,undef);
7649: $value=&unescape($value);
7650: return &thaw($value);
7651: }
7652: return &unescape($value);
7653: }
7654:
1.436 albertel 7655: sub correct_line_ends {
7656: my ($result)=@_;
7657: $$result =~s/\r\n/\n/mg;
7658: $$result =~s/\r/\n/mg;
1.415 albertel 7659: }
1.1 albertel 7660: # ================================================================ Main Program
7661:
1.184 www 7662: sub goodbye {
1.204 albertel 7663: &logthis("Starting Shut down");
1.443 albertel 7664: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 7665: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 7666: #converted
1.599 albertel 7667: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 7668: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
7669: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
7670: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 7671: #1.1 only
1.870 albertel 7672: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
7673: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
7674: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
7675: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
7676: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 7677: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7678: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7679: &flushcourselogs();
7680: &logthis("Shutting down");
7681: }
7682:
1.852 albertel 7683: sub get_dns {
1.869 albertel 7684: my ($url,$func,$ignore_cache) = @_;
7685: if (!$ignore_cache) {
7686: my ($content,$cached)=
7687: &Apache::lonnet::is_cached_new('dns',$url);
7688: if ($cached) {
7689: &$func($content);
7690: return;
7691: }
7692: }
7693:
7694: my %alldns;
1.852 albertel 7695: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7696: foreach my $dns (<$config>) {
7697: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 7698: $alldns{$1} = 1;
7699: }
7700: while (%alldns) {
7701: my ($dns) = keys(%alldns);
7702: delete($alldns{$dns});
1.852 albertel 7703: my $ua=new LWP::UserAgent;
7704: my $request=new HTTP::Request('GET',"http://$dns$url");
7705: my $response=$ua->request($request);
7706: next if ($response->is_error());
7707: my @content = split("\n",$response->content);
1.869 albertel 7708: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 7709: &$func(\@content);
1.869 albertel 7710: return;
1.852 albertel 7711: }
7712: close($config);
1.871 ! albertel 7713: my $which = (split('/',$url))[3];
! 7714: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
! 7715: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 7716: my @content = <$config>;
7717: &$func(\@content);
7718: return;
1.852 albertel 7719: }
1.327 albertel 7720: # ------------------------------------------------------------ Read domain file
7721: {
1.852 albertel 7722: my $loaded;
1.846 albertel 7723: my %domain;
7724:
1.852 albertel 7725: sub parse_domain_tab {
7726: my ($lines) = @_;
7727: foreach my $line (@$lines) {
7728: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 7729:
1.846 albertel 7730: chomp($line);
1.852 albertel 7731: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 7732: my %this_domain;
7733: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7734: 'lang_def', 'city', 'longi', 'lati',
7735: 'primary') {
7736: $this_domain{$field} = shift(@elements);
7737: }
7738: $domain{$name} = \%this_domain;
1.852 albertel 7739: }
7740: }
1.864 albertel 7741:
7742: sub reset_domain_info {
7743: undef($loaded);
7744: undef(%domain);
7745: }
7746:
1.852 albertel 7747: sub load_domain_tab {
1.869 albertel 7748: my ($ignore_cache) = @_;
7749: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 7750: my $fh;
7751: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7752: my @lines = <$fh>;
7753: &parse_domain_tab(\@lines);
1.448 albertel 7754: }
1.852 albertel 7755: close($fh);
7756: $loaded = 1;
1.327 albertel 7757: }
1.846 albertel 7758:
7759: sub domain {
1.852 albertel 7760: &load_domain_tab() if (!$loaded);
7761:
1.846 albertel 7762: my ($name,$what) = @_;
7763: return if ( !exists($domain{$name}) );
7764:
7765: if (!$what) {
7766: return $domain{$name}{'description'};
7767: }
7768: return $domain{$name}{$what};
7769: }
1.327 albertel 7770: }
7771:
7772:
1.1 albertel 7773: # ------------------------------------------------------------- Read hosts file
7774: {
1.838 albertel 7775: my %hostname;
1.844 albertel 7776: my %hostdom;
1.845 albertel 7777: my %libserv;
1.852 albertel 7778: my $loaded;
7779:
7780: sub parse_hosts_tab {
7781: my ($file) = @_;
7782: foreach my $configline (@$file) {
7783: next if ($configline =~ /^(\#|\s*$ )/x);
7784: next if ($configline =~ /^\^/);
7785: chomp($configline);
7786: my ($id,$domain,$role,$name)=split(/:/,$configline);
7787: $name=~s/\s//g;
7788: if ($id && $domain && $role && $name) {
7789: $hostname{$id}=$name;
7790: $hostdom{$id}=$domain;
7791: if ($role eq 'library') { $libserv{$id}=$name; }
7792: }
7793: }
7794: }
1.864 albertel 7795:
7796: sub reset_hosts_info {
7797: &reset_domain_info();
7798: &reset_hosts_ip_info();
7799: undef(%hostname);
7800: undef(%hostdom);
7801: undef(%libserv);
7802: undef($loaded);
7803: }
1.1 albertel 7804:
1.852 albertel 7805: sub load_hosts_tab {
1.869 albertel 7806: my ($ignore_cache) = @_;
7807: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 7808: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7809: my @config = <$config>;
7810: &parse_hosts_tab(\@config);
7811: close($config);
7812: $loaded=1;
1.1 albertel 7813: }
1.852 albertel 7814:
1.838 albertel 7815: sub hostname {
1.852 albertel 7816: &load_hosts_tab() if (!$loaded);
7817:
1.838 albertel 7818: my ($lonid) = @_;
7819: return $hostname{$lonid};
7820: }
1.845 albertel 7821:
1.838 albertel 7822: sub all_hostnames {
1.852 albertel 7823: &load_hosts_tab() if (!$loaded);
7824:
1.838 albertel 7825: return %hostname;
7826: }
1.845 albertel 7827:
7828: sub is_library {
1.852 albertel 7829: &load_hosts_tab() if (!$loaded);
7830:
1.845 albertel 7831: return exists($libserv{$_[0]});
7832: }
7833:
7834: sub all_library {
1.852 albertel 7835: &load_hosts_tab() if (!$loaded);
7836:
1.845 albertel 7837: return %libserv;
7838: }
7839:
1.841 albertel 7840: sub get_servers {
1.852 albertel 7841: &load_hosts_tab() if (!$loaded);
7842:
1.841 albertel 7843: my ($domain,$type) = @_;
7844: my %possible_hosts = ($type eq 'library') ? %libserv
7845: : %hostname;
7846: my %result;
1.842 albertel 7847: if (ref($domain) eq 'ARRAY') {
7848: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 7849: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 7850: $result{$host} = $hostname;
7851: }
7852: }
7853: } else {
7854: while ( my ($host,$hostname) = each(%possible_hosts)) {
7855: if ($hostdom{$host} eq $domain) {
7856: $result{$host} = $hostname;
7857: }
1.841 albertel 7858: }
7859: }
7860: return %result;
7861: }
1.845 albertel 7862:
1.844 albertel 7863: sub host_domain {
1.852 albertel 7864: &load_hosts_tab() if (!$loaded);
7865:
1.844 albertel 7866: my ($lonid) = @_;
7867: return $hostdom{$lonid};
7868: }
7869:
1.841 albertel 7870: sub all_domains {
1.852 albertel 7871: &load_hosts_tab() if (!$loaded);
7872:
1.841 albertel 7873: my %seen;
7874: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7875: return @uniq;
7876: }
1.1 albertel 7877: }
7878:
1.847 albertel 7879: {
7880: my %iphost;
1.856 albertel 7881: my %name_to_ip;
7882: my %lonid_to_ip;
1.869 albertel 7883:
7884: my %valid_ip;
7885: sub valid_ip {
7886: my ($ip) = @_;
7887: if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
7888: return 1;
7889: }
7890: my $name = gethostbyip($ip);
7891: my $lonid = &hostname($name);
7892: if (defined($lonid)) {
7893: $valid_ip{$ip} = $lonid;
7894: return 1;
7895: }
7896: my %iphosts = &get_iphost();
7897: if (ref($iphost{$ip})) {
7898: return 1;
7899: }
7900: }
7901:
1.847 albertel 7902: sub get_hosts_from_ip {
7903: my ($ip) = @_;
7904: my %iphosts = &get_iphost();
7905: if (ref($iphosts{$ip})) {
7906: return @{$iphosts{$ip}};
7907: }
7908: return;
1.839 albertel 7909: }
1.864 albertel 7910:
7911: sub reset_hosts_ip_info {
7912: undef(%iphost);
7913: undef(%name_to_ip);
7914: undef(%lonid_to_ip);
7915: }
1.856 albertel 7916:
7917: sub get_host_ip {
7918: my ($lonid) = @_;
7919: if (exists($lonid_to_ip{$lonid})) {
7920: return $lonid_to_ip{$lonid};
7921: }
7922: my $name=&hostname($lonid);
7923: my $ip = gethostbyname($name);
7924: return if (!$ip || length($ip) ne 4);
7925: $ip=inet_ntoa($ip);
7926: $name_to_ip{$name} = $ip;
7927: $lonid_to_ip{$lonid} = $ip;
7928: return $ip;
7929: }
1.847 albertel 7930:
7931: sub get_iphost {
1.869 albertel 7932: my ($ignore_cache) = @_;
7933: if (!$ignore_cache) {
7934: if (%iphost) {
7935: return %iphost;
7936: }
7937: my ($ip_info,$cached)=
7938: &Apache::lonnet::is_cached_new('iphost','iphost');
7939: if ($cached) {
7940: %iphost = %{$ip_info->[0]};
7941: %name_to_ip = %{$ip_info->[1]};
7942: %lonid_to_ip = %{$ip_info->[2]};
7943: return %iphost;
7944: }
7945: }
1.847 albertel 7946: my %hostname = &all_hostnames();
7947: foreach my $id (keys(%hostname)) {
1.864 albertel 7948: my $name=&hostname($id);
1.847 albertel 7949: my $ip;
7950: if (!exists($name_to_ip{$name})) {
7951: $ip = gethostbyname($name);
7952: if (!$ip || length($ip) ne 4) {
7953: &logthis("Skipping host $id name $name no IP found");
7954: next;
7955: }
7956: $ip=inet_ntoa($ip);
7957: $name_to_ip{$name} = $ip;
7958: } else {
7959: $ip = $name_to_ip{$name};
1.653 albertel 7960: }
1.856 albertel 7961: $lonid_to_ip{$id} = $ip;
1.847 albertel 7962: push(@{$iphost{$ip}},$id);
1.598 albertel 7963: }
1.869 albertel 7964: &Apache::lonnet::do_cache_new('iphost','iphost',
7965: [\%iphost,\%name_to_ip,\%lonid_to_ip],
7966: 24*60*60);
7967:
1.847 albertel 7968: return %iphost;
1.598 albertel 7969: }
7970: }
7971:
1.862 albertel 7972: BEGIN {
7973:
7974: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7975: unless ($readit) {
7976: {
7977: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7978: %perlvar = (%perlvar,%{$configvars});
7979: }
7980:
7981:
1.1 albertel 7982: # ------------------------------------------------------ Read spare server file
7983: {
1.448 albertel 7984: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7985:
7986: while (my $configline=<$config>) {
7987: chomp($configline);
1.284 matthew 7988: if ($configline) {
1.784 albertel 7989: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7990: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7991: push(@{ $spareid{$type} }, $host);
1.1 albertel 7992: }
7993: }
1.448 albertel 7994: close($config);
1.1 albertel 7995: }
1.11 www 7996: # ------------------------------------------------------------ Read permissions
7997: {
1.448 albertel 7998: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7999:
8000: while (my $configline=<$config>) {
1.448 albertel 8001: chomp($configline);
8002: if ($configline) {
8003: my ($role,$perm)=split(/ /,$configline);
8004: if ($perm ne '') { $pr{$role}=$perm; }
8005: }
1.11 www 8006: }
1.448 albertel 8007: close($config);
1.11 www 8008: }
8009:
8010: # -------------------------------------------- Read plain texts for permissions
8011: {
1.448 albertel 8012: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8013:
8014: while (my $configline=<$config>) {
1.448 albertel 8015: chomp($configline);
8016: if ($configline) {
1.742 raeburn 8017: my ($short,@plain)=split(/:/,$configline);
8018: %{$prp{$short}} = ();
8019: if (@plain > 0) {
8020: $prp{$short}{'std'} = $plain[0];
8021: for (my $i=1; $i<@plain; $i++) {
8022: $prp{$short}{'alt'.$i} = $plain[$i];
8023: }
8024: }
1.448 albertel 8025: }
1.135 www 8026: }
1.448 albertel 8027: close($config);
1.135 www 8028: }
8029:
8030: # ---------------------------------------------------------- Read package table
8031: {
1.448 albertel 8032: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8033:
8034: while (my $configline=<$config>) {
1.483 albertel 8035: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8036: chomp($configline);
8037: my ($short,$plain)=split(/:/,$configline);
8038: my ($pack,$name)=split(/\&/,$short);
8039: if ($plain ne '') {
8040: $packagetab{$pack.'&'.$name.'&name'}=$name;
8041: $packagetab{$short}=$plain;
8042: }
1.11 www 8043: }
1.448 albertel 8044: close($config);
1.329 matthew 8045: }
8046:
8047: # ------------- set up temporary directory
8048: {
8049: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8050:
1.11 www 8051: }
8052:
1.794 albertel 8053: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8054: 'compress_threshold'=> 20_000,
8055: });
1.185 www 8056:
1.281 www 8057: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8058: $dumpcount=0;
1.22 www 8059:
1.163 harris41 8060: &logtouch();
1.672 albertel 8061: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8062: $readit=1;
1.564 albertel 8063: {
8064: use integer;
8065: my $test=(2**32)+1;
1.568 albertel 8066: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8067: &logthis(" Detected 64bit platform ($_64bit)");
8068: }
1.195 www 8069: }
1.1 albertel 8070: }
1.179 www 8071:
1.1 albertel 8072: 1;
1.191 harris41 8073: __END__
8074:
1.243 albertel 8075: =pod
8076:
1.191 harris41 8077: =head1 NAME
8078:
1.243 albertel 8079: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8080:
8081: =head1 SYNOPSIS
8082:
1.243 albertel 8083: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8084:
8085: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8086:
1.243 albertel 8087: Common parameters:
8088:
8089: =over 4
8090:
8091: =item *
8092:
8093: $uname : an internal username (if $cname expecting a course Id specifically)
8094:
8095: =item *
8096:
8097: $udom : a domain (if $cdom expecting a course's domain specifically)
8098:
8099: =item *
8100:
8101: $symb : a resource instance identifier
8102:
8103: =item *
8104:
8105: $namespace : the name of a .db file that contains the data needed or
8106: being set.
8107:
8108: =back
8109:
1.394 bowersj2 8110: =head1 OVERVIEW
1.191 harris41 8111:
1.394 bowersj2 8112: lonnet provides subroutines which interact with the
8113: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8114: about classes, users, and resources.
1.243 albertel 8115:
8116: For many of these objects you can also use this to store data about
8117: them or modify them in various ways.
1.191 harris41 8118:
1.394 bowersj2 8119: =head2 Symbs
1.191 harris41 8120:
1.394 bowersj2 8121: To identify a specific instance of a resource, LON-CAPA uses symbols
8122: or "symbs"X<symb>. These identifiers are built from the URL of the
8123: map, the resource number of the resource in the map, and the URL of
8124: the resource itself. The latter is somewhat redundant, but might help
8125: if maps change.
8126:
8127: An example is
8128:
8129: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8130:
8131: The respective map entry is
8132:
8133: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8134: title="Problem 2">
8135: </resource>
8136:
8137: Symbs are used by the random number generator, as well as to store and
8138: restore data specific to a certain instance of for example a problem.
8139:
8140: =head2 Storing And Retrieving Data
8141:
8142: X<store()>X<cstore()>X<restore()>Three of the most important functions
8143: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8144: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8145: is is the non-critical message twin of cstore. These functions are for
8146: handlers to store a perl hash to a user's permanent data space in an
8147: easy manner, and to retrieve it again on another call. It is expected
8148: that a handler would use this once at the beginning to retrieve data,
8149: and then again once at the end to send only the new data back.
8150:
8151: The data is stored in the user's data directory on the user's
8152: homeserver under the ID of the course.
8153:
8154: The hash that is returned by restore will have all of the previous
8155: value for all of the elements of the hash.
8156:
8157: Example:
8158:
8159: #creating a hash
8160: my %hash;
8161: $hash{'foo'}='bar';
8162:
8163: #storing it
8164: &Apache::lonnet::cstore(\%hash);
8165:
8166: #changing a value
8167: $hash{'foo'}='notbar';
8168:
8169: #adding a new value
8170: $hash{'bar'}='foo';
8171: &Apache::lonnet::cstore(\%hash);
8172:
8173: #retrieving the hash
8174: my %history=&Apache::lonnet::restore();
8175:
8176: #print the hash
8177: foreach my $key (sort(keys(%history))) {
8178: print("\%history{$key} = $history{$key}");
8179: }
8180:
8181: Will print out:
1.191 harris41 8182:
1.394 bowersj2 8183: %history{1:foo} = bar
8184: %history{1:keys} = foo:timestamp
8185: %history{1:timestamp} = 990455579
8186: %history{2:bar} = foo
8187: %history{2:foo} = notbar
8188: %history{2:keys} = foo:bar:timestamp
8189: %history{2:timestamp} = 990455580
8190: %history{bar} = foo
8191: %history{foo} = notbar
8192: %history{timestamp} = 990455580
8193: %history{version} = 2
8194:
8195: Note that the special hash entries C<keys>, C<version> and
8196: C<timestamp> were added to the hash. C<version> will be equal to the
8197: total number of versions of the data that have been stored. The
8198: C<timestamp> attribute will be the UNIX time the hash was
8199: stored. C<keys> is available in every historical section to list which
8200: keys were added or changed at a specific historical revision of a
8201: hash.
8202:
8203: B<Warning>: do not store the hash that restore returns directly. This
8204: will cause a mess since it will restore the historical keys as if the
8205: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8206:
1.394 bowersj2 8207: Calling convention:
1.191 harris41 8208:
1.394 bowersj2 8209: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8210: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8211:
1.394 bowersj2 8212: For more detailed information, see lonnet specific documentation.
1.191 harris41 8213:
1.394 bowersj2 8214: =head1 RETURN MESSAGES
1.191 harris41 8215:
1.394 bowersj2 8216: =over 4
1.191 harris41 8217:
1.394 bowersj2 8218: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8219:
1.394 bowersj2 8220: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8221: when the connection is brought back up
1.191 harris41 8222:
1.394 bowersj2 8223: =item * B<con_failed>: unable to contact remote host and unable to save message
8224: for later delivery
1.191 harris41 8225:
1.394 bowersj2 8226: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8227:
1.394 bowersj2 8228: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8229: that was requested
1.191 harris41 8230:
1.243 albertel 8231: =back
1.191 harris41 8232:
1.243 albertel 8233: =head1 PUBLIC SUBROUTINES
1.191 harris41 8234:
1.243 albertel 8235: =head2 Session Environment Functions
1.191 harris41 8236:
1.243 albertel 8237: =over 4
1.191 harris41 8238:
1.394 bowersj2 8239: =item *
8240: X<appenv()>
8241: B<appenv(%hash)>: the value of %hash is written to
8242: the user envirnoment file, and will be restored for each access this
1.620 albertel 8243: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8244: process
1.191 harris41 8245:
8246: =item *
1.394 bowersj2 8247: X<delenv()>
8248: B<delenv($regexp)>: removes all items from the session
8249: environment file that matches the regular expression in $regexp. The
1.620 albertel 8250: values are also delted from the current processes %env.
1.191 harris41 8251:
1.795 albertel 8252: =item * get_env_multiple($name)
8253:
8254: gets $name from the %env hash, it seemlessly handles the cases where multiple
8255: values may be defined and end up as an array ref.
8256:
8257: returns an array of values
8258:
1.243 albertel 8259: =back
8260:
8261: =head2 User Information
1.191 harris41 8262:
1.243 albertel 8263: =over 4
1.191 harris41 8264:
8265: =item *
1.394 bowersj2 8266: X<queryauthenticate()>
8267: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8268: authentication scheme
8269:
8270: =item *
1.394 bowersj2 8271: X<authenticate()>
8272: B<authenticate($uname,$upass,$udom)>: try to
8273: authenticate user from domain's lib servers (first use the current
8274: one). C<$upass> should be the users password.
1.191 harris41 8275:
8276: =item *
1.394 bowersj2 8277: X<homeserver()>
8278: B<homeserver($uname,$udom)>: find the server which has
8279: the user's directory and files (there must be only one), this caches
8280: the answer, and also caches if there is a borken connection.
1.191 harris41 8281:
8282: =item *
1.394 bowersj2 8283: X<idget()>
8284: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8285: (IDs are a unique resource in a domain, there must be only 1 ID per
8286: username, and only 1 username per ID in a specific domain) (returns
8287: hash: id=>name,id=>name)
1.191 harris41 8288:
8289: =item *
1.394 bowersj2 8290: X<idrget()>
8291: B<idrget($udom,@unames)>: find the IDs behind a list of
8292: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8293:
8294: =item *
1.394 bowersj2 8295: X<idput()>
8296: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8297:
8298: =item *
1.394 bowersj2 8299: X<rolesinit()>
8300: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8301:
8302: =item *
1.551 albertel 8303: X<getsection()>
8304: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8305: course $cname, return section name/number or '' for "not in course"
8306: and '-1' for "no section"
8307:
8308: =item *
1.394 bowersj2 8309: X<userenvironment()>
8310: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8311: passed in @what from the requested user's environment, returns a hash
8312:
1.858 raeburn 8313: =item *
8314: X<userlog_query()>
1.859 albertel 8315: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8316: activity.log file. %filters defines filters applied when parsing the
8317: log file. These can be start or end timestamps, or the type of action
8318: - log to look for Login or Logout events, check for Checkin or
8319: Checkout, role for role selection. The response is in the form
8320: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8321: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8322:
1.243 albertel 8323: =back
8324:
8325: =head2 User Roles
8326:
8327: =over 4
8328:
8329: =item *
8330:
1.810 raeburn 8331: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8332: F: full access
8333: U,I,K: authentication modes (cxx only)
8334: '': forbidden
8335: 1: user needs to choose course
8336: 2: browse allowed
1.766 albertel 8337: A: passphrase authentication needed
1.243 albertel 8338:
8339: =item *
8340:
8341: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8342: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8343: and course level
8344:
8345: =item *
8346:
8347: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8348: explanation of a user role term
8349:
1.832 raeburn 8350: =item *
8351:
1.858 raeburn 8352: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8353: All arguments are optional. Returns a hash of a roles, either for
8354: co-author/assistant author roles for a user's Construction Space
8355: (default), or if $context is 'user', roles for the user himself,
8356: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8357: and value is set to colon-separated start and end times for the role.
8358: If no username and domain are specified, will default to current
8359: user/domain. Types, roles, and roledoms are references to arrays,
8360: of role statuses (active, future or previous), roles
8361: (e.g., cc,in, st etc.) and domains of the roles which can be used
8362: to restrict the list of roles reported. If no array ref is
8363: provided for types, will default to return only active roles.
1.834 albertel 8364:
1.243 albertel 8365: =back
8366:
8367: =head2 User Modification
8368:
8369: =over 4
8370:
8371: =item *
8372:
8373: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8374: user for the level given by URL. Optional start and end dates (leave empty
8375: string or zero for "no date")
1.191 harris41 8376:
8377: =item *
8378:
1.243 albertel 8379: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8380: change a users, password, possible return values are: ok,
8381: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8382: refused
1.191 harris41 8383:
8384: =item *
8385:
1.243 albertel 8386: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8387:
8388: =item *
8389:
1.243 albertel 8390: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8391: modify user
1.191 harris41 8392:
8393: =item *
8394:
1.286 matthew 8395: modifystudent
8396:
8397: modify a students enrollment and identification information.
8398: The course id is resolved based on the current users environment.
8399: This means the envoking user must be a course coordinator or otherwise
8400: associated with a course.
8401:
1.297 matthew 8402: This call is essentially a wrapper for lonnet::modifyuser and
8403: lonnet::modify_student_enrollment
1.286 matthew 8404:
8405: Inputs:
8406:
8407: =over 4
8408:
8409: =item B<$udom> Students loncapa domain
8410:
8411: =item B<$uname> Students loncapa login name
8412:
8413: =item B<$uid> Students id/student number
8414:
8415: =item B<$umode> Students authentication mode
8416:
8417: =item B<$upass> Students password
8418:
8419: =item B<$first> Students first name
8420:
8421: =item B<$middle> Students middle name
8422:
8423: =item B<$last> Students last name
8424:
8425: =item B<$gene> Students generation
8426:
8427: =item B<$usec> Students section in course
8428:
8429: =item B<$end> Unix time of the roles expiration
8430:
8431: =item B<$start> Unix time of the roles start date
8432:
8433: =item B<$forceid> If defined, allow $uid to be changed
8434:
8435: =item B<$desiredhome> server to use as home server for student
8436:
8437: =back
1.297 matthew 8438:
8439: =item *
8440:
8441: modify_student_enrollment
8442:
8443: Change a students enrollment status in a class. The environment variable
8444: 'role.request.course' must be defined for this function to proceed.
8445:
8446: Inputs:
8447:
8448: =over 4
8449:
8450: =item $udom, students domain
8451:
8452: =item $uname, students name
8453:
8454: =item $uid, students user id
8455:
8456: =item $first, students first name
8457:
8458: =item $middle
8459:
8460: =item $last
8461:
8462: =item $gene
8463:
8464: =item $usec
8465:
8466: =item $end
8467:
8468: =item $start
8469:
8470: =back
8471:
1.191 harris41 8472:
8473: =item *
8474:
1.243 albertel 8475: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8476: custom role; give a custom role to a user for the level given by URL. Specify
8477: name and domain of role author, and role name
1.191 harris41 8478:
8479: =item *
8480:
1.243 albertel 8481: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8482:
8483: =item *
8484:
1.243 albertel 8485: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8486:
8487: =back
8488:
8489: =head2 Course Infomation
8490:
8491: =over 4
1.191 harris41 8492:
8493: =item *
8494:
1.631 albertel 8495: coursedescription($courseid) : returns a hash of information about the
8496: specified course id, including all environment settings for the
8497: course, the description of the course will be in the hash under the
8498: key 'description'
1.191 harris41 8499:
8500: =item *
8501:
1.624 albertel 8502: resdata($name,$domain,$type,@which) : request for current parameter
8503: setting for a specific $type, where $type is either 'course' or 'user',
8504: @what should be a list of parameters to ask about. This routine caches
8505: answers for 5 minutes.
1.243 albertel 8506:
8507: =back
8508:
8509: =head2 Course Modification
8510:
8511: =over 4
1.191 harris41 8512:
8513: =item *
8514:
1.243 albertel 8515: writecoursepref($courseid,%prefs) : write preferences (environment
8516: database) for a course
1.191 harris41 8517:
8518: =item *
8519:
1.243 albertel 8520: createcourse($udom,$description,$url) : make/modify course
8521:
8522: =back
8523:
8524: =head2 Resource Subroutines
8525:
8526: =over 4
1.191 harris41 8527:
8528: =item *
8529:
1.243 albertel 8530: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8531:
8532: =item *
8533:
1.243 albertel 8534: repcopy($filename) : subscribes to the requested file, and attempts to
8535: replicate from the owning library server, Might return
1.607 raeburn 8536: 'unavailable', 'not_found', 'forbidden', 'ok', or
8537: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8538: resource. Expects the local filesystem pathname
8539: (/home/httpd/html/res/....)
8540:
8541: =back
8542:
8543: =head2 Resource Information
8544:
8545: =over 4
1.191 harris41 8546:
8547: =item *
8548:
1.243 albertel 8549: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8550: a vairety of different possible values, $varname should be a request
8551: string, and the other parameters can be used to specify who and what
8552: one is asking about.
8553:
8554: Possible values for $varname are environment.lastname (or other item
8555: from the envirnment hash), user.name (or someother aspect about the
8556: user), resource.0.maxtries (or some other part and parameter of a
8557: resource)
1.204 albertel 8558:
8559: =item *
8560:
1.243 albertel 8561: directcondval($number) : get current value of a condition; reads from a state
8562: string
1.204 albertel 8563:
8564: =item *
8565:
1.243 albertel 8566: condval($condidx) : value of condition index based on state
1.204 albertel 8567:
8568: =item *
8569:
1.243 albertel 8570: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8571: resource's metadata, $what should be either a specific key, or either
8572: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8573: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8574:
8575: this function automatically caches all requests
1.191 harris41 8576:
8577: =item *
8578:
1.243 albertel 8579: metadata_query($query,$custom,$customshow) : make a metadata query against the
8580: network of library servers; returns file handle of where SQL and regex results
8581: will be stored for query
1.191 harris41 8582:
8583: =item *
8584:
1.243 albertel 8585: symbread($filename) : return symbolic list entry (filename argument optional);
8586: returns the data handle
1.191 harris41 8587:
8588: =item *
8589:
1.243 albertel 8590: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 8591: a possible symb for the URL in $thisfn, and if is an encryypted
8592: resource that the user accessed using /enc/ returns a 1 on success, 0
8593: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 8594: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 8595:
1.191 harris41 8596:
8597: =item *
8598:
1.243 albertel 8599: symbclean($symb) : removes versions numbers from a symb, returns the
8600: cleaned symb
1.191 harris41 8601:
8602: =item *
8603:
1.243 albertel 8604: is_on_map($uri) : checks if the $uri is somewhere on the current
8605: course map, user must be in a course for it to work.
1.191 harris41 8606:
8607: =item *
8608:
1.243 albertel 8609: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 8610:
8611: =item *
8612:
1.243 albertel 8613: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8614: a random seed, all arguments are optional, if they aren't sent it uses the
8615: environment to derive them. Note: if symb isn't sent and it can't get one
8616: from &symbread it will use the current time as its return value
1.191 harris41 8617:
8618: =item *
8619:
1.243 albertel 8620: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8621: unfakeable, receipt
1.191 harris41 8622:
8623: =item *
8624:
1.620 albertel 8625: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 8626:
8627: =item *
8628:
1.243 albertel 8629: countacc($url) : count the number of accesses to a given URL
1.191 harris41 8630:
8631: =item *
8632:
1.243 albertel 8633: 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 8634:
8635: =item *
8636:
1.243 albertel 8637: 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 8638:
8639: =item *
8640:
1.243 albertel 8641: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 8642:
8643: =item *
8644:
1.243 albertel 8645: devalidate($symb) : devalidate temporary spreadsheet calculations,
8646: forcing spreadsheet to reevaluate the resource scores next time.
8647:
8648: =back
8649:
8650: =head2 Storing/Retreiving Data
8651:
8652: =over 4
1.191 harris41 8653:
8654: =item *
8655:
1.243 albertel 8656: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8657: for this url; hashref needs to be given and should be a \%hashname; the
8658: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 8659: be derived from the env
1.191 harris41 8660:
8661: =item *
8662:
1.243 albertel 8663: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8664: uses critical subroutine
1.191 harris41 8665:
8666: =item *
8667:
1.243 albertel 8668: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8669: all args are optional
1.191 harris41 8670:
8671: =item *
8672:
1.717 albertel 8673: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8674: dumps the complete (or key matching regexp) namespace into a hash
8675: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8676: normally &store()ed into
8677:
8678: $range should be either an integer '100' (give me the first 100
8679: matching records)
8680: or be two integers sperated by a - with no spaces
8681: '30-50' (give me the 30th through the 50th matching
8682: records)
8683:
8684:
8685: =item *
8686:
8687: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8688: replaces a &store() version of data with a replacement set of data
8689: for a particular resource in a namespace passed in the $storehash hash
8690: reference
8691:
8692: =item *
8693:
1.243 albertel 8694: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8695: works very similar to store/cstore, but all data is stored in a
8696: temporary location and can be reset using tmpreset, $storehash should
8697: be a hash reference, returns nothing on success
1.191 harris41 8698:
8699: =item *
8700:
1.243 albertel 8701: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8702: similar to restore, but all data is stored in a temporary location and
8703: can be reset using tmpreset. Returns a hash of values on success,
8704: error string otherwise.
1.191 harris41 8705:
8706: =item *
8707:
1.243 albertel 8708: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8709: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 8710:
8711: =item *
8712:
1.243 albertel 8713: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8714: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 8715:
8716: =item *
8717:
1.243 albertel 8718: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8719: namesp ($udom and $uname are optional)
1.191 harris41 8720:
8721: =item *
8722:
1.702 albertel 8723: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 8724: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 8725: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 8726:
1.702 albertel 8727: $range should be either an integer '100' (give me the first 100
8728: matching records)
8729: or be two integers sperated by a - with no spaces
8730: '30-50' (give me the 30th through the 50th matching
8731: records)
1.449 matthew 8732: =item *
8733:
8734: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8735: $store can be a scalar, an array reference, or if the amount to be
8736: incremented is > 1, a hash reference.
8737:
8738: ($udom and $uname are optional)
1.191 harris41 8739:
8740: =item *
8741:
1.243 albertel 8742: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8743: ($udom and $uname are optional)
1.191 harris41 8744:
8745: =item *
8746:
1.243 albertel 8747: cput($namespace,$storehash,$udom,$uname) : critical put
8748: ($udom and $uname are optional)
1.191 harris41 8749:
8750: =item *
8751:
1.748 albertel 8752: newput($namespace,$storehash,$udom,$uname) :
8753:
8754: Attempts to store the items in the $storehash, but only if they don't
8755: currently exist, if this succeeds you can be certain that you have
8756: successfully created a new key value pair in the $namespace db.
8757:
8758:
8759: Args:
8760: $namespace: name of database to store values to
8761: $storehash: hashref to store to the db
8762: $udom: (optional) domain of user containing the db
8763: $uname: (optional) name of user caontaining the db
8764:
8765: Returns:
8766: 'ok' -> succeeded in storing all keys of $storehash
8767: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8768: least <key> already existed in the db (other
8769: requested keys may also already exist)
8770: 'error: <msg>' -> unable to tie the DB or other erorr occured
8771: 'con_lost' -> unable to contact request server
8772: 'refused' -> action was not allowed by remote machine
8773:
8774:
8775: =item *
8776:
1.243 albertel 8777: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8778: reference filled in from namesp (encrypts the return communication)
8779: ($udom and $uname are optional)
1.191 harris41 8780:
8781: =item *
8782:
1.243 albertel 8783: log($udom,$name,$home,$message) : write to permanent log for user; use
8784: critical subroutine
8785:
1.806 raeburn 8786: =item *
8787:
1.860 raeburn 8788: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
8789: array reference filled in from namespace found in domain level on either
8790: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 8791:
8792: =item *
8793:
1.860 raeburn 8794: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
8795: domain level either on specified domain server ($uhome) or primary domain
8796: server ($udom and $uhome are optional)
1.806 raeburn 8797:
1.243 albertel 8798: =back
8799:
8800: =head2 Network Status Functions
8801:
8802: =over 4
1.191 harris41 8803:
8804: =item *
8805:
8806: dirlist($uri) : return directory list based on URI
8807:
8808: =item *
8809:
1.243 albertel 8810: spareserver() : find server with least workload from spare.tab
8811:
8812: =back
8813:
8814: =head2 Apache Request
8815:
8816: =over 4
1.191 harris41 8817:
8818: =item *
8819:
1.243 albertel 8820: ssi($url,%hash) : server side include, does a complete request cycle on url to
8821: localhost, posts hash
8822:
8823: =back
8824:
8825: =head2 Data to String to Data
8826:
8827: =over 4
1.191 harris41 8828:
8829: =item *
8830:
1.243 albertel 8831: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8832: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 8833:
8834: =item *
8835:
1.243 albertel 8836: hashref2str($hashref) : convert a hashref into a string complete with
8837: escaping and '=' and '&' separators, supports elements that are
8838: arrayrefs and hashrefs
1.191 harris41 8839:
8840: =item *
8841:
1.243 albertel 8842: arrayref2str($arrayref) : convert an arrayref into a string complete
8843: with escaping and '&' separators, supports elements that are arrayrefs
8844: and hashrefs
1.191 harris41 8845:
8846: =item *
8847:
1.243 albertel 8848: str2hash($string) : convert string to hash using unescaping and
8849: splitting on '=' and '&', supports elements that are arrayrefs and
8850: hashrefs
1.191 harris41 8851:
8852: =item *
8853:
1.243 albertel 8854: str2array($string) : convert string to hash using unescaping and
8855: splitting on '&', supports elements that are arrayrefs and hashrefs
8856:
8857: =back
8858:
8859: =head2 Logging Routines
8860:
8861: =over 4
8862:
8863: These routines allow one to make log messages in the lonnet.log and
8864: lonnet.perm logfiles.
1.191 harris41 8865:
8866: =item *
8867:
1.243 albertel 8868: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8869:
8870: =item *
8871:
1.243 albertel 8872: logthis() : append message to the normal lonnet.log file, it gets
8873: preiodically rolled over and deleted.
1.191 harris41 8874:
8875: =item *
8876:
1.243 albertel 8877: logperm() : append a permanent message to lonnet.perm.log, this log
8878: file never gets deleted by any automated portion of the system, only
8879: messages of critical importance should go in here.
8880:
8881: =back
8882:
8883: =head2 General File Helper Routines
8884:
8885: =over 4
1.191 harris41 8886:
8887: =item *
8888:
1.481 raeburn 8889: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8890: (a) files in /uploaded
8891: (i) If a local copy of the file exists -
8892: compares modification date of local copy with last-modified date for
8893: definitive version stored on home server for course. If local copy is
8894: stale, requests a new version from the home server and stores it.
8895: If the original has been removed from the home server, then local copy
8896: is unlinked.
8897: (ii) If local copy does not exist -
8898: requests the file from the home server and stores it.
8899:
8900: If $caller is 'uploadrep':
8901: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8902: for request for files originally uploaded via DOCS.
8903: - returns 'ok' if fresh local copy now available, -1 otherwise.
8904:
8905: Otherwise:
8906: This indicates a call from the content generation phase of the request.
8907: - returns the entire contents of the file or -1.
8908:
8909: (b) files in /res
8910: - returns the entire contents of a file or -1;
8911: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8912:
1.712 albertel 8913:
8914: =item *
8915:
8916: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8917: reference
8918:
8919: returns either a stat() list of data about the file or an empty list
8920: if the file doesn't exist or couldn't find out about it (connection
8921: problems or user unknown)
8922:
1.191 harris41 8923: =item *
8924:
1.243 albertel 8925: filelocation($dir,$file) : returns file system location of a file
8926: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8927: directory that relative $file lookups are to looked in ($dir of /a/dir
8928: and a file of ../bob will become /a/bob)
1.191 harris41 8929:
8930: =item *
8931:
8932: hreflocation($dir,$file) : returns file system location or a URL; same as
8933: filelocation except for hrefs
8934:
8935: =item *
8936:
8937: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8938:
1.243 albertel 8939: =back
8940:
1.608 albertel 8941: =head2 Usererfile file routines (/uploaded*)
8942:
8943: =over 4
8944:
8945: =item *
8946:
8947: userfileupload(): main rotine for putting a file in a user or course's
8948: filespace, arguments are,
8949:
1.620 albertel 8950: formname - required - this is the name of the element in $env where the
1.608 albertel 8951: filename, and the contents of the file to create/modifed exist
1.620 albertel 8952: the filename is in $env{'form.'.$formname.'.filename'} and the
8953: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8954: coursedoc - if true, store the file in the course of the active role
8955: of the current user
8956: subdir - required - subdirectory to put the file in under ../userfiles/
8957: if undefined, it will be placed in "unknown"
8958:
8959: (This routine calls clean_filename() to remove any dangerous
8960: characters from the filename, and then calls finuserfileupload() to
8961: complete the transaction)
8962:
8963: returns either the url of the uploaded file (/uploaded/....) if successful
8964: and /adm/notfound.html if unsuccessful
8965:
8966: =item *
8967:
8968: clean_filename(): routine for cleaing a filename up for storage in
8969: userfile space, argument is:
8970:
8971: filename - proposed filename
8972:
8973: returns: the new clean filename
8974:
8975: =item *
8976:
8977: finishuserfileupload(): routine that creaes and sends the file to
8978: userspace, probably shouldn't be called directly
8979:
8980: docuname: username or courseid of destination for the file
8981: docudom: domain of user/course of destination for the file
8982: formname: same as for userfileupload()
8983: fname: filename (inculding subdirectories) for the file
8984:
8985: returns either the url of the uploaded file (/uploaded/....) if successful
8986: and /adm/notfound.html if unsuccessful
8987:
8988: =item *
8989:
8990: renameuserfile(): renames an existing userfile to a new name
8991:
8992: Args:
8993: docuname: username or courseid of destination for the file
8994: docudom: domain of user/course of destination for the file
8995: old: current file name (including any subdirs under userfiles)
8996: new: desired file name (including any subdirs under userfiles)
8997:
8998: =item *
8999:
9000: mkdiruserfile(): creates a directory is a userfiles dir
9001:
9002: Args:
9003: docuname: username or courseid of destination for the file
9004: docudom: domain of user/course of destination for the file
9005: dir: dir to create (including any subdirs under userfiles)
9006:
9007: =item *
9008:
9009: removeuserfile(): removes a file that exists in userfiles
9010:
9011: Args:
9012: docuname: username or courseid of destination for the file
9013: docudom: domain of user/course of destination for the file
9014: fname: filname to delete (including any subdirs under userfiles)
9015:
9016: =item *
9017:
9018: removeuploadedurl(): convience function for removeuserfile()
9019:
9020: Args:
9021: url: a full /uploaded/... url to delete
9022:
1.747 albertel 9023: =item *
9024:
9025: get_portfile_permissions():
9026: Args:
9027: domain: domain of user or course contain the portfolio files
9028: user: name of user or num of course contain the portfolio files
9029: Returns:
9030: hashref of a dump of the proper file_permissions.db
9031:
9032:
9033: =item *
9034:
9035: get_access_controls():
9036:
9037: Args:
9038: current_permissions: the hash ref returned from get_portfile_permissions()
9039: group: (optional) the group you want the files associated with
9040: file: (optional) the file you want access info on
9041:
9042: Returns:
1.749 raeburn 9043: a hash (keys are file names) of hashes containing
9044: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9045: values are XML containing access control settings (see below)
1.747 albertel 9046:
9047: Internal notes:
9048:
1.749 raeburn 9049: access controls are stored in file_permissions.db as key=value pairs.
9050: key -> path to file/file_name\0uniqueID:scope_end_start
9051: where scope -> public,guest,course,group,domains or users.
9052: end -> UNIX time for end of access (0 -> no end date)
9053: start -> UNIX time for start of access
9054:
9055: value -> XML description of access control
9056: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9057: <start></start>
9058: <end></end>
9059:
9060: <password></password> for scope type = guest
9061:
9062: <domain></domain> for scope type = course or group
9063: <number></number>
9064: <roles id="">
9065: <role></role>
9066: <access></access>
9067: <section></section>
9068: <group></group>
9069: </roles>
9070:
9071: <dom></dom> for scope type = domains
9072:
9073: <users> for scope type = users
9074: <user>
9075: <uname></uname>
9076: <udom></udom>
9077: </user>
9078: </users>
9079: </scope>
9080:
9081: Access data is also aggregated for each file in an additional key=value pair:
9082: key -> path to file/file_name\0accesscontrol
9083: value -> reference to hash
9084: hash contains key = value pairs
9085: where key = uniqueID:scope_end_start
9086: value = UNIX time record was last updated
9087:
9088: Used to improve speed of look-ups of access controls for each file.
9089:
9090: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9091:
9092: modify_access_controls():
9093:
9094: Modifies access controls for a portfolio file
9095: Args
9096: 1. file name
9097: 2. reference to hash of required changes,
9098: 3. domain
9099: 4. username
9100: where domain,username are the domain of the portfolio owner
9101: (either a user or a course)
9102:
9103: Returns:
9104: 1. result of additions or updates ('ok' or 'error', with error message).
9105: 2. result of deletions ('ok' or 'error', with error message).
9106: 3. reference to hash of any new or updated access controls.
9107: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9108: key = integer (inbound ID)
9109: value = uniqueID
1.747 albertel 9110:
1.608 albertel 9111: =back
9112:
1.243 albertel 9113: =head2 HTTP Helper Routines
9114:
9115: =over 4
9116:
1.191 harris41 9117: =item *
9118:
9119: escape() : unpack non-word characters into CGI-compatible hex codes
9120:
9121: =item *
9122:
9123: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9124:
1.243 albertel 9125: =back
9126:
9127: =head1 PRIVATE SUBROUTINES
9128:
9129: =head2 Underlying communication routines (Shouldn't call)
9130:
9131: =over 4
9132:
9133: =item *
9134:
9135: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9136:
9137: =item *
9138:
9139: reply() : uses subreply to send a message to remote machine, logs all failures
9140:
9141: =item *
9142:
9143: critical() : passes a critical message to another server; if cannot
9144: get through then place message in connection buffer directory and
9145: returns con_delayed, if incapable of saving message, returns
9146: con_failed
9147:
9148: =item *
9149:
9150: reconlonc() : tries to reconnect lonc client processes.
9151:
9152: =back
9153:
9154: =head2 Resource Access Logging
9155:
9156: =over 4
9157:
9158: =item *
9159:
9160: flushcourselogs() : flush (save) buffer logs and access logs
9161:
9162: =item *
9163:
9164: courselog($what) : save message for course in hash
9165:
9166: =item *
9167:
9168: courseacclog($what) : save message for course using &courselog(). Perform
9169: special processing for specific resource types (problems, exams, quizzes, etc).
9170:
1.191 harris41 9171: =item *
9172:
9173: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9174: as a PerlChildExitHandler
1.243 albertel 9175:
9176: =back
9177:
9178: =head2 Other
9179:
9180: =over 4
9181:
9182: =item *
9183:
9184: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9185:
9186: =back
9187:
9188: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>