Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.941.2.1
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.941.2.1! raeburn 4: # $Id: lonnet.pm,v 1.941 2008/02/03 05:08:05 raeburn 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.890 albertel 152: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\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.891 albertel 217: my ($lonid) = @_;
218: my $hostname = &hostname($lonid);
219: if ($lonid) {
220: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
221: if ($hostname && -e $peerfile) {
222: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
223: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
224: Type => SOCK_STREAM,
225: Timeout => 10);
226: if ($client) {
227: print $client ("reset_retries\n");
228: my $answer=<$client>;
229: #reset just this one.
230: }
231: }
232: return;
233: }
234:
1.836 www 235: &logthis("Trying to reconnect lonc");
1.1 albertel 236: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 237: if (open(my $fh,"<$loncfile")) {
1.1 albertel 238: my $loncpid=<$fh>;
239: chomp($loncpid);
240: if (kill 0 => $loncpid) {
241: &logthis("lonc at pid $loncpid responding, sending USR1");
242: kill USR1 => $loncpid;
243: sleep 1;
1.836 www 244: } else {
1.12 www 245: &logthis(
1.672 albertel 246: "<font color=\"blue\">WARNING:".
1.12 www 247: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 248: }
249: } else {
1.836 www 250: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 251: }
252: }
253:
254: # ------------------------------------------------------ Critical communication
1.12 www 255:
1.1 albertel 256: sub critical {
257: my ($cmd,$server)=@_;
1.838 albertel 258: unless (&hostname($server)) {
1.672 albertel 259: &logthis("<font color=\"blue\">WARNING:".
1.89 www 260: " Critical message to unknown server ($server)</font>");
261: return 'no_such_host';
262: }
1.1 albertel 263: my $answer=reply($cmd,$server);
264: if ($answer eq 'con_lost') {
265: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 266: my $answer=reply($cmd,$server);
1.1 albertel 267: if ($answer eq 'con_lost') {
268: my $now=time;
269: my $middlename=$cmd;
1.5 www 270: $middlename=substr($middlename,0,16);
1.1 albertel 271: $middlename=~s/\W//g;
272: my $dfilename=
1.305 www 273: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
274: $dumpcount++;
1.1 albertel 275: {
1.448 albertel 276: my $dfh;
277: if (open($dfh,">$dfilename")) {
278: print $dfh "$cmd\n";
279: close($dfh);
280: }
1.1 albertel 281: }
282: sleep 2;
283: my $wcmd='';
284: {
1.448 albertel 285: my $dfh;
286: if (open($dfh,"<$dfilename")) {
287: $wcmd=<$dfh>;
288: close($dfh);
289: }
1.1 albertel 290: }
291: chomp($wcmd);
1.7 www 292: if ($wcmd eq $cmd) {
1.672 albertel 293: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 294: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 295: &logperm("D:$server:$cmd");
296: return 'con_delayed';
297: } else {
1.672 albertel 298: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 299: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 300: &logperm("F:$server:$cmd");
301: return 'con_failed';
302: }
303: }
304: }
305: return $answer;
1.405 albertel 306: }
307:
1.755 albertel 308: # ------------------------------------------- check if return value is an error
309:
310: sub error {
311: my ($result) = @_;
1.756 albertel 312: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 313: if ($2 == 2) { return undef; }
314: return $1;
315: }
316: return undef;
317: }
318:
1.783 albertel 319: sub convert_and_load_session_env {
320: my ($lonidsdir,$handle)=@_;
321: my @profile;
322: {
1.917 albertel 323: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
324: if (!$opened) {
1.915 albertel 325: return 0;
326: }
1.783 albertel 327: flock($idf,LOCK_SH);
328: @profile=<$idf>;
329: close($idf);
330: }
331: my %temp_env;
332: foreach my $line (@profile) {
1.786 albertel 333: if ($line !~ m/=/) {
334: return 0;
335: }
1.783 albertel 336: chomp($line);
337: my ($envname,$envvalue)=split(/=/,$line,2);
338: $temp_env{&unescape($envname)} = &unescape($envvalue);
339: }
340: unlink("$lonidsdir/$handle.id");
341: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
342: 0640)) {
343: %disk_env = %temp_env;
344: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
345: untie(%disk_env);
346: }
1.786 albertel 347: return 1;
1.783 albertel 348: }
349:
1.374 www 350: # ------------------------------------------- Transfer profile into environment
1.780 albertel 351: my $env_loaded;
352: sub transfer_profile_to_env {
1.788 albertel 353: my ($lonidsdir,$handle,$force_transfer) = @_;
354: if (!$force_transfer && $env_loaded) { return; }
1.374 www 355:
1.720 albertel 356: if (!defined($lonidsdir)) {
357: $lonidsdir = $perlvar{'lonIDsDir'};
358: }
359: if (!defined($handle)) {
360: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
361: }
362:
1.786 albertel 363: my $convert;
364: {
1.917 albertel 365: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
366: if (!$opened) {
1.915 albertel 367: return;
368: }
1.786 albertel 369: flock($idf,LOCK_SH);
370: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
371: &GDBM_READER(),0640)) {
372: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
373: untie(%disk_env);
374: } else {
375: $convert = 1;
376: }
377: }
378: if ($convert) {
379: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
380: &logthis("Failed to load session, or convert session.");
381: }
1.374 www 382: }
1.783 albertel 383:
1.786 albertel 384: my %remove;
1.783 albertel 385: while ( my $envname = each(%env) ) {
1.433 matthew 386: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
387: if ($time < time-300) {
1.783 albertel 388: $remove{$key}++;
1.433 matthew 389: }
390: }
391: }
1.783 albertel 392:
1.619 albertel 393: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 394: $env_loaded=1;
1.783 albertel 395: foreach my $expired_key (keys(%remove)) {
1.433 matthew 396: &delenv($expired_key);
1.374 www 397: }
1.1 albertel 398: }
399:
1.916 albertel 400: # ---------------------------------------------------- Check for valid session
401: sub check_for_valid_session {
402: my ($r) = @_;
403: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
404: my $lonid=$cookies{'lonID'};
405: return undef if (!$lonid);
406:
407: my $handle=&LONCAPA::clean_handle($lonid->value);
408: my $lonidsdir=$r->dir_config('lonIDsDir');
409: return undef if (!-e "$lonidsdir/$handle.id");
410:
1.917 albertel 411: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
412: return undef if (!$opened);
1.916 albertel 413:
414: flock($idf,LOCK_SH);
415: my %disk_env;
416: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
417: &GDBM_READER(),0640)) {
418: return undef;
419: }
420:
421: if (!defined($disk_env{'user.name'})
422: || !defined($disk_env{'user.domain'})) {
423: return undef;
424: }
425: return $handle;
426: }
427:
1.830 albertel 428: sub timed_flock {
429: my ($file,$lock_type) = @_;
430: my $failed=0;
431: eval {
432: local $SIG{__DIE__}='DEFAULT';
433: local $SIG{ALRM}=sub {
434: $failed=1;
435: die("failed lock");
436: };
437: alarm(13);
438: flock($file,$lock_type);
439: alarm(0);
440: };
441: if ($failed) {
442: return undef;
443: } else {
444: return 1;
445: }
446: }
447:
1.5 www 448: # ---------------------------------------------------------- Append Environment
449:
450: sub appenv {
1.6 www 451: my %newenv=@_;
1.692 albertel 452: foreach my $key (keys(%newenv)) {
453: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 454: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 455: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 456: .'</font>');
1.692 albertel 457: delete($newenv{$key});
1.35 www 458: } else {
1.692 albertel 459: $env{$key}=$newenv{$key};
1.35 www 460: }
1.191 harris41 461: }
1.917 albertel 462: my $opened = open(my $env_file,'+<',$env{'user.environment'});
463: if ($opened
1.915 albertel 464: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 465: &&
466: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
467: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 468: while (my ($key,$value) = each(%newenv)) {
469: $disk_env{$key} = $value;
1.448 albertel 470: }
1.783 albertel 471: untie(%disk_env);
1.56 www 472: }
473: return 'ok';
474: }
475: # ----------------------------------------------------- Delete from Environment
476:
477: sub delenv {
478: my $delthis=shift;
479: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 480: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 481: "Attempt to delete from environment ".$delthis);
482: return 'error';
483: }
1.917 albertel 484: my $opened = open(my $env_file,'+<',$env{'user.environment'});
485: if ($opened
1.915 albertel 486: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 487: &&
488: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
489: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 490: foreach my $key (keys(%disk_env)) {
491: if ($key=~/^$delthis/) {
1.915 albertel 492: delete($env{$key});
493: delete($disk_env{$key});
494: }
1.448 albertel 495: }
1.783 albertel 496: untie(%disk_env);
1.5 www 497: }
498: return 'ok';
1.369 albertel 499: }
500:
1.790 albertel 501: sub get_env_multiple {
502: my ($name) = @_;
503: my @values;
504: if (defined($env{$name})) {
505: # exists is it an array
506: if (ref($env{$name})) {
507: @values=@{ $env{$name} };
508: } else {
509: $values[0]=$env{$name};
510: }
511: }
512: return(@values);
513: }
514:
1.369 albertel 515: # ------------------------------------------ Find out current server userload
516: sub userload {
517: my $numusers=0;
518: {
519: opendir(LONIDS,$perlvar{'lonIDsDir'});
520: my $filename;
521: my $curtime=time;
522: while ($filename=readdir(LONIDS)) {
1.925 albertel 523: next if ($filename eq '.' || $filename eq '..');
524: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 525: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 526: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 527: }
528: closedir(LONIDS);
529: }
530: my $userloadpercent=0;
531: my $maxuserload=$perlvar{'lonUserLoadLim'};
532: if ($maxuserload) {
1.371 albertel 533: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 534: }
1.372 albertel 535: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 536: return $userloadpercent;
1.283 www 537: }
538:
539: # ------------------------------------------ Fight off request when overloaded
540:
541: sub overloaderror {
542: my ($r,$checkserver)=@_;
543: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
544: my $loadavg;
545: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 546: open(my $loadfile,'/proc/loadavg');
1.283 www 547: $loadavg=<$loadfile>;
548: $loadavg =~ s/\s.*//g;
1.285 matthew 549: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 550: close($loadfile);
1.283 www 551: } else {
552: $loadavg=&reply('load',$checkserver);
553: }
1.285 matthew 554: my $overload=$loadavg-100;
1.283 www 555: if ($overload>0) {
1.285 matthew 556: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 557: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 558: return 413;
1.283 www 559: }
560: return '';
1.5 www 561: }
1.1 albertel 562:
563: # ------------------------------ Find server with least workload from spare.tab
1.11 www 564:
1.1 albertel 565: sub spareserver {
1.670 albertel 566: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 567: my $spare_server;
1.370 albertel 568: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 569: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
570: : $userloadpercent;
571:
572: foreach my $try_server (@{ $spareid{'primary'} }) {
573: ($spare_server, $lowest_load) =
574: &compare_server_load($try_server, $spare_server, $lowest_load);
575: }
576:
577: my $found_server = ($spare_server ne '' && $lowest_load < 100);
578:
579: if (!$found_server) {
580: foreach my $try_server (@{ $spareid{'default'} }) {
581: ($spare_server, $lowest_load) =
582: &compare_server_load($try_server, $spare_server, $lowest_load);
583: }
584: }
585:
586: if (!$want_server_name) {
1.838 albertel 587: $spare_server="http://".&hostname($spare_server);
1.784 albertel 588: }
589: return $spare_server;
590: }
591:
592: sub compare_server_load {
593: my ($try_server, $spare_server, $lowest_load) = @_;
594:
595: my $loadans = &reply('load', $try_server);
596: my $userloadans = &reply('userload',$try_server);
597:
598: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
599: next; #didn't get a number from the server
600: }
601:
602: my $load;
603: if ($loadans =~ /\d/) {
604: if ($userloadans =~ /\d/) {
605: #both are numbers, pick the bigger one
606: $load = ($loadans > $userloadans) ? $loadans
607: : $userloadans;
1.411 albertel 608: } else {
1.784 albertel 609: $load = $loadans;
1.411 albertel 610: }
1.784 albertel 611: } else {
612: $load = $userloadans;
613: }
614:
615: if (($load =~ /\d/) && ($load < $lowest_load)) {
616: $spare_server = $try_server;
617: $lowest_load = $load;
1.370 albertel 618: }
1.784 albertel 619: return ($spare_server,$lowest_load);
1.202 matthew 620: }
1.914 albertel 621:
622: # --------------------------- ask offload servers if user already has a session
623: sub find_existing_session {
624: my ($udom,$uname) = @_;
625: foreach my $try_server (@{ $spareid{'primary'} },
626: @{ $spareid{'default'} }) {
627: return $try_server if (&has_user_session($try_server, $udom, $uname));
628: }
629: return;
630: }
631:
632: # -------------------------------- ask if server already has a session for user
633: sub has_user_session {
634: my ($lonid,$udom,$uname) = @_;
635: my $result = &reply(join(':','userhassession',
636: map {&escape($_)} ($udom,$uname)),$lonid);
637: return 1 if ($result eq 'ok');
638:
639: return 0;
640: }
641:
1.202 matthew 642: # --------------------------------------------- Try to change a user's password
643:
644: sub changepass {
1.799 raeburn 645: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 646: $currentpass = &escape($currentpass);
647: $newpass = &escape($newpass);
1.799 raeburn 648: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 649: $server);
650: if (! $answer) {
651: &logthis("No reply on password change request to $server ".
652: "by $uname in domain $udom.");
653: } elsif ($answer =~ "^ok") {
654: &logthis("$uname in $udom successfully changed their password ".
655: "on $server.");
656: } elsif ($answer =~ "^pwchange_failure") {
657: &logthis("$uname in $udom was unable to change their password ".
658: "on $server. The action was blocked by either lcpasswd ".
659: "or pwchange");
660: } elsif ($answer =~ "^non_authorized") {
661: &logthis("$uname in $udom did not get their password correct when ".
662: "attempting to change it on $server.");
663: } elsif ($answer =~ "^auth_mode_error") {
664: &logthis("$uname in $udom attempted to change their password despite ".
665: "not being locally or internally authenticated on $server.");
666: } elsif ($answer =~ "^unknown_user") {
667: &logthis("$uname in $udom attempted to change their password ".
668: "on $server but were unable to because $server is not ".
669: "their home server.");
670: } elsif ($answer =~ "^refused") {
671: &logthis("$server refused to change $uname in $udom password because ".
672: "it was sent an unencrypted request to change the password.");
673: }
674: return $answer;
1.1 albertel 675: }
676:
1.169 harris41 677: # ----------------------- Try to determine user's current authentication scheme
678:
679: sub queryauthenticate {
680: my ($uname,$udom)=@_;
1.456 albertel 681: my $uhome=&homeserver($uname,$udom);
682: if (!$uhome) {
683: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
684: return 'no_host';
685: }
686: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
687: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
688: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 689: }
1.456 albertel 690: return $answer;
1.169 harris41 691: }
692:
1.1 albertel 693: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 694:
1.1 albertel 695: sub authenticate {
696: my ($uname,$upass,$udom)=@_;
1.807 albertel 697: $upass=&escape($upass);
698: $uname= &LONCAPA::clean_username($uname);
1.836 www 699: my $uhome=&homeserver($uname,$udom,1);
700: if ((!$uhome) || ($uhome eq 'no_host')) {
701: # Maybe the machine was offline and only re-appeared again recently?
702: &reconlonc();
703: # One more
704: my $uhome=&homeserver($uname,$udom,1);
705: if ((!$uhome) || ($uhome eq 'no_host')) {
706: &logthis("User $uname at $udom is unknown in authenticate");
707: }
1.471 albertel 708: return 'no_host';
1.1 albertel 709: }
1.471 albertel 710: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
711: if ($answer eq 'authorized') {
712: &logthis("User $uname at $udom authorized by $uhome");
713: return $uhome;
714: }
715: if ($answer eq 'non_authorized') {
716: &logthis("User $uname at $udom rejected by $uhome");
717: return 'no_host';
1.9 www 718: }
1.471 albertel 719: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 720: return 'no_host';
721: }
722:
723: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 724:
1.599 albertel 725: my %homecache;
1.1 albertel 726: sub homeserver {
1.230 stredwic 727: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 728: my $index="$uname:$udom";
1.426 albertel 729:
1.599 albertel 730: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 731:
732: my %servers = &get_servers($udom,'library');
733: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 734: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 735: exists($badServerCache{$tryserver}));
1.841 albertel 736:
737: my $answer=reply("home:$udom:$uname",$tryserver);
738: if ($answer eq 'found') {
739: delete($badServerCache{$tryserver});
740: return $homecache{$index}=$tryserver;
741: } elsif ($answer eq 'no_host') {
742: $badServerCache{$tryserver}=1;
743: }
1.1 albertel 744: }
745: return 'no_host';
1.70 www 746: }
747:
748: # ------------------------------------- Find the usernames behind a list of IDs
749:
750: sub idget {
751: my ($udom,@ids)=@_;
752: my %returnhash=();
753:
1.841 albertel 754: my %servers = &get_servers($udom,'library');
755: foreach my $tryserver (keys(%servers)) {
756: my $idlist=join('&',@ids);
757: $idlist=~tr/A-Z/a-z/;
758: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
759: my @answer=();
760: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
761: @answer=split(/\&/,$reply);
762: } ;
763: my $i;
764: for ($i=0;$i<=$#ids;$i++) {
765: if ($answer[$i]) {
766: $returnhash{$ids[$i]}=$answer[$i];
767: }
768: }
769: }
1.70 www 770: return %returnhash;
771: }
772:
773: # ------------------------------------- Find the IDs behind a list of usernames
774:
775: sub idrget {
776: my ($udom,@unames)=@_;
777: my %returnhash=();
1.800 albertel 778: foreach my $uname (@unames) {
779: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 780: }
1.70 www 781: return %returnhash;
782: }
783:
784: # ------------------------------- Store away a list of names and associated IDs
785:
786: sub idput {
787: my ($udom,%ids)=@_;
788: my %servers=();
1.800 albertel 789: foreach my $uname (keys(%ids)) {
790: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
791: my $uhom=&homeserver($uname,$udom);
1.70 www 792: if ($uhom ne 'no_host') {
1.800 albertel 793: my $id=&escape($ids{$uname});
1.70 www 794: $id=~tr/A-Z/a-z/;
1.800 albertel 795: my $esc_unam=&escape($uname);
1.70 www 796: if ($servers{$uhom}) {
1.800 albertel 797: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 798: } else {
1.800 albertel 799: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 800: }
801: }
1.191 harris41 802: }
1.800 albertel 803: foreach my $server (keys(%servers)) {
804: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 805: }
1.344 www 806: }
807:
1.806 raeburn 808: # ------------------------------------------- get items from domain db files
809:
810: sub get_dom {
1.860 raeburn 811: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 812: my $items='';
813: foreach my $item (@$storearr) {
814: $items.=&escape($item).'&';
815: }
816: $items=~s/\&$//;
1.860 raeburn 817: if (!$udom) {
818: $udom=$env{'user.domain'};
819: if (defined(&domain($udom,'primary'))) {
820: $uhome=&domain($udom,'primary');
821: } else {
1.874 albertel 822: undef($uhome);
1.860 raeburn 823: }
824: } else {
825: if (!$uhome) {
826: if (defined(&domain($udom,'primary'))) {
827: $uhome=&domain($udom,'primary');
828: }
829: }
830: }
831: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 832: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 833: my %returnhash;
1.875 albertel 834: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 835: return %returnhash;
836: }
1.806 raeburn 837: my @pairs=split(/\&/,$rep);
838: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
839: return @pairs;
840: }
841: my $i=0;
842: foreach my $item (@$storearr) {
843: $returnhash{$item}=&thaw_unescape($pairs[$i]);
844: $i++;
845: }
846: return %returnhash;
847: } else {
1.880 banghart 848: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 849: }
850: }
851:
852: # -------------------------------------------- put items in domain db files
853:
854: sub put_dom {
1.860 raeburn 855: my ($namespace,$storehash,$udom,$uhome)=@_;
856: if (!$udom) {
857: $udom=$env{'user.domain'};
858: if (defined(&domain($udom,'primary'))) {
859: $uhome=&domain($udom,'primary');
860: } else {
1.874 albertel 861: undef($uhome);
1.860 raeburn 862: }
863: } else {
864: if (!$uhome) {
865: if (defined(&domain($udom,'primary'))) {
866: $uhome=&domain($udom,'primary');
867: }
868: }
869: }
870: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 871: my $items='';
872: foreach my $item (keys(%$storehash)) {
873: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
874: }
875: $items=~s/\&$//;
876: return &reply("putdom:$udom:$namespace:$items",$uhome);
877: } else {
1.860 raeburn 878: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 879: }
880: }
881:
1.837 raeburn 882: sub retrieve_inst_usertypes {
883: my ($udom) = @_;
884: my (%returnhash,@order);
1.846 albertel 885: if (defined(&domain($udom,'primary'))) {
886: my $uhome=&domain($udom,'primary');
1.837 raeburn 887: my $rep=&reply("inst_usertypes:$udom",$uhome);
888: my ($hashitems,$orderitems) = split(/:/,$rep);
889: my @pairs=split(/\&/,$hashitems);
890: foreach my $item (@pairs) {
891: my ($key,$value)=split(/=/,$item,2);
892: $key = &unescape($key);
893: next if ($key =~ /^error: 2 /);
894: $returnhash{$key}=&thaw_unescape($value);
895: }
896: my @esc_order = split(/\&/,$orderitems);
897: foreach my $item (@esc_order) {
898: push(@order,&unescape($item));
899: }
900: } else {
901: &logthis("get_dom failed - no primary domain server for $udom");
902: }
903: return (\%returnhash,\@order);
904: }
905:
1.868 raeburn 906: sub is_domainimage {
907: my ($url) = @_;
908: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
909: if (&domain($1) ne '') {
910: return '1';
911: }
912: }
913: return;
914: }
915:
1.899 raeburn 916: sub inst_directory_query {
917: my ($srch) = @_;
918: my $udom = $srch->{'srchdomain'};
919: my %results;
920: my $homeserver = &domain($udom,'primary');
1.909 raeburn 921: my $outcome;
1.899 raeburn 922: if ($homeserver ne '') {
1.904 albertel 923: my $queryid=&reply("querysend:instdirsearch:".
924: &escape($srch->{'srchby'}).':'.
925: &escape($srch->{'srchterm'}).':'.
926: &escape($srch->{'srchtype'}),$homeserver);
927: my $host=&hostname($homeserver);
928: if ($queryid !~/^\Q$host\E\_/) {
929: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
930: return;
931: }
932: my $response = &get_query_reply($queryid);
933: my $maxtries = 5;
934: my $tries = 1;
935: while (($response=~/^timeout/) && ($tries < $maxtries)) {
936: $response = &get_query_reply($queryid);
937: $tries ++;
938: }
939:
940: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 941: if ($response eq 'unavailable') {
942: $outcome = $response;
943: } else {
944: $outcome = 'ok';
945: my @matches = split(/\n/,$response);
946: foreach my $match (@matches) {
947: my ($key,$value) = split(/=/,$match);
948: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
949: }
1.899 raeburn 950: }
951: }
952: }
1.909 raeburn 953: return ($outcome,%results);
1.899 raeburn 954: }
955:
956: sub usersearch {
957: my ($srch) = @_;
958: my $dom = $srch->{'srchdomain'};
959: my %results;
960: my %libserv = &all_library();
961: my $query = 'usersearch';
962: foreach my $tryserver (keys(%libserv)) {
963: if (&host_domain($tryserver) eq $dom) {
964: my $host=&hostname($tryserver);
965: my $queryid=
1.911 raeburn 966: &reply("querysend:".&escape($query).':'.
967: &escape($srch->{'srchby'}).':'.
1.899 raeburn 968: &escape($srch->{'srchtype'}).':'.
969: &escape($srch->{'srchterm'}),$tryserver);
970: if ($queryid !~/^\Q$host\E\_/) {
971: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 972: next;
1.899 raeburn 973: }
974: my $reply = &get_query_reply($queryid);
975: my $maxtries = 1;
976: my $tries = 1;
977: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
978: $reply = &get_query_reply($queryid);
979: $tries ++;
980: }
981: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
982: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
983: } else {
1.911 raeburn 984: my @matches;
985: if ($reply =~ /\n/) {
986: @matches = split(/\n/,$reply);
987: } else {
988: @matches = split(/\&/,$reply);
989: }
1.899 raeburn 990: foreach my $match (@matches) {
991: my ($uname,$udom,%userhash);
1.911 raeburn 992: foreach my $entry (split(/:/,$match)) {
993: my ($key,$value) =
994: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 995: $userhash{$key} = $value;
996: if ($key eq 'username') {
997: $uname = $value;
998: } elsif ($key eq 'domain') {
999: $udom = $value;
1.911 raeburn 1000: }
1.899 raeburn 1001: }
1002: $results{$uname.':'.$udom} = \%userhash;
1003: }
1004: }
1005: }
1006: }
1007: return %results;
1008: }
1009:
1.912 raeburn 1010: sub get_instuser {
1011: my ($udom,$uname,$id) = @_;
1012: my $homeserver = &domain($udom,'primary');
1013: my ($outcome,%results);
1014: if ($homeserver ne '') {
1015: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1016: &escape($id).':'.&escape($udom),$homeserver);
1017: my $host=&hostname($homeserver);
1018: if ($queryid !~/^\Q$host\E\_/) {
1019: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1020: return;
1021: }
1022: my $response = &get_query_reply($queryid);
1023: my $maxtries = 5;
1024: my $tries = 1;
1025: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1026: $response = &get_query_reply($queryid);
1027: $tries ++;
1028: }
1029: if (!&error($response) && $response ne 'refused') {
1030: if ($response eq 'unavailable') {
1031: $outcome = $response;
1032: } else {
1033: $outcome = 'ok';
1034: my @matches = split(/\n/,$response);
1035: foreach my $match (@matches) {
1036: my ($key,$value) = split(/=/,$match);
1037: $results{&unescape($key)} = &thaw_unescape($value);
1038: }
1039: }
1040: }
1041: }
1042: my %userinfo;
1043: if (ref($results{$uname}) eq 'HASH') {
1044: %userinfo = %{$results{$uname}};
1045: }
1046: return ($outcome,%userinfo);
1047: }
1048:
1049: sub inst_rulecheck {
1.923 raeburn 1050: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1051: my %returnhash;
1052: if ($udom ne '') {
1053: if (ref($rules) eq 'ARRAY') {
1054: @{$rules} = map {&escape($_);} (@{$rules});
1055: my $rulestr = join(':',@{$rules});
1056: my $homeserver=&domain($udom,'primary');
1057: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1058: my $response;
1059: if ($item eq 'username') {
1060: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1061: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1062: $homeserver));
1.923 raeburn 1063: } elsif ($item eq 'id') {
1064: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1065: ':'.&escape($id).':'.$rulestr,
1066: $homeserver));
1067: }
1.912 raeburn 1068: if ($response ne 'refused') {
1069: my @pairs=split(/\&/,$response);
1070: foreach my $item (@pairs) {
1071: my ($key,$value)=split(/=/,$item,2);
1072: $key = &unescape($key);
1073: next if ($key =~ /^error: 2 /);
1074: $returnhash{$key}=&thaw_unescape($value);
1075: }
1076: }
1077: }
1078: }
1079: }
1080: return %returnhash;
1081: }
1082:
1083: sub inst_userrules {
1.923 raeburn 1084: my ($udom,$check) = @_;
1.912 raeburn 1085: my (%ruleshash,@ruleorder);
1086: if ($udom ne '') {
1087: my $homeserver=&domain($udom,'primary');
1088: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1089: my $response;
1090: if ($check eq 'id') {
1091: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1092: $homeserver);
1.923 raeburn 1093: } else {
1094: $response=&reply('instuserrules:'.&escape($udom),
1095: $homeserver);
1096: }
1.912 raeburn 1097: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1098: ($response ne 'unknown_cmd') &&
1.912 raeburn 1099: ($response ne 'no_such_host')) {
1100: my ($hashitems,$orderitems) = split(/:/,$response);
1101: my @pairs=split(/\&/,$hashitems);
1102: foreach my $item (@pairs) {
1103: my ($key,$value)=split(/=/,$item,2);
1104: $key = &unescape($key);
1105: next if ($key =~ /^error: 2 /);
1106: $ruleshash{$key}=&thaw_unescape($value);
1107: }
1108: my @esc_order = split(/\&/,$orderitems);
1109: foreach my $item (@esc_order) {
1110: push(@ruleorder,&unescape($item));
1111: }
1112: }
1113: }
1114: }
1115: return (\%ruleshash,\@ruleorder);
1116: }
1117:
1.344 www 1118: # --------------------------------------------------- Assign a key to a student
1119:
1120: sub assign_access_key {
1.364 www 1121: #
1122: # a valid key looks like uname:udom#comments
1123: # comments are being appended
1124: #
1.498 www 1125: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1126: $kdom=
1.620 albertel 1127: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1128: $knum=
1.620 albertel 1129: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1130: $cdom=
1.620 albertel 1131: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1132: $cnum=
1.620 albertel 1133: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1134: $udom=$env{'user.name'} unless (defined($udom));
1135: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1136: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1137: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1138: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1139: # assigned to this person
1140: # - this should not happen,
1.345 www 1141: # unless something went wrong
1142: # the first time around
1143: # ready to assign
1.364 www 1144: $logentry=$1.'; '.$logentry;
1.496 www 1145: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1146: $kdom,$knum) eq 'ok') {
1.345 www 1147: # key now belongs to user
1.346 www 1148: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1149: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1150: &appenv('environment.'.$envkey => $ckey);
1151: return 'ok';
1152: } else {
1153: return
1154: 'error: Count not permanently assign key, will need to be re-entered later.';
1155: }
1156: } else {
1157: return 'error: Could not assign key, try again later.';
1158: }
1.364 www 1159: } elsif (!$existing{$ckey}) {
1.345 www 1160: # the key does not exist
1161: return 'error: The key does not exist';
1162: } else {
1163: # the key is somebody else's
1164: return 'error: The key is already in use';
1165: }
1.344 www 1166: }
1167:
1.364 www 1168: # ------------------------------------------ put an additional comment on a key
1169:
1170: sub comment_access_key {
1171: #
1172: # a valid key looks like uname:udom#comments
1173: # comments are being appended
1174: #
1175: my ($ckey,$cdom,$cnum,$logentry)=@_;
1176: $cdom=
1.620 albertel 1177: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1178: $cnum=
1.620 albertel 1179: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1180: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1181: if ($existing{$ckey}) {
1182: $existing{$ckey}.='; '.$logentry;
1183: # ready to assign
1.367 www 1184: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1185: $cdom,$cnum) eq 'ok') {
1186: return 'ok';
1187: } else {
1188: return 'error: Count not store comment.';
1189: }
1190: } else {
1191: # the key does not exist
1192: return 'error: The key does not exist';
1193: }
1194: }
1195:
1.344 www 1196: # ------------------------------------------------------ Generate a set of keys
1197:
1198: sub generate_access_keys {
1.364 www 1199: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1200: $cdom=
1.620 albertel 1201: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1202: $cnum=
1.620 albertel 1203: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1204: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1205: unless (($cdom) && ($cnum)) { return 0; }
1206: if ($number>10000) { return 0; }
1207: sleep(2); # make sure don't get same seed twice
1208: srand(time()^($$+($$<<15))); # from "Programming Perl"
1209: my $total=0;
1210: for (my $i=1;$i<=$number;$i++) {
1211: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1212: sprintf("%lx",int(100000*rand)).'-'.
1213: sprintf("%lx",int(100000*rand));
1214: $newkey=~s/1/g/g; # folks mix up 1 and l
1215: $newkey=~s/0/h/g; # and also 0 and O
1216: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1217: if ($existing{$newkey}) {
1218: $i--;
1219: } else {
1.364 www 1220: if (&put('accesskeys',
1221: { $newkey => '# generated '.localtime().
1.620 albertel 1222: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1223: '; '.$logentry },
1224: $cdom,$cnum) eq 'ok') {
1.344 www 1225: $total++;
1226: }
1227: }
1228: }
1.620 albertel 1229: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1230: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1231: return $total;
1232: }
1233:
1234: # ------------------------------------------------------- Validate an accesskey
1235:
1236: sub validate_access_key {
1237: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1238: $cdom=
1.620 albertel 1239: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1240: $cnum=
1.620 albertel 1241: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1242: $udom=$env{'user.domain'} unless (defined($udom));
1243: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1244: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1245: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1246: }
1247:
1248: # ------------------------------------- Find the section of student in a course
1.652 albertel 1249: sub devalidate_getsection_cache {
1250: my ($udom,$unam,$courseid)=@_;
1251: my $hashid="$udom:$unam:$courseid";
1252: &devalidate_cache_new('getsection',$hashid);
1253: }
1.298 matthew 1254:
1.815 albertel 1255: sub courseid_to_courseurl {
1256: my ($courseid) = @_;
1257: #already url style courseid
1258: return $courseid if ($courseid =~ m{^/});
1259:
1260: if (exists($env{'course.'.$courseid.'.num'})) {
1261: my $cnum = $env{'course.'.$courseid.'.num'};
1262: my $cdom = $env{'course.'.$courseid.'.domain'};
1263: return "/$cdom/$cnum";
1264: }
1265:
1266: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1267: if (exists($courseinfo{'num'})) {
1268: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1269: }
1270:
1271: return undef;
1272: }
1273:
1.298 matthew 1274: sub getsection {
1275: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1276: my $cachetime=1800;
1.551 albertel 1277:
1278: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1279: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1280: if (defined($cached)) { return $result; }
1281:
1.298 matthew 1282: my %Pending;
1283: my %Expired;
1284: #
1285: # Each role can either have not started yet (pending), be active,
1286: # or have expired.
1287: #
1288: # If there is an active role, we are done.
1289: #
1290: # If there is more than one role which has not started yet,
1291: # choose the one which will start sooner
1292: # If there is one role which has not started yet, return it.
1293: #
1294: # If there is more than one expired role, choose the one which ended last.
1295: # If there is a role which has expired, return it.
1296: #
1.815 albertel 1297: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1298: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1299: foreach my $key (keys(%roleshash)) {
1.479 albertel 1300: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1301: my $section=$1;
1302: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1303: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1304: my $now=time;
1.548 albertel 1305: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1306: $Expired{$end}=$section;
1307: next;
1308: }
1.548 albertel 1309: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1310: $Pending{$start}=$section;
1311: next;
1312: }
1.599 albertel 1313: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1314: }
1315: #
1316: # Presumedly there will be few matching roles from the above
1317: # loop and the sorting time will be negligible.
1318: if (scalar(keys(%Pending))) {
1319: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1320: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1321: }
1322: if (scalar(keys(%Expired))) {
1323: my @sorted = sort {$a <=> $b} keys(%Expired);
1324: my $time = pop(@sorted);
1.599 albertel 1325: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1326: }
1.599 albertel 1327: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1328: }
1.70 www 1329:
1.599 albertel 1330: sub save_cache {
1331: &purge_remembered();
1.722 albertel 1332: #&Apache::loncommon::validate_page();
1.620 albertel 1333: undef(%env);
1.780 albertel 1334: undef($env_loaded);
1.599 albertel 1335: }
1.452 albertel 1336:
1.599 albertel 1337: my $to_remember=-1;
1338: my %remembered;
1339: my %accessed;
1340: my $kicks=0;
1341: my $hits=0;
1.849 albertel 1342: sub make_key {
1343: my ($name,$id) = @_;
1.872 albertel 1344: if (length($id) > 65
1345: && length(&escape($id)) > 200) {
1346: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1347: }
1.849 albertel 1348: return &escape($name.':'.$id);
1349: }
1350:
1.599 albertel 1351: sub devalidate_cache_new {
1352: my ($name,$id,$debug) = @_;
1353: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1354: $id=&make_key($name,$id);
1.599 albertel 1355: $memcache->delete($id);
1356: delete($remembered{$id});
1357: delete($accessed{$id});
1358: }
1359:
1360: sub is_cached_new {
1361: my ($name,$id,$debug) = @_;
1.849 albertel 1362: $id=&make_key($name,$id);
1.599 albertel 1363: if (exists($remembered{$id})) {
1364: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1365: $accessed{$id}=[&gettimeofday()];
1366: $hits++;
1367: return ($remembered{$id},1);
1368: }
1369: my $value = $memcache->get($id);
1370: if (!(defined($value))) {
1371: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1372: return (undef,undef);
1.416 albertel 1373: }
1.599 albertel 1374: if ($value eq '__undef__') {
1375: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1376: $value=undef;
1377: }
1378: &make_room($id,$value,$debug);
1379: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1380: return ($value,1);
1381: }
1382:
1383: sub do_cache_new {
1384: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1385: $id=&make_key($name,$id);
1.599 albertel 1386: my $setvalue=$value;
1387: if (!defined($setvalue)) {
1388: $setvalue='__undef__';
1389: }
1.623 albertel 1390: if (!defined($time) ) {
1391: $time=600;
1392: }
1.599 albertel 1393: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1394: my $result = $memcache->set($id,$setvalue,$time);
1395: if (! $result) {
1.872 albertel 1396: &logthis("caching of id -> $id failed");
1.910 albertel 1397: $memcache->disconnect_all();
1.872 albertel 1398: }
1.600 albertel 1399: # need to make a copy of $value
1.919 albertel 1400: &make_room($id,$value,$debug);
1.599 albertel 1401: return $value;
1402: }
1403:
1404: sub make_room {
1405: my ($id,$value,$debug)=@_;
1.919 albertel 1406:
1407: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1408: : $value;
1.599 albertel 1409: if ($to_remember<0) { return; }
1410: $accessed{$id}=[&gettimeofday()];
1411: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1412: my $to_kick;
1413: my $max_time=0;
1414: foreach my $other (keys(%accessed)) {
1415: if (&tv_interval($accessed{$other}) > $max_time) {
1416: $to_kick=$other;
1417: $max_time=&tv_interval($accessed{$other});
1418: }
1419: }
1420: delete($remembered{$to_kick});
1421: delete($accessed{$to_kick});
1422: $kicks++;
1423: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1424: return;
1425: }
1426:
1.599 albertel 1427: sub purge_remembered {
1.604 albertel 1428: #&logthis("Tossing ".scalar(keys(%remembered)));
1429: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1430: undef(%remembered);
1431: undef(%accessed);
1.428 albertel 1432: }
1.70 www 1433: # ------------------------------------- Read an entry from a user's environment
1434:
1435: sub userenvironment {
1436: my ($udom,$unam,@what)=@_;
1437: my %returnhash=();
1438: my @answer=split(/\&/,
1439: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1440: &homeserver($unam,$udom)));
1441: my $i;
1442: for ($i=0;$i<=$#what;$i++) {
1443: $returnhash{$what[$i]}=&unescape($answer[$i]);
1444: }
1445: return %returnhash;
1.1 albertel 1446: }
1447:
1.617 albertel 1448: # ---------------------------------------------------------- Get a studentphoto
1449: sub studentphoto {
1450: my ($udom,$unam,$ext) = @_;
1451: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1452: if (defined($env{'request.course.id'})) {
1.708 raeburn 1453: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1454: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1455: return(&retrievestudentphoto($udom,$unam,$ext));
1456: } else {
1457: my ($result,$perm_reqd)=
1.707 albertel 1458: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1459: if ($result eq 'ok') {
1460: if (!($perm_reqd eq 'yes')) {
1461: return(&retrievestudentphoto($udom,$unam,$ext));
1462: }
1463: }
1464: }
1465: }
1466: } else {
1467: my ($result,$perm_reqd) =
1.707 albertel 1468: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1469: if ($result eq 'ok') {
1470: if (!($perm_reqd eq 'yes')) {
1471: return(&retrievestudentphoto($udom,$unam,$ext));
1472: }
1473: }
1474: }
1475: return '/adm/lonKaputt/lonlogo_broken.gif';
1476: }
1477:
1478: sub retrievestudentphoto {
1479: my ($udom,$unam,$ext,$type) = @_;
1480: my $home=&Apache::lonnet::homeserver($unam,$udom);
1481: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1482: if ($ret eq 'ok') {
1483: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1484: if ($type eq 'thumbnail') {
1485: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1486: }
1487: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1488: return $tokenurl;
1489: } else {
1490: if ($type eq 'thumbnail') {
1491: return '/adm/lonKaputt/genericstudent_tn.gif';
1492: } else {
1493: return '/adm/lonKaputt/lonlogo_broken.gif';
1494: }
1.617 albertel 1495: }
1496: }
1497:
1.263 www 1498: # -------------------------------------------------------------------- New chat
1499:
1500: sub chatsend {
1.724 raeburn 1501: my ($newentry,$anon,$group)=@_;
1.620 albertel 1502: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1503: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1504: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1505: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1506: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1507: &escape($newentry)).':'.$group,$chome);
1.292 www 1508: }
1509:
1510: # ------------------------------------------ Find current version of a resource
1511:
1512: sub getversion {
1513: my $fname=&clutter(shift);
1514: unless ($fname=~/^\/res\//) { return -1; }
1515: return ¤tversion(&filelocation('',$fname));
1516: }
1517:
1518: sub currentversion {
1519: my $fname=shift;
1.599 albertel 1520: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1521: if (defined($cached)) { return $result; }
1.292 www 1522: my $author=$fname;
1523: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1524: my ($udom,$uname)=split(/\//,$author);
1525: my $home=homeserver($uname,$udom);
1526: if ($home eq 'no_host') {
1527: return -1;
1528: }
1529: my $answer=reply("currentversion:$fname",$home);
1530: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1531: return -1;
1532: }
1.599 albertel 1533: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1534: }
1535:
1.1 albertel 1536: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1537:
1.1 albertel 1538: sub subscribe {
1539: my $fname=shift;
1.761 raeburn 1540: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1541: $fname=~s/[\n\r]//g;
1.1 albertel 1542: my $author=$fname;
1543: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1544: my ($udom,$uname)=split(/\//,$author);
1545: my $home=homeserver($uname,$udom);
1.335 albertel 1546: if ($home eq 'no_host') {
1547: return 'not_found';
1.1 albertel 1548: }
1549: my $answer=reply("sub:$fname",$home);
1.64 www 1550: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1551: $answer.=' by '.$home;
1552: }
1.1 albertel 1553: return $answer;
1554: }
1555:
1.8 www 1556: # -------------------------------------------------------------- Replicate file
1557:
1558: sub repcopy {
1559: my $filename=shift;
1.23 www 1560: $filename=~s/\/+/\//g;
1.607 raeburn 1561: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1562: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1563: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1564: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1565: return &repcopy_userfile($filename);
1566: }
1.532 albertel 1567: $filename=~s/[\n\r]//g;
1.8 www 1568: my $transname="$filename.in.transfer";
1.828 www 1569: # FIXME: this should flock
1.607 raeburn 1570: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1571: my $remoteurl=subscribe($filename);
1.64 www 1572: if ($remoteurl =~ /^con_lost by/) {
1573: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1574: return 'unavailable';
1.8 www 1575: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1576: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1577: return 'not_found';
1.64 www 1578: } elsif ($remoteurl =~ /^rejected by/) {
1579: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1580: return 'forbidden';
1.20 www 1581: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1582: return 'ok';
1.8 www 1583: } else {
1.290 www 1584: my $author=$filename;
1585: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1586: my ($udom,$uname)=split(/\//,$author);
1587: my $home=homeserver($uname,$udom);
1588: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1589: my @parts=split(/\//,$filename);
1590: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1591: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1592: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1593: return 'bad_request';
1.8 www 1594: }
1595: my $count;
1596: for ($count=5;$count<$#parts;$count++) {
1597: $path.="/$parts[$count]";
1598: if ((-e $path)!=1) {
1599: mkdir($path,0777);
1600: }
1601: }
1602: my $ua=new LWP::UserAgent;
1603: my $request=new HTTP::Request('GET',"$remoteurl");
1604: my $response=$ua->request($request,$transname);
1605: if ($response->is_error()) {
1606: unlink($transname);
1607: my $message=$response->status_line;
1.672 albertel 1608: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1609: ." LWP get: $message: $filename</font>");
1.607 raeburn 1610: return 'unavailable';
1.8 www 1611: } else {
1.16 www 1612: if ($remoteurl!~/\.meta$/) {
1613: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1614: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1615: if ($mresponse->is_error()) {
1616: unlink($filename.'.meta');
1617: &logthis(
1.672 albertel 1618: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1619: }
1620: }
1.8 www 1621: rename($transname,$filename);
1.607 raeburn 1622: return 'ok';
1.8 www 1623: }
1.290 www 1624: }
1.8 www 1625: }
1.330 www 1626: }
1627:
1628: # ------------------------------------------------ Get server side include body
1629: sub ssi_body {
1.381 albertel 1630: my ($filelink,%form)=@_;
1.606 matthew 1631: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1632: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1633: }
1.330 www 1634: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1635: &ssi($filelink,%form));
1.778 albertel 1636: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1637: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1638: $output=~s/\<\/body\s*\>.*?$//si;
1.330 www 1639: return $output;
1.8 www 1640: }
1641:
1.15 www 1642: # --------------------------------------------------------- Server Side Include
1643:
1.782 albertel 1644: sub absolute_url {
1645: my ($host_name) = @_;
1646: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1647: if ($host_name eq '') {
1648: $host_name = $ENV{'SERVER_NAME'};
1649: }
1650: return $protocol.$host_name;
1651: }
1652:
1.941.2.1! raeburn 1653: #
! 1654: # Server side include.
! 1655: # Parameters:
! 1656: # fn Possibly encrypted resource name/id.
! 1657: # form Hash that describes how the rendering should be done
! 1658: # and other things.
! 1659: # Returns:
! 1660: # Scalar context: The content of the response.
! 1661: # Array context: 2 element list of the content and the full response object.
! 1662: #
1.15 www 1663: sub ssi {
1664:
1.23 www 1665: my ($fn,%form)=@_;
1.15 www 1666: my $ua=new LWP::UserAgent;
1.23 www 1667: my $request;
1.711 albertel 1668:
1669: $form{'no_update_last_known'}=1;
1.895 albertel 1670: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1671: if (%form) {
1.782 albertel 1672: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1673: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1674: } else {
1.782 albertel 1675: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1676: }
1677:
1.15 www 1678: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1679: my $response=$ua->request($request);
1680:
1.941.2.1! raeburn 1681: if (wantarray) {
! 1682: return ($response->content, $response);
! 1683: } else {
! 1684: return $response->content;
! 1685: }
1.324 www 1686: }
1687:
1688: sub externalssi {
1689: my ($url)=@_;
1690: my $ua=new LWP::UserAgent;
1691: my $request=new HTTP::Request('GET',$url);
1692: my $response=$ua->request($request);
1.15 www 1693: return $response->content;
1694: }
1.254 www 1695:
1.492 albertel 1696: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1697:
1698: sub allowuploaded {
1699: my ($srcurl,$url)=@_;
1700: $url=&clutter(&declutter($url));
1701: my $dir=$url;
1702: $dir=~s/\/[^\/]+$//;
1703: my %httpref=();
1704: my $httpurl=&hreflocation('',$url);
1705: $httpref{'httpref.'.$httpurl}=$srcurl;
1706: &Apache::lonnet::appenv(%httpref);
1.254 www 1707: }
1.477 raeburn 1708:
1.478 albertel 1709: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1710: # input: action, courseID, current domain, intended
1.637 raeburn 1711: # path to file, source of file, instruction to parse file for objects,
1712: # ref to hash for embedded objects,
1713: # ref to hash for codebase of java objects.
1714: #
1.485 raeburn 1715: # output: url to file (if action was uploaddoc),
1716: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1717: #
1.478 albertel 1718: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1719: # course.
1.477 raeburn 1720: #
1.478 albertel 1721: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1722: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1723: # course's home server.
1.477 raeburn 1724: #
1.478 albertel 1725: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1726: # be copied from $source (current location) to
1727: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1728: # and will then be copied to
1729: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1730: # course's home server.
1.485 raeburn 1731: #
1.481 raeburn 1732: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1733: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1734: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1735: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1736: # in course's home server.
1.637 raeburn 1737: #
1.477 raeburn 1738:
1739: sub process_coursefile {
1.638 albertel 1740: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1741: my $fetchresult;
1.638 albertel 1742: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1743: if ($action eq 'propagate') {
1.638 albertel 1744: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1745: $home);
1.481 raeburn 1746: } else {
1.477 raeburn 1747: my $fpath = '';
1748: my $fname = $file;
1.478 albertel 1749: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1750: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1751: my $filepath = &build_filepath($fpath);
1.481 raeburn 1752: if ($action eq 'copy') {
1753: if ($source eq '') {
1754: $fetchresult = 'no source file';
1755: return $fetchresult;
1756: } else {
1757: my $destination = $filepath.'/'.$fname;
1758: rename($source,$destination);
1759: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1760: $home);
1.481 raeburn 1761: }
1762: } elsif ($action eq 'uploaddoc') {
1763: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1764: print $fh $env{'form.'.$source};
1.481 raeburn 1765: close($fh);
1.637 raeburn 1766: if ($parser eq 'parse') {
1767: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1768: unless ($parse_result eq 'ok') {
1769: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1770: }
1771: }
1.477 raeburn 1772: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1773: $home);
1.481 raeburn 1774: if ($fetchresult eq 'ok') {
1775: return '/uploaded/'.$fpath.'/'.$fname;
1776: } else {
1777: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1778: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1779: return '/adm/notfound.html';
1780: }
1.477 raeburn 1781: }
1782: }
1.485 raeburn 1783: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1784: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1785: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1786: }
1787: return $fetchresult;
1788: }
1789:
1.637 raeburn 1790: sub build_filepath {
1791: my ($fpath) = @_;
1792: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1793: unless ($fpath eq '') {
1794: my @parts=split('/',$fpath);
1795: foreach my $part (@parts) {
1796: $filepath.= '/'.$part;
1797: if ((-e $filepath)!=1) {
1798: mkdir($filepath,0777);
1799: }
1800: }
1801: }
1802: return $filepath;
1803: }
1804:
1805: sub store_edited_file {
1.638 albertel 1806: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1807: my $file = $primary_url;
1808: $file =~ s#^/uploaded/$docudom/$docuname/##;
1809: my $fpath = '';
1810: my $fname = $file;
1811: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1812: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1813: my $filepath = &build_filepath($fpath);
1814: open(my $fh,'>'.$filepath.'/'.$fname);
1815: print $fh $content;
1816: close($fh);
1.638 albertel 1817: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1818: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1819: $home);
1.637 raeburn 1820: if ($$fetchresult eq 'ok') {
1821: return '/uploaded/'.$fpath.'/'.$fname;
1822: } else {
1.638 albertel 1823: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1824: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1825: return '/adm/notfound.html';
1826: }
1827: }
1828:
1.531 albertel 1829: sub clean_filename {
1.831 albertel 1830: my ($fname,$args)=@_;
1.315 www 1831: # Replace Windows backslashes by forward slashes
1.257 www 1832: $fname=~s/\\/\//g;
1.831 albertel 1833: if (!$args->{'keep_path'}) {
1834: # Get rid of everything but the actual filename
1835: $fname=~s/^.*\/([^\/]+)$/$1/;
1836: }
1.315 www 1837: # Replace spaces by underscores
1838: $fname=~s/\s+/\_/g;
1839: # Replace all other weird characters by nothing
1.831 albertel 1840: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1841: # Replace all .\d. sequences with _\d. so they no longer look like version
1842: # numbers
1843: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1844: return $fname;
1845: }
1846:
1.608 albertel 1847: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1848: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1849: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1850: # $coursedoc - if true up to the current course
1851: # if false
1852: # $subdir - directory in userfile to store the file into
1.858 raeburn 1853: # $parser - instruction to parse file for objects ($parser = parse)
1854: # $allfiles - reference to hash for embedded objects
1855: # $codebase - reference to hash for codebase of java objects
1856: # $desuname - username for permanent storage of uploaded file
1857: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1858: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1859: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1860: #
1.686 albertel 1861: # output: url of file in userspace, or error: <message>
1862: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1863:
1864:
1.531 albertel 1865: sub userfileupload {
1.860 raeburn 1866: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1867: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1868: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1869: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1870: $fname=&clean_filename($fname);
1.315 www 1871: # See if there is anything left
1.257 www 1872: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1873: chop($env{'form.'.$formname});
1.523 raeburn 1874: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1875: my $now = time;
1876: my $filepath = 'tmp/helprequests/'.$now;
1877: my @parts=split(/\//,$filepath);
1878: my $fullpath = $perlvar{'lonDaemons'};
1879: for (my $i=0;$i<@parts;$i++) {
1880: $fullpath .= '/'.$parts[$i];
1881: if ((-e $fullpath)!=1) {
1882: mkdir($fullpath,0777);
1883: }
1884: }
1885: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1886: print $fh $env{'form.'.$formname};
1.523 raeburn 1887: close($fh);
1.741 raeburn 1888: return $fullpath.'/'.$fname;
1889: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1890: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1891: '_'.$env{'user.domain'}.'/pending';
1892: my @parts=split(/\//,$filepath);
1893: my $fullpath = $perlvar{'lonDaemons'};
1894: for (my $i=0;$i<@parts;$i++) {
1895: $fullpath .= '/'.$parts[$i];
1896: if ((-e $fullpath)!=1) {
1897: mkdir($fullpath,0777);
1898: }
1899: }
1900: open(my $fh,'>'.$fullpath.'/'.$fname);
1901: print $fh $env{'form.'.$formname};
1902: close($fh);
1903: return $fullpath.'/'.$fname;
1.523 raeburn 1904: }
1.719 banghart 1905:
1.258 www 1906: # Create the directory if not present
1.493 albertel 1907: $fname="$subdir/$fname";
1.259 www 1908: if ($coursedoc) {
1.638 albertel 1909: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1910: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1911: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1912: return &finishuserfileupload($docuname,$docudom,
1913: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1914: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1915: } else {
1.620 albertel 1916: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1917: return &process_coursefile('uploaddoc',$docuname,$docudom,
1918: $fname,$formname,$parser,
1919: $allfiles,$codebase);
1.481 raeburn 1920: }
1.719 banghart 1921: } elsif (defined($destuname)) {
1922: my $docuname=$destuname;
1923: my $docudom=$destudom;
1.860 raeburn 1924: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1925: $parser,$allfiles,$codebase,
1926: $thumbwidth,$thumbheight);
1.719 banghart 1927:
1.259 www 1928: } else {
1.638 albertel 1929: my $docuname=$env{'user.name'};
1930: my $docudom=$env{'user.domain'};
1.714 raeburn 1931: if (exists($env{'form.group'})) {
1932: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1933: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1934: }
1.860 raeburn 1935: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1936: $parser,$allfiles,$codebase,
1937: $thumbwidth,$thumbheight);
1.259 www 1938: }
1.271 www 1939: }
1940:
1941: sub finishuserfileupload {
1.860 raeburn 1942: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1943: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1944: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1945: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1946: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1947: $file=$fname;
1948: if ($fname=~m|/|) {
1949: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1950: $path.=$fnamepath.'/';
1951: }
1.259 www 1952: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1953: my $count;
1954: for ($count=4;$count<=$#parts;$count++) {
1955: $filepath.="/$parts[$count]";
1956: if ((-e $filepath)!=1) {
1957: mkdir($filepath,0777);
1958: }
1959: }
1960: # Save the file
1961: {
1.701 albertel 1962: if (!open(FH,'>'.$filepath.'/'.$file)) {
1963: &logthis('Failed to create '.$filepath.'/'.$file);
1964: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1965: return '/adm/notfound.html';
1966: }
1967: if (!print FH ($env{'form.'.$formname})) {
1968: &logthis('Failed to write to '.$filepath.'/'.$file);
1969: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1970: return '/adm/notfound.html';
1971: }
1.570 albertel 1972: close(FH);
1.258 www 1973: }
1.637 raeburn 1974: if ($parser eq 'parse') {
1.638 albertel 1975: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1976: $codebase);
1.637 raeburn 1977: unless ($parse_result eq 'ok') {
1.638 albertel 1978: &logthis('Failed to parse '.$filepath.$file.
1979: ' for embedded media: '.$parse_result);
1.637 raeburn 1980: }
1981: }
1.860 raeburn 1982: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1983: my $input = $filepath.'/'.$file;
1984: my $output = $filepath.'/'.'tn-'.$file;
1985: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1986: system("convert -sample $thumbsize $input $output");
1987: if (-e $filepath.'/'.'tn-'.$file) {
1988: $fetchthumb = 1;
1989: }
1990: }
1.858 raeburn 1991:
1.259 www 1992: # Notify homeserver to grep it
1993: #
1.638 albertel 1994: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1995: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1996: if ($fetchresult eq 'ok') {
1.860 raeburn 1997: if ($fetchthumb) {
1998: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1999: if ($thumbresult ne 'ok') {
2000: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2001: $docuhome.': '.$thumbresult);
2002: }
2003: }
1.259 www 2004: #
1.258 www 2005: # Return the URL to it
1.494 albertel 2006: return '/uploaded/'.$path.$file;
1.263 www 2007: } else {
1.494 albertel 2008: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2009: ': '.$fetchresult);
1.263 www 2010: return '/adm/notfound.html';
1.858 raeburn 2011: }
1.493 albertel 2012: }
2013:
1.637 raeburn 2014: sub extract_embedded_items {
1.648 raeburn 2015: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2016: my @state = ();
2017: my %javafiles = (
2018: codebase => '',
2019: code => '',
2020: archive => ''
2021: );
2022: my %mediafiles = (
2023: src => '',
2024: movie => '',
2025: );
1.648 raeburn 2026: my $p;
2027: if ($content) {
2028: $p = HTML::LCParser->new($content);
2029: } else {
2030: $p = HTML::LCParser->new($filepath.'/'.$file);
2031: }
1.641 albertel 2032: while (my $t=$p->get_token()) {
1.640 albertel 2033: if ($t->[0] eq 'S') {
2034: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2035: push(@state, $tagname);
1.648 raeburn 2036: if (lc($tagname) eq 'allow') {
2037: &add_filetype($allfiles,$attr->{'src'},'src');
2038: }
1.640 albertel 2039: if (lc($tagname) eq 'img') {
2040: &add_filetype($allfiles,$attr->{'src'},'src');
2041: }
1.886 albertel 2042: if (lc($tagname) eq 'a') {
2043: &add_filetype($allfiles,$attr->{'href'},'href');
2044: }
1.645 raeburn 2045: if (lc($tagname) eq 'script') {
2046: if ($attr->{'archive'} =~ /\.jar$/i) {
2047: &add_filetype($allfiles,$attr->{'archive'},'archive');
2048: } else {
2049: &add_filetype($allfiles,$attr->{'src'},'src');
2050: }
2051: }
2052: if (lc($tagname) eq 'link') {
2053: if (lc($attr->{'rel'}) eq 'stylesheet') {
2054: &add_filetype($allfiles,$attr->{'href'},'href');
2055: }
2056: }
1.640 albertel 2057: if (lc($tagname) eq 'object' ||
2058: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2059: foreach my $item (keys(%javafiles)) {
2060: $javafiles{$item} = '';
2061: }
2062: }
2063: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2064: my $name = lc($attr->{'name'});
2065: foreach my $item (keys(%javafiles)) {
2066: if ($name eq $item) {
2067: $javafiles{$item} = $attr->{'value'};
2068: last;
2069: }
2070: }
2071: foreach my $item (keys(%mediafiles)) {
2072: if ($name eq $item) {
2073: &add_filetype($allfiles, $attr->{'value'}, 'value');
2074: last;
2075: }
2076: }
2077: }
2078: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2079: foreach my $item (keys(%javafiles)) {
2080: if ($attr->{$item}) {
2081: $javafiles{$item} = $attr->{$item};
2082: last;
2083: }
2084: }
2085: foreach my $item (keys(%mediafiles)) {
2086: if ($attr->{$item}) {
2087: &add_filetype($allfiles,$attr->{$item},$item);
2088: last;
2089: }
2090: }
2091: }
2092: } elsif ($t->[0] eq 'E') {
2093: my ($tagname) = ($t->[1]);
2094: if ($javafiles{'codebase'} ne '') {
2095: $javafiles{'codebase'} .= '/';
2096: }
2097: if (lc($tagname) eq 'applet' ||
2098: lc($tagname) eq 'object' ||
2099: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2100: ) {
2101: foreach my $item (keys(%javafiles)) {
2102: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2103: my $file=$javafiles{'codebase'}.$javafiles{$item};
2104: &add_filetype($allfiles,$file,$item);
2105: }
2106: }
2107: }
2108: pop @state;
2109: }
2110: }
1.637 raeburn 2111: return 'ok';
2112: }
2113:
1.639 albertel 2114: sub add_filetype {
2115: my ($allfiles,$file,$type)=@_;
2116: if (exists($allfiles->{$file})) {
2117: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2118: push(@{$allfiles->{$file}}, &escape($type));
2119: }
2120: } else {
2121: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2122: }
2123: }
2124:
1.493 albertel 2125: sub removeuploadedurl {
2126: my ($url)=@_;
2127: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2128: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2129: }
2130:
2131: sub removeuserfile {
2132: my ($docuname,$docudom,$fname)=@_;
2133: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2134: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2135: if ($result eq 'ok') {
2136: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2137: my $metafile = $fname.'.meta';
2138: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2139: my $url = "/uploaded/$docudom/$docuname/$fname";
2140: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2141: my $sqlresult =
1.823 albertel 2142: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2143: 'portfolio_metadata',$group,
2144: 'delete');
1.798 raeburn 2145: }
2146: }
2147: return $result;
1.257 www 2148: }
1.15 www 2149:
1.530 albertel 2150: sub mkdiruserfile {
2151: my ($docuname,$docudom,$dir)=@_;
2152: my $home=&homeserver($docuname,$docudom);
2153: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2154: }
2155:
1.531 albertel 2156: sub renameuserfile {
2157: my ($docuname,$docudom,$old,$new)=@_;
2158: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2159: my $result = &reply("renameuserfile:$docudom:$docuname:".
2160: &escape("$old").':'.&escape("$new"),$home);
2161: if ($result eq 'ok') {
2162: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2163: my $oldmeta = $old.'.meta';
2164: my $newmeta = $new.'.meta';
2165: my $metaresult =
2166: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2167: my $url = "/uploaded/$docudom/$docuname/$old";
2168: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2169: my $sqlresult =
1.823 albertel 2170: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2171: 'portfolio_metadata',$group,
2172: 'delete');
1.798 raeburn 2173: }
2174: }
2175: return $result;
1.531 albertel 2176: }
2177:
1.14 www 2178: # ------------------------------------------------------------------------- Log
2179:
2180: sub log {
2181: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2182: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2183: }
2184:
2185: # ------------------------------------------------------------------ Course Log
1.352 www 2186: #
2187: # This routine flushes several buffers of non-mission-critical nature
2188: #
1.157 www 2189:
2190: sub flushcourselogs {
1.352 www 2191: &logthis('Flushing log buffers');
2192: #
2193: # course logs
2194: # This is a log of all transactions in a course, which can be used
2195: # for data mining purposes
2196: #
2197: # It also collects the courseid database, which lists last transaction
2198: # times and course titles for all courseids
2199: #
2200: my %courseidbuffer=();
1.921 raeburn 2201: foreach my $crsid (keys(%courselogs)) {
1.352 www 2202: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2203: &escape($courselogs{$crsid}),
2204: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2205: delete $courselogs{$crsid};
2206: } else {
2207: &logthis('Failed to flush log buffer for '.$crsid);
2208: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2209: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2210: " exceeded maximum size, deleting.</font>");
2211: delete $courselogs{$crsid};
2212: }
1.352 www 2213: }
1.920 raeburn 2214: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2215: 'description' => $coursedescrbuf{$crsid},
2216: 'inst_code' => $courseinstcodebuf{$crsid},
2217: 'type' => $coursetypebuf{$crsid},
2218: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2219: };
1.191 harris41 2220: }
1.352 www 2221: #
2222: # Write course id database (reverse lookup) to homeserver of courses
2223: # Is used in pickcourse
2224: #
1.840 albertel 2225: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2226: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2227: $courseidbuffer{$crs_home},
2228: $crs_home,'timeonly');
1.352 www 2229: }
2230: #
2231: # File accesses
2232: # Writes to the dynamic metadata of resources to get hit counts, etc.
2233: #
1.449 matthew 2234: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2235: if ($entry =~ /___count$/) {
2236: my ($dom,$name);
1.807 albertel 2237: ($dom,$name,undef)=
1.811 albertel 2238: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2239: if (! defined($dom) || $dom eq '' ||
2240: ! defined($name) || $name eq '') {
1.620 albertel 2241: my $cid = $env{'request.course.id'};
2242: $dom = $env{'request.'.$cid.'.domain'};
2243: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2244: }
1.450 matthew 2245: my $value = $accesshash{$entry};
2246: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2247: my %temphash=($url => $value);
1.449 matthew 2248: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2249: if ($result eq 'ok') {
2250: delete $accesshash{$entry};
2251: } elsif ($result eq 'unknown_cmd') {
2252: # Target server has old code running on it.
1.450 matthew 2253: my %temphash=($entry => $value);
1.449 matthew 2254: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2255: delete $accesshash{$entry};
2256: }
2257: }
2258: } else {
1.811 albertel 2259: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2260: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2261: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2262: delete $accesshash{$entry};
2263: }
1.185 www 2264: }
1.191 harris41 2265: }
1.352 www 2266: #
2267: # Roles
2268: # Reverse lookup of user roles for course faculty/staff and co-authorship
2269: #
1.800 albertel 2270: foreach my $entry (keys(%userrolehash)) {
1.351 www 2271: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2272: split(/\:/,$entry);
2273: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2274: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2275: $rudom,$runame) eq 'ok') {
2276: delete $userrolehash{$entry};
2277: }
2278: }
1.662 raeburn 2279: #
2280: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2281: #
2282: my %domrolebuffer = ();
2283: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2284: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2285: if ($domrolebuffer{$rudom}) {
2286: $domrolebuffer{$rudom}.='&'.&escape($entry).
2287: '='.&escape($domainrolehash{$entry});
2288: } else {
2289: $domrolebuffer{$rudom}.=&escape($entry).
2290: '='.&escape($domainrolehash{$entry});
2291: }
2292: delete $domainrolehash{$entry};
2293: }
2294: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2295: my %servers = &get_servers($dom,'library');
2296: foreach my $tryserver (keys(%servers)) {
2297: unless (&reply('domroleput:'.$dom.':'.
2298: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2299: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2300: }
1.662 raeburn 2301: }
2302: }
1.186 www 2303: $dumpcount++;
1.157 www 2304: }
2305:
2306: sub courselog {
2307: my $what=shift;
1.158 www 2308: $what=time.':'.$what;
1.620 albertel 2309: unless ($env{'request.course.id'}) { return ''; }
2310: $coursedombuf{$env{'request.course.id'}}=
2311: $env{'course.'.$env{'request.course.id'}.'.domain'};
2312: $coursenumbuf{$env{'request.course.id'}}=
2313: $env{'course.'.$env{'request.course.id'}.'.num'};
2314: $coursehombuf{$env{'request.course.id'}}=
2315: $env{'course.'.$env{'request.course.id'}.'.home'};
2316: $coursedescrbuf{$env{'request.course.id'}}=
2317: $env{'course.'.$env{'request.course.id'}.'.description'};
2318: $courseinstcodebuf{$env{'request.course.id'}}=
2319: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2320: $courseownerbuf{$env{'request.course.id'}}=
2321: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2322: $coursetypebuf{$env{'request.course.id'}}=
2323: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2324: if (defined $courselogs{$env{'request.course.id'}}) {
2325: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2326: } else {
1.620 albertel 2327: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2328: }
1.620 albertel 2329: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2330: &flushcourselogs();
2331: }
1.158 www 2332: }
2333:
2334: sub courseacclog {
2335: my $fnsymb=shift;
1.620 albertel 2336: unless ($env{'request.course.id'}) { return ''; }
2337: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2338: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2339: $what.=':POST';
1.583 matthew 2340: # FIXME: Probably ought to escape things....
1.800 albertel 2341: foreach my $key (keys(%env)) {
2342: if ($key=~/^form\.(.*)/) {
2343: $what.=':'.$1.'='.$env{$key};
1.158 www 2344: }
1.191 harris41 2345: }
1.583 matthew 2346: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2347: # FIXME: We should not be depending on a form parameter that someone
2348: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2349: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2350: $what.= ':POST';
2351: # FIXME: Probably ought to escape things....
2352: foreach my $element ('courseexp','crsfulltext','crsrelated',
2353: 'crsdiscuss') {
1.620 albertel 2354: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2355: }
2356: }
1.158 www 2357: }
2358: &courselog($what);
1.149 www 2359: }
2360:
1.185 www 2361: sub countacc {
2362: my $url=&declutter(shift);
1.458 matthew 2363: return if (! defined($url) || $url eq '');
1.620 albertel 2364: unless ($env{'request.course.id'}) { return ''; }
2365: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2366: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2367: $accesshash{$key}++;
1.185 www 2368: }
1.349 www 2369:
1.361 www 2370: sub linklog {
2371: my ($from,$to)=@_;
2372: $from=&declutter($from);
2373: $to=&declutter($to);
2374: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2375: $accesshash{$to.'___'.$from.'___goto'}=1;
2376: }
2377:
1.349 www 2378: sub userrolelog {
2379: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2380: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2381: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2382: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2383: ($trole=~/^ta/)) {
1.350 www 2384: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2385: $userrolehash
2386: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2387: =$tend.':'.$tstart;
1.662 raeburn 2388: }
1.898 albertel 2389: if (($env{'request.role'} =~ /dc\./) &&
2390: (($trole=~/^au/) || ($trole=~/^in/) ||
2391: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2392: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2393: $userrolehash
2394: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2395: =$tend.':'.$tstart;
2396: }
1.662 raeburn 2397: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2398: ($trole=~/^li/) || ($trole=~/^li/) ||
2399: ($trole=~/^au/) || ($trole=~/^dg/) ||
2400: ($trole=~/^sc/)) {
2401: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2402: $domainrolehash
2403: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2404: = $tend.':'.$tstart;
2405: }
1.351 www 2406: }
2407:
2408: sub get_course_adv_roles {
2409: my $cid=shift;
1.620 albertel 2410: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2411: my %coursehash=&coursedescription($cid);
1.470 www 2412: my %nothide=();
1.800 albertel 2413: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2414: if ($user !~ /:/) {
2415: $nothide{join(':',split(/[\@]/,$user))}=1;
2416: } else {
2417: $nothide{$user}=1;
2418: }
1.470 www 2419: }
1.351 www 2420: my %returnhash=();
2421: my %dumphash=
2422: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2423: my $now=time;
1.800 albertel 2424: foreach my $entry (keys %dumphash) {
2425: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2426: if (($tstart) && ($tstart<0)) { next; }
2427: if (($tend) && ($tend<$now)) { next; }
2428: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2429: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2430: if ($username eq '' || $domain eq '') { next; }
1.470 www 2431: if ((&privileged($username,$domain)) &&
2432: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2433: if ($role eq 'cr') { next; }
1.351 www 2434: my $key=&plaintext($role);
2435: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2436: if ($returnhash{$key}) {
2437: $returnhash{$key}.=','.$username.':'.$domain;
2438: } else {
2439: $returnhash{$key}=$username.':'.$domain;
2440: }
1.400 www 2441: }
2442: return %returnhash;
2443: }
2444:
2445: sub get_my_roles {
1.937 raeburn 2446: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2447: unless (defined($uname)) { $uname=$env{'user.name'}; }
2448: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2449: my (%dumphash,%nothide);
1.858 raeburn 2450: if ($context eq 'userroles') {
2451: %dumphash = &dump('roles',$udom,$uname);
2452: } else {
2453: %dumphash=
1.400 www 2454: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2455: if ($hidepriv) {
2456: my %coursehash=&coursedescription($udom.'_'.$uname);
2457: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2458: if ($user !~ /:/) {
2459: $nothide{join(':',split(/[\@]/,$user))} = 1;
2460: } else {
2461: $nothide{$user} = 1;
2462: }
2463: }
2464: }
1.858 raeburn 2465: }
1.400 www 2466: my %returnhash=();
2467: my $now=time;
1.800 albertel 2468: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2469: my ($role,$tend,$tstart);
2470: if ($context eq 'userroles') {
2471: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2472: } else {
2473: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2474: }
1.400 www 2475: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2476: my $status = 'active';
1.939 raeburn 2477: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2478: $status = 'previous';
2479: }
2480: if (($tstart) && ($now<$tstart)) {
2481: $status = 'future';
2482: }
2483: if (ref($types) eq 'ARRAY') {
2484: if (!grep(/^\Q$status\E$/,@{$types})) {
2485: next;
2486: }
2487: } else {
2488: if ($status ne 'active') {
2489: next;
2490: }
2491: }
1.867 raeburn 2492: my ($rolecode,$username,$domain,$section,$area);
2493: if ($context eq 'userroles') {
2494: ($area,$rolecode) = split(/_/,$entry);
2495: (undef,$domain,$username,$section) = split(/\//,$area);
2496: } else {
2497: ($role,$username,$domain,$section) = split(/\:/,$entry);
2498: }
1.832 raeburn 2499: if (ref($roledoms) eq 'ARRAY') {
2500: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2501: next;
2502: }
2503: }
2504: if (ref($roles) eq 'ARRAY') {
2505: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2506: if ($role =~ /^cr\//) {
2507: if (!grep(/^cr$/,@{$roles})) {
2508: next;
2509: }
2510: } else {
2511: next;
2512: }
1.832 raeburn 2513: }
1.867 raeburn 2514: }
1.937 raeburn 2515: if ($hidepriv) {
2516: if ((&privileged($username,$domain)) &&
2517: (!$nothide{$username.':'.$domain})) {
2518: next;
2519: }
2520: }
1.933 raeburn 2521: if ($withsec) {
2522: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2523: $tstart.':'.$tend;
2524: } else {
2525: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2526: }
1.832 raeburn 2527: }
1.373 www 2528: return %returnhash;
1.399 www 2529: }
2530:
2531: # ----------------------------------------------------- Frontpage Announcements
2532: #
2533: #
2534:
2535: sub postannounce {
2536: my ($server,$text)=@_;
1.844 albertel 2537: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2538: unless ($text=~/\w/) { $text=''; }
2539: return &reply('setannounce:'.&escape($text),$server);
2540: }
2541:
2542: sub getannounce {
1.448 albertel 2543:
2544: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2545: my $announcement='';
1.800 albertel 2546: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2547: close($fh);
1.399 www 2548: if ($announcement=~/\w/) {
2549: return
2550: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2551: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2552: } else {
2553: return '';
2554: }
2555: } else {
2556: return '';
2557: }
1.351 www 2558: }
1.353 www 2559:
2560: # ---------------------------------------------------------- Course ID routines
2561: # Deal with domain's nohist_courseid.db files
2562: #
2563:
2564: sub courseidput {
1.921 raeburn 2565: my ($domain,$storehash,$coursehome,$caller) = @_;
2566: my $outcome;
2567: if ($caller eq 'timeonly') {
2568: my $cids = '';
2569: foreach my $item (keys(%$storehash)) {
2570: $cids.=&escape($item).'&';
2571: }
2572: $cids=~s/\&$//;
2573: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2574: $coursehome);
2575: } else {
2576: my $items = '';
2577: foreach my $item (keys(%$storehash)) {
2578: $items.= &escape($item).'='.
2579: &freeze_escape($$storehash{$item}).'&';
2580: }
2581: $items=~s/\&$//;
2582: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2583: $coursehome);
1.918 raeburn 2584: }
2585: if ($outcome eq 'unknown_cmd') {
2586: my $what;
2587: foreach my $cid (keys(%$storehash)) {
2588: $what .= &escape($cid).'=';
1.921 raeburn 2589: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2590: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2591: }
2592: $what =~ s/\:$/&/;
2593: }
2594: $what =~ s/\&$//;
2595: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2596: } else {
2597: return $outcome;
2598: }
1.353 www 2599: }
2600:
2601: sub courseiddump {
1.921 raeburn 2602: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
2603: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918 raeburn 2604: my $as_hash = 1;
2605: my %returnhash;
2606: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2607: my %libserv = &all_library();
2608: foreach my $tryserver (keys(%libserv)) {
2609: if ( ( $hostidflag == 1
2610: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2611: || (!defined($hostidflag)) ) {
2612:
1.918 raeburn 2613: if (($domfilter eq '') ||
2614: (&host_domain($tryserver) eq $domfilter)) {
2615: my $rep =
2616: &reply('courseiddump:'.&host_domain($tryserver).':'.
2617: $sincefilter.':'.&escape($descfilter).':'.
2618: &escape($instcodefilter).':'.&escape($ownerfilter).
2619: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.921 raeburn 2620: ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
1.918 raeburn 2621: my @pairs=split(/\&/,$rep);
2622: foreach my $item (@pairs) {
2623: my ($key,$value)=split(/\=/,$item,2);
2624: $key = &unescape($key);
2625: next if ($key =~ /^error: 2 /);
2626: my $result = &thaw_unescape($value);
2627: if (ref($result) eq 'HASH') {
2628: $returnhash{$key}=$result;
2629: } else {
1.921 raeburn 2630: my @responses = split(/:/,$value);
2631: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2632: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2633: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2634: }
2635: }
1.353 www 2636: }
2637: }
2638: }
2639: }
2640: return %returnhash;
2641: }
2642:
1.658 raeburn 2643: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2644:
2645: sub dcmailput {
1.685 raeburn 2646: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2647: my $status = &Apache::lonnet::critical(
1.740 www 2648: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2649: &escape($message),$server);
1.662 raeburn 2650: return $status;
2651: }
2652:
1.658 raeburn 2653: sub dcmaildump {
2654: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2655: my %returnhash=();
1.846 albertel 2656:
2657: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2658: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2659: &escape($enddate).':';
2660: my @esc_senders=map { &escape($_)} @$senders;
2661: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2662: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2663: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2664: if (($key) && ($value)) {
2665: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2666: }
2667: }
2668: }
2669: return %returnhash;
2670: }
1.662 raeburn 2671: # ---------------------------------------------------------- Domain roles
2672:
2673: sub get_domain_roles {
2674: my ($dom,$roles,$startdate,$enddate)=@_;
2675: if (undef($startdate) || $startdate eq '') {
2676: $startdate = '.';
2677: }
2678: if (undef($enddate) || $enddate eq '') {
2679: $enddate = '.';
2680: }
1.922 raeburn 2681: my $rolelist;
2682: if (ref($roles) eq 'ARRAY') {
2683: $rolelist = join(':',@{$roles});
2684: }
1.662 raeburn 2685: my %personnel = ();
1.841 albertel 2686:
2687: my %servers = &get_servers($dom,'library');
2688: foreach my $tryserver (keys(%servers)) {
2689: %{$personnel{$tryserver}}=();
2690: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2691: &escape($startdate).':'.
2692: &escape($enddate).':'.
2693: &escape($rolelist), $tryserver))) {
2694: my ($key,$value) = split(/\=/,$line,2);
2695: if (($key) && ($value)) {
2696: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2697: }
2698: }
1.662 raeburn 2699: }
2700: return %personnel;
2701: }
1.658 raeburn 2702:
1.149 www 2703: # ----------------------------------------------------------- Check out an item
2704:
1.504 albertel 2705: sub get_first_access {
2706: my ($type,$argsymb)=@_;
1.790 albertel 2707: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2708: if ($argsymb) { $symb=$argsymb; }
2709: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2710: if ($type eq 'course') {
2711: $res='course';
2712: } elsif ($type eq 'map') {
1.588 albertel 2713: $res=&symbread($map);
2714: } else {
2715: $res=$symb;
2716: }
2717: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2718: return $times{"$courseid\0$res"};
1.504 albertel 2719: }
2720:
2721: sub set_first_access {
2722: my ($type)=@_;
1.790 albertel 2723: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2724: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 2725: if ($type eq 'course') {
2726: $res='course';
2727: } elsif ($type eq 'map') {
1.588 albertel 2728: $res=&symbread($map);
2729: } else {
2730: $res=$symb;
2731: }
2732: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2733: if (!$firstaccess) {
1.588 albertel 2734: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2735: }
2736: return 'already_set';
1.504 albertel 2737: }
2738:
1.149 www 2739: sub checkout {
2740: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2741: my $now=time;
2742: my $lonhost=$perlvar{'lonHostID'};
2743: my $infostr=&escape(
1.234 www 2744: 'CHECKOUTTOKEN&'.
1.149 www 2745: $tuname.'&'.
2746: $tudom.'&'.
2747: $tcrsid.'&'.
2748: $symb.'&'.
2749: $now.'&'.$ENV{'REMOTE_ADDR'});
2750: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2751: if ($token=~/^error\:/) {
1.672 albertel 2752: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2753: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2754: "</font>");
2755: return '';
2756: }
2757:
1.149 www 2758: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2759: $token=~tr/a-z/A-Z/;
2760:
1.153 www 2761: my %infohash=('resource.0.outtoken' => $token,
2762: 'resource.0.checkouttime' => $now,
2763: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2764:
2765: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2766: return '';
1.151 www 2767: } else {
1.672 albertel 2768: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2769: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2770: "</font>");
1.149 www 2771: }
2772:
2773: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2774: &escape('Checkout '.$infostr.' - '.
2775: $token)) ne 'ok') {
2776: return '';
1.151 www 2777: } else {
1.672 albertel 2778: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2779: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2780: "</font>");
1.149 www 2781: }
1.151 www 2782: return $token;
1.149 www 2783: }
2784:
2785: # ------------------------------------------------------------ Check in an item
2786:
2787: sub checkin {
2788: my $token=shift;
1.150 www 2789: my $now=time;
2790: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2791: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2792: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2793: $dtoken=~s/\W/\_/g;
1.234 www 2794: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2795: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2796:
1.154 www 2797: unless (($tuname) && ($tudom)) {
2798: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2799: return '';
2800: }
2801:
2802: unless (&allowed('mgr',$tcrsid)) {
2803: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2804: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2805: return '';
2806: }
2807:
1.153 www 2808: my %infohash=('resource.0.intoken' => $token,
2809: 'resource.0.checkintime' => $now,
2810: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2811:
2812: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2813: return '';
2814: }
2815:
2816: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2817: &escape('Checkin - '.$token)) ne 'ok') {
2818: return '';
2819: }
2820:
2821: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2822: }
2823:
2824: # --------------------------------------------- Set Expire Date for Spreadsheet
2825:
2826: sub expirespread {
2827: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2828: my $cid=$env{'request.course.id'};
1.110 www 2829: if ($cid) {
2830: my $now=time;
2831: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2832: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2833: $env{'course.'.$cid.'.num'}.
1.110 www 2834: ':nohist_expirationdates:'.
2835: &escape($key).'='.$now,
1.620 albertel 2836: $env{'course.'.$cid.'.home'})
1.110 www 2837: }
2838: return 'ok';
1.14 www 2839: }
2840:
1.109 www 2841: # ----------------------------------------------------- Devalidate Spreadsheets
2842:
2843: sub devalidate {
1.325 www 2844: my ($symb,$uname,$udom)=@_;
1.620 albertel 2845: my $cid=$env{'request.course.id'};
1.109 www 2846: if ($cid) {
1.391 matthew 2847: # delete the stored spreadsheets for
2848: # - the student level sheet of this user in course's homespace
2849: # - the assessment level sheet for this resource
2850: # for this user in user's homespace
1.553 albertel 2851: # - current conditional state info
1.325 www 2852: my $key=$uname.':'.$udom.':';
1.109 www 2853: my $status=
1.299 matthew 2854: &del('nohist_calculatedsheets',
1.391 matthew 2855: [$key.'studentcalc:'],
1.620 albertel 2856: $env{'course.'.$cid.'.domain'},
2857: $env{'course.'.$cid.'.num'})
1.133 albertel 2858: .' '.
2859: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2860: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2861: unless ($status eq 'ok ok') {
2862: &logthis('Could not devalidate spreadsheet '.
1.325 www 2863: $uname.' at '.$udom.' for '.
1.109 www 2864: $symb.': '.$status);
1.133 albertel 2865: }
1.553 albertel 2866: &delenv('user.state.'.$cid);
1.109 www 2867: }
2868: }
2869:
1.265 albertel 2870: sub get_scalar {
2871: my ($string,$end) = @_;
2872: my $value;
2873: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2874: $value = $1;
2875: } elsif ($$string =~ s/^([^&]*?)&//) {
2876: $value = $1;
2877: }
2878: return &unescape($value);
2879: }
2880:
2881: sub array2str {
2882: my (@array) = @_;
2883: my $result=&arrayref2str(\@array);
2884: $result=~s/^__ARRAY_REF__//;
2885: $result=~s/__END_ARRAY_REF__$//;
2886: return $result;
2887: }
2888:
1.204 albertel 2889: sub arrayref2str {
2890: my ($arrayref) = @_;
1.265 albertel 2891: my $result='__ARRAY_REF__';
1.204 albertel 2892: foreach my $elem (@$arrayref) {
1.265 albertel 2893: if(ref($elem) eq 'ARRAY') {
2894: $result.=&arrayref2str($elem).'&';
2895: } elsif(ref($elem) eq 'HASH') {
2896: $result.=&hashref2str($elem).'&';
2897: } elsif(ref($elem)) {
2898: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2899: } else {
2900: $result.=&escape($elem).'&';
2901: }
2902: }
2903: $result=~s/\&$//;
1.265 albertel 2904: $result .= '__END_ARRAY_REF__';
1.204 albertel 2905: return $result;
2906: }
2907:
1.168 albertel 2908: sub hash2str {
1.204 albertel 2909: my (%hash) = @_;
2910: my $result=&hashref2str(\%hash);
1.265 albertel 2911: $result=~s/^__HASH_REF__//;
2912: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2913: return $result;
2914: }
2915:
2916: sub hashref2str {
2917: my ($hashref)=@_;
1.265 albertel 2918: my $result='__HASH_REF__';
1.800 albertel 2919: foreach my $key (sort(keys(%$hashref))) {
2920: if (ref($key) eq 'ARRAY') {
2921: $result.=&arrayref2str($key).'=';
2922: } elsif (ref($key) eq 'HASH') {
2923: $result.=&hashref2str($key).'=';
2924: } elsif (ref($key)) {
1.265 albertel 2925: $result.='=';
1.800 albertel 2926: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2927: } else {
1.800 albertel 2928: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2929: }
2930:
1.800 albertel 2931: if(ref($hashref->{$key}) eq 'ARRAY') {
2932: $result.=&arrayref2str($hashref->{$key}).'&';
2933: } elsif(ref($hashref->{$key}) eq 'HASH') {
2934: $result.=&hashref2str($hashref->{$key}).'&';
2935: } elsif(ref($hashref->{$key})) {
1.265 albertel 2936: $result.='&';
1.800 albertel 2937: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2938: } else {
1.800 albertel 2939: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2940: }
2941: }
1.168 albertel 2942: $result=~s/\&$//;
1.265 albertel 2943: $result .= '__END_HASH_REF__';
1.168 albertel 2944: return $result;
2945: }
2946:
2947: sub str2hash {
1.265 albertel 2948: my ($string)=@_;
2949: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2950: return %$hash;
2951: }
2952:
2953: sub str2hashref {
1.168 albertel 2954: my ($string) = @_;
1.265 albertel 2955:
2956: my %hash;
2957:
2958: if($string !~ /^__HASH_REF__/) {
2959: if (! ($string eq '' || !defined($string))) {
2960: $hash{'error'}='Not hash reference';
2961: }
2962: return (\%hash, $string);
2963: }
2964:
2965: $string =~ s/^__HASH_REF__//;
2966:
2967: while($string !~ /^__END_HASH_REF__/) {
2968: #key
2969: my $key='';
2970: if($string =~ /^__HASH_REF__/) {
2971: ($key, $string)=&str2hashref($string);
2972: if(defined($key->{'error'})) {
2973: $hash{'error'}='Bad data';
2974: return (\%hash, $string);
2975: }
2976: } elsif($string =~ /^__ARRAY_REF__/) {
2977: ($key, $string)=&str2arrayref($string);
2978: if($key->[0] eq 'Array reference error') {
2979: $hash{'error'}='Bad data';
2980: return (\%hash, $string);
2981: }
2982: } else {
2983: $string =~ s/^(.*?)=//;
1.267 albertel 2984: $key=&unescape($1);
1.265 albertel 2985: }
2986: $string =~ s/^=//;
2987:
2988: #value
2989: my $value='';
2990: if($string =~ /^__HASH_REF__/) {
2991: ($value, $string)=&str2hashref($string);
2992: if(defined($value->{'error'})) {
2993: $hash{'error'}='Bad data';
2994: return (\%hash, $string);
2995: }
2996: } elsif($string =~ /^__ARRAY_REF__/) {
2997: ($value, $string)=&str2arrayref($string);
2998: if($value->[0] eq 'Array reference error') {
2999: $hash{'error'}='Bad data';
3000: return (\%hash, $string);
3001: }
3002: } else {
3003: $value=&get_scalar(\$string,'__END_HASH_REF__');
3004: }
3005: $string =~ s/^&//;
3006:
3007: $hash{$key}=$value;
1.204 albertel 3008: }
1.265 albertel 3009:
3010: $string =~ s/^__END_HASH_REF__//;
3011:
3012: return (\%hash, $string);
1.204 albertel 3013: }
3014:
3015: sub str2array {
1.265 albertel 3016: my ($string)=@_;
3017: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3018: return @$array;
3019: }
3020:
3021: sub str2arrayref {
1.204 albertel 3022: my ($string) = @_;
1.265 albertel 3023: my @array;
3024:
3025: if($string !~ /^__ARRAY_REF__/) {
3026: if (! ($string eq '' || !defined($string))) {
3027: $array[0]='Array reference error';
3028: }
3029: return (\@array, $string);
3030: }
3031:
3032: $string =~ s/^__ARRAY_REF__//;
3033:
3034: while($string !~ /^__END_ARRAY_REF__/) {
3035: my $value='';
3036: if($string =~ /^__HASH_REF__/) {
3037: ($value, $string)=&str2hashref($string);
3038: if(defined($value->{'error'})) {
3039: $array[0] ='Array reference error';
3040: return (\@array, $string);
3041: }
3042: } elsif($string =~ /^__ARRAY_REF__/) {
3043: ($value, $string)=&str2arrayref($string);
3044: if($value->[0] eq 'Array reference error') {
3045: $array[0] ='Array reference error';
3046: return (\@array, $string);
3047: }
3048: } else {
3049: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3050: }
3051: $string =~ s/^&//;
3052:
3053: push(@array, $value);
1.191 harris41 3054: }
1.265 albertel 3055:
3056: $string =~ s/^__END_ARRAY_REF__//;
3057:
3058: return (\@array, $string);
1.168 albertel 3059: }
3060:
1.167 albertel 3061: # -------------------------------------------------------------------Temp Store
3062:
1.168 albertel 3063: sub tmpreset {
3064: my ($symb,$namespace,$domain,$stuname) = @_;
3065: if (!$symb) {
3066: $symb=&symbread();
1.620 albertel 3067: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3068: }
3069: $symb=escape($symb);
3070:
1.620 albertel 3071: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3072: $namespace=~s/\//\_/g;
3073: $namespace=~s/\W//g;
3074:
1.620 albertel 3075: if (!$domain) { $domain=$env{'user.domain'}; }
3076: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3077: if ($domain eq 'public' && $stuname eq 'public') {
3078: $stuname=$ENV{'REMOTE_ADDR'};
3079: }
1.168 albertel 3080: my $path=$perlvar{'lonDaemons'}.'/tmp';
3081: my %hash;
3082: if (tie(%hash,'GDBM_File',
3083: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3084: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3085: foreach my $key (keys %hash) {
1.180 albertel 3086: if ($key=~ /:$symb/) {
1.168 albertel 3087: delete($hash{$key});
3088: }
3089: }
3090: }
3091: }
3092:
1.167 albertel 3093: sub tmpstore {
1.168 albertel 3094: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3095:
3096: if (!$symb) {
3097: $symb=&symbread();
1.620 albertel 3098: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3099: }
3100: $symb=escape($symb);
3101:
3102: if (!$namespace) {
3103: # I don't think we would ever want to store this for a course.
3104: # it seems this will only be used if we don't have a course.
1.620 albertel 3105: #$namespace=$env{'request.course.id'};
1.168 albertel 3106: #if (!$namespace) {
1.620 albertel 3107: $namespace=$env{'request.state'};
1.168 albertel 3108: #}
3109: }
3110: $namespace=~s/\//\_/g;
3111: $namespace=~s/\W//g;
1.620 albertel 3112: if (!$domain) { $domain=$env{'user.domain'}; }
3113: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3114: if ($domain eq 'public' && $stuname eq 'public') {
3115: $stuname=$ENV{'REMOTE_ADDR'};
3116: }
1.168 albertel 3117: my $now=time;
3118: my %hash;
3119: my $path=$perlvar{'lonDaemons'}.'/tmp';
3120: if (tie(%hash,'GDBM_File',
3121: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3122: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3123: $hash{"version:$symb"}++;
3124: my $version=$hash{"version:$symb"};
3125: my $allkeys='';
3126: foreach my $key (keys(%$storehash)) {
3127: $allkeys.=$key.':';
1.591 albertel 3128: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3129: }
3130: $hash{"$version:$symb:timestamp"}=$now;
3131: $allkeys.='timestamp';
3132: $hash{"$version:keys:$symb"}=$allkeys;
3133: if (untie(%hash)) {
3134: return 'ok';
3135: } else {
3136: return "error:$!";
3137: }
3138: } else {
3139: return "error:$!";
3140: }
3141: }
1.167 albertel 3142:
1.168 albertel 3143: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3144:
1.168 albertel 3145: sub tmprestore {
3146: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3147:
1.168 albertel 3148: if (!$symb) {
3149: $symb=&symbread();
1.620 albertel 3150: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3151: }
3152: $symb=escape($symb);
3153:
1.620 albertel 3154: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3155:
1.620 albertel 3156: if (!$domain) { $domain=$env{'user.domain'}; }
3157: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3158: if ($domain eq 'public' && $stuname eq 'public') {
3159: $stuname=$ENV{'REMOTE_ADDR'};
3160: }
1.168 albertel 3161: my %returnhash;
3162: $namespace=~s/\//\_/g;
3163: $namespace=~s/\W//g;
3164: my %hash;
3165: my $path=$perlvar{'lonDaemons'}.'/tmp';
3166: if (tie(%hash,'GDBM_File',
3167: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3168: &GDBM_READER(),0640)) {
1.168 albertel 3169: my $version=$hash{"version:$symb"};
3170: $returnhash{'version'}=$version;
3171: my $scope;
3172: for ($scope=1;$scope<=$version;$scope++) {
3173: my $vkeys=$hash{"$scope:keys:$symb"};
3174: my @keys=split(/:/,$vkeys);
3175: my $key;
3176: $returnhash{"$scope:keys"}=$vkeys;
3177: foreach $key (@keys) {
1.591 albertel 3178: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3179: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3180: }
3181: }
1.168 albertel 3182: if (!(untie(%hash))) {
3183: return "error:$!";
3184: }
3185: } else {
3186: return "error:$!";
3187: }
3188: return %returnhash;
1.167 albertel 3189: }
3190:
1.9 www 3191: # ----------------------------------------------------------------------- Store
3192:
3193: sub store {
1.124 www 3194: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3195: my $home='';
3196:
1.168 albertel 3197: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3198:
1.213 www 3199: $symb=&symbclean($symb);
1.122 albertel 3200: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3201:
1.620 albertel 3202: if (!$domain) { $domain=$env{'user.domain'}; }
3203: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3204:
3205: &devalidate($symb,$stuname,$domain);
1.109 www 3206:
3207: $symb=escape($symb);
1.187 www 3208: if (!$namespace) {
1.620 albertel 3209: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3210: return '';
3211: }
3212: }
1.620 albertel 3213: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3214:
3215: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3216: $$storehash{'host'}=$perlvar{'lonHostID'};
3217:
1.12 www 3218: my $namevalue='';
1.800 albertel 3219: foreach my $key (keys(%$storehash)) {
3220: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3221: }
1.12 www 3222: $namevalue=~s/\&$//;
1.187 www 3223: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3224: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3225: }
3226:
1.47 www 3227: # -------------------------------------------------------------- Critical Store
3228:
3229: sub cstore {
1.124 www 3230: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3231: my $home='';
3232:
1.168 albertel 3233: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3234:
1.213 www 3235: $symb=&symbclean($symb);
1.122 albertel 3236: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3237:
1.620 albertel 3238: if (!$domain) { $domain=$env{'user.domain'}; }
3239: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3240:
3241: &devalidate($symb,$stuname,$domain);
1.109 www 3242:
3243: $symb=escape($symb);
1.187 www 3244: if (!$namespace) {
1.620 albertel 3245: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3246: return '';
3247: }
3248: }
1.620 albertel 3249: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3250:
3251: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3252: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3253:
1.47 www 3254: my $namevalue='';
1.800 albertel 3255: foreach my $key (keys(%$storehash)) {
3256: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3257: }
1.47 www 3258: $namevalue=~s/\&$//;
1.187 www 3259: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3260: return critical
3261: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3262: }
3263:
1.9 www 3264: # --------------------------------------------------------------------- Restore
3265:
3266: sub restore {
1.124 www 3267: my ($symb,$namespace,$domain,$stuname) = @_;
3268: my $home='';
3269:
1.168 albertel 3270: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3271:
1.122 albertel 3272: if (!$symb) {
3273: unless ($symb=escape(&symbread())) { return ''; }
3274: } else {
1.213 www 3275: $symb=&escape(&symbclean($symb));
1.122 albertel 3276: }
1.188 www 3277: if (!$namespace) {
1.620 albertel 3278: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3279: return '';
3280: }
3281: }
1.620 albertel 3282: if (!$domain) { $domain=$env{'user.domain'}; }
3283: if (!$stuname) { $stuname=$env{'user.name'}; }
3284: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3285: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3286:
1.12 www 3287: my %returnhash=();
1.800 albertel 3288: foreach my $line (split(/\&/,$answer)) {
3289: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3290: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3291: }
1.75 www 3292: my $version;
3293: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3294: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3295: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3296: }
1.75 www 3297: }
1.13 www 3298: return %returnhash;
1.34 www 3299: }
3300:
3301: # ---------------------------------------------------------- Course Description
3302:
3303: sub coursedescription {
1.731 albertel 3304: my ($courseid,$args)=@_;
1.34 www 3305: $courseid=~s/^\///;
1.49 www 3306: $courseid=~s/\_/\//g;
1.34 www 3307: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3308: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3309: my $normalid=$cdomain.'_'.$cnum;
3310: # need to always cache even if we get errors otherwise we keep
3311: # trying and trying and trying to get the course description.
3312: my %envhash=();
3313: my %returnhash=();
1.731 albertel 3314:
3315: my $expiretime=600;
3316: if ($env{'request.course.id'} eq $normalid) {
3317: $expiretime=120;
3318: }
3319:
3320: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3321: if (!$args->{'freshen_cache'}
3322: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3323: foreach my $key (keys(%env)) {
3324: next if ($key !~ /^\Q$prefix\E(.*)/);
3325: my ($setting) = $1;
3326: $returnhash{$setting} = $env{$key};
3327: }
3328: return %returnhash;
3329: }
3330:
3331: # get the data agin
3332: if (!$args->{'one_time'}) {
3333: $envhash{'course.'.$normalid.'.last_cache'}=time;
3334: }
1.811 albertel 3335:
1.34 www 3336: if ($chome ne 'no_host') {
1.302 albertel 3337: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3338: if (!exists($returnhash{'con_lost'})) {
3339: $returnhash{'home'}= $chome;
3340: $returnhash{'domain'} = $cdomain;
3341: $returnhash{'num'} = $cnum;
1.741 raeburn 3342: if (!defined($returnhash{'type'})) {
3343: $returnhash{'type'} = 'Course';
3344: }
1.130 albertel 3345: while (my ($name,$value) = each %returnhash) {
1.53 www 3346: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3347: }
1.270 www 3348: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3349: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3350: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3351: $envhash{'course.'.$normalid.'.home'}=$chome;
3352: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3353: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3354: }
3355: }
1.731 albertel 3356: if (!$args->{'one_time'}) {
3357: &appenv(%envhash);
3358: }
1.302 albertel 3359: return %returnhash;
1.461 www 3360: }
3361:
3362: # -------------------------------------------------See if a user is privileged
3363:
3364: sub privileged {
3365: my ($username,$domain)=@_;
3366: my $rolesdump=&reply("dump:$domain:$username:roles",
3367: &homeserver($username,$domain));
3368: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3369: my $now=time;
3370: if ($rolesdump ne '') {
1.800 albertel 3371: foreach my $entry (split(/&/,$rolesdump)) {
3372: if ($entry!~/^rolesdef_/) {
3373: my ($area,$role)=split(/=/,$entry);
1.461 www 3374: $area=~s/\_\w\w$//;
3375: my ($trole,$tend,$tstart)=split(/_/,$role);
3376: if (($trole eq 'dc') || ($trole eq 'su')) {
3377: my $active=1;
3378: if ($tend) {
3379: if ($tend<$now) { $active=0; }
3380: }
3381: if ($tstart) {
3382: if ($tstart>$now) { $active=0; }
3383: }
3384: if ($active) { return 1; }
3385: }
3386: }
3387: }
3388: }
3389: return 0;
1.9 www 3390: }
1.1 albertel 3391:
1.103 harris41 3392: # -------------------------------------------------------- Get user privileges
1.11 www 3393:
3394: sub rolesinit {
3395: my ($domain,$username,$authhost)=@_;
3396: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3397: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3398: my %allroles=();
1.678 raeburn 3399: my %allgroups=();
1.11 www 3400: my $now=time;
1.743 albertel 3401: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3402: my $group_privs;
1.11 www 3403:
3404: if ($rolesdump ne '') {
1.800 albertel 3405: foreach my $entry (split(/&/,$rolesdump)) {
3406: if ($entry!~/^rolesdef_/) {
3407: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3408: $area=~s/\_\w\w$//;
1.678 raeburn 3409: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3410: if ($role=~/^cr/) {
1.807 albertel 3411: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3412: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3413: ($tend,$tstart)=split('_',$trest);
3414: } else {
3415: $trole=$role;
3416: }
1.678 raeburn 3417: } elsif ($role =~ m|^gr/|) {
3418: ($trole,$tend,$tstart) = split(/_/,$role);
3419: ($trole,$group_privs) = split(/\//,$trole);
3420: $group_privs = &unescape($group_privs);
1.587 albertel 3421: } else {
3422: ($trole,$tend,$tstart)=split(/_/,$role);
3423: }
1.743 albertel 3424: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3425: $username);
3426: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3427: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3428: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3429: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3430: my $spec=$trole.'.'.$area;
3431: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3432: if ($trole =~ /^cr\//) {
1.567 raeburn 3433: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3434: } elsif ($trole eq 'gr') {
3435: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3436: } else {
1.567 raeburn 3437: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3438: }
1.12 www 3439: }
1.662 raeburn 3440: }
1.191 harris41 3441: }
1.743 albertel 3442: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3443: $userroles{'user.adv'} = $adv;
3444: $userroles{'user.author'} = $author;
1.620 albertel 3445: $env{'user.adv'}=$adv;
1.11 www 3446: }
1.743 albertel 3447: return \%userroles;
1.11 www 3448: }
3449:
1.567 raeburn 3450: sub set_arearole {
3451: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3452: # log the associated role with the area
3453: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3454: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3455: }
3456:
3457: sub custom_roleprivs {
3458: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3459: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3460: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3461: if (&hostname($homsvr) ne '') {
1.567 raeburn 3462: my ($rdummy,$roledef)=
3463: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3464: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3465: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3466: if (defined($syspriv)) {
3467: $$allroles{'cm./'}.=':'.$syspriv;
3468: $$allroles{$spec.'./'}.=':'.$syspriv;
3469: }
3470: if ($tdomain ne '') {
3471: if (defined($dompriv)) {
3472: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3473: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3474: }
3475: if (($trest ne '') && (defined($coursepriv))) {
3476: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3477: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3478: }
3479: }
3480: }
3481: }
3482: }
3483:
1.678 raeburn 3484: sub group_roleprivs {
3485: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3486: my $access = 1;
3487: my $now = time;
3488: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3489: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3490: if ($access) {
1.811 albertel 3491: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3492: $$allgroups{$course}{$group} .=':'.$group_privs;
3493: }
3494: }
1.567 raeburn 3495:
3496: sub standard_roleprivs {
3497: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3498: if (defined($pr{$trole.':s'})) {
3499: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3500: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3501: }
3502: if ($tdomain ne '') {
3503: if (defined($pr{$trole.':d'})) {
3504: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3505: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3506: }
3507: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3508: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3509: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3510: }
3511: }
3512: }
3513:
3514: sub set_userprivs {
1.678 raeburn 3515: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3516: my $author=0;
3517: my $adv=0;
1.678 raeburn 3518: my %grouproles = ();
3519: if (keys(%{$allgroups}) > 0) {
3520: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3521: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3522: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3523: $trole = $1;
3524: $area = $2;
1.681 raeburn 3525: $sec = $3;
3526: $extendedarea = $area.$sec;
3527: if (exists($$allgroups{$area})) {
3528: foreach my $group (keys(%{$$allgroups{$area}})) {
3529: my $spec = $trole.'.'.$extendedarea;
3530: $grouproles{$spec.'.'.$area.'/'.$group} =
3531: $$allgroups{$area}{$group};
1.678 raeburn 3532: }
3533: }
3534: }
3535: }
3536: }
1.800 albertel 3537: foreach my $group (keys(%grouproles)) {
3538: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3539: }
1.800 albertel 3540: foreach my $role (keys(%{$allroles})) {
3541: my %thesepriv;
1.941 raeburn 3542: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3543: foreach my $item (split(/:/,$$allroles{$role})) {
3544: if ($item ne '') {
3545: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3546: if ($restrictions eq '') {
3547: $thesepriv{$privilege}='F';
3548: } elsif ($thesepriv{$privilege} ne 'F') {
3549: $thesepriv{$privilege}.=$restrictions;
3550: }
3551: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3552: }
3553: }
3554: my $thesestr='';
1.800 albertel 3555: foreach my $priv (keys(%thesepriv)) {
3556: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3557: }
3558: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3559: }
3560: return ($author,$adv);
3561: }
3562:
1.12 www 3563: # --------------------------------------------------------------- get interface
3564:
3565: sub get {
1.131 albertel 3566: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3567: my $items='';
1.800 albertel 3568: foreach my $item (@$storearr) {
3569: $items.=&escape($item).'&';
1.191 harris41 3570: }
1.12 www 3571: $items=~s/\&$//;
1.620 albertel 3572: if (!$udomain) { $udomain=$env{'user.domain'}; }
3573: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3574: my $uhome=&homeserver($uname,$udomain);
3575:
1.133 albertel 3576: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3577: my @pairs=split(/\&/,$rep);
1.273 albertel 3578: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3579: return @pairs;
3580: }
1.15 www 3581: my %returnhash=();
1.42 www 3582: my $i=0;
1.800 albertel 3583: foreach my $item (@$storearr) {
3584: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3585: $i++;
1.191 harris41 3586: }
1.15 www 3587: return %returnhash;
1.27 www 3588: }
3589:
3590: # --------------------------------------------------------------- del interface
3591:
3592: sub del {
1.133 albertel 3593: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3594: my $items='';
1.800 albertel 3595: foreach my $item (@$storearr) {
3596: $items.=&escape($item).'&';
1.191 harris41 3597: }
1.27 www 3598: $items=~s/\&$//;
1.620 albertel 3599: if (!$udomain) { $udomain=$env{'user.domain'}; }
3600: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3601: my $uhome=&homeserver($uname,$udomain);
3602:
3603: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3604: }
3605:
3606: # -------------------------------------------------------------- dump interface
3607:
3608: sub dump {
1.755 albertel 3609: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3610: if (!$udomain) { $udomain=$env{'user.domain'}; }
3611: if (!$uname) { $uname=$env{'user.name'}; }
3612: my $uhome=&homeserver($uname,$udomain);
3613: if ($regexp) {
3614: $regexp=&escape($regexp);
3615: } else {
3616: $regexp='.';
3617: }
3618: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3619: my @pairs=split(/\&/,$rep);
3620: my %returnhash=();
3621: foreach my $item (@pairs) {
3622: my ($key,$value)=split(/=/,$item,2);
3623: $key = &unescape($key);
3624: next if ($key =~ /^error: 2 /);
3625: $returnhash{$key}=&thaw_unescape($value);
3626: }
3627: return %returnhash;
1.407 www 3628: }
3629:
1.717 albertel 3630: # --------------------------------------------------------- dumpstore interface
3631:
3632: sub dumpstore {
3633: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3634: if (!$udomain) { $udomain=$env{'user.domain'}; }
3635: if (!$uname) { $uname=$env{'user.name'}; }
3636: my $uhome=&homeserver($uname,$udomain);
3637: if ($regexp) {
3638: $regexp=&escape($regexp);
3639: } else {
3640: $regexp='.';
3641: }
3642: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3643: my @pairs=split(/\&/,$rep);
3644: my %returnhash=();
3645: foreach my $item (@pairs) {
3646: my ($key,$value)=split(/=/,$item,2);
3647: next if ($key =~ /^error: 2 /);
3648: $returnhash{$key}=&thaw_unescape($value);
3649: }
3650: return %returnhash;
1.717 albertel 3651: }
3652:
1.407 www 3653: # -------------------------------------------------------------- keys interface
3654:
3655: sub getkeys {
3656: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3657: if (!$udomain) { $udomain=$env{'user.domain'}; }
3658: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3659: my $uhome=&homeserver($uname,$udomain);
3660: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3661: my @keyarray=();
1.800 albertel 3662: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3663: next if ($key =~ /^error: 2 /);
1.800 albertel 3664: push(@keyarray,&unescape($key));
1.407 www 3665: }
3666: return @keyarray;
1.318 matthew 3667: }
3668:
1.319 matthew 3669: # --------------------------------------------------------------- currentdump
3670: sub currentdump {
1.328 matthew 3671: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3672: $courseid = $env{'request.course.id'} if (! defined($courseid));
3673: $sdom = $env{'user.domain'} if (! defined($sdom));
3674: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3675: my $uhome = &homeserver($sname,$sdom);
3676: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3677: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3678: #
1.318 matthew 3679: my %returnhash=();
1.319 matthew 3680: #
3681: if ($rep eq "unknown_cmd") {
3682: # an old lond will not know currentdump
3683: # Do a dump and make it look like a currentdump
1.822 albertel 3684: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3685: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3686: my %hash = @tmp;
3687: @tmp=();
1.424 matthew 3688: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3689: } else {
3690: my @pairs=split(/\&/,$rep);
1.800 albertel 3691: foreach my $pair (@pairs) {
3692: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3693: my ($symb,$param) = split(/:/,$key);
3694: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3695: &thaw_unescape($value);
1.319 matthew 3696: }
1.191 harris41 3697: }
1.12 www 3698: return %returnhash;
1.424 matthew 3699: }
3700:
3701: sub convert_dump_to_currentdump{
3702: my %hash = %{shift()};
3703: my %returnhash;
3704: # Code ripped from lond, essentially. The only difference
3705: # here is the unescaping done by lonnet::dump(). Conceivably
3706: # we might run in to problems with parameter names =~ /^v\./
3707: while (my ($key,$value) = each(%hash)) {
3708: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3709: $symb = &unescape($symb);
3710: $param = &unescape($param);
1.424 matthew 3711: next if ($v eq 'version' || $symb eq 'keys');
3712: next if (exists($returnhash{$symb}) &&
3713: exists($returnhash{$symb}->{$param}) &&
3714: $returnhash{$symb}->{'v.'.$param} > $v);
3715: $returnhash{$symb}->{$param}=$value;
3716: $returnhash{$symb}->{'v.'.$param}=$v;
3717: }
3718: #
3719: # Remove all of the keys in the hashes which keep track of
3720: # the version of the parameter.
3721: while (my ($symb,$param_hash) = each(%returnhash)) {
3722: # use a foreach because we are going to delete from the hash.
3723: foreach my $key (keys(%$param_hash)) {
3724: delete($param_hash->{$key}) if ($key =~ /^v\./);
3725: }
3726: }
3727: return \%returnhash;
1.12 www 3728: }
3729:
1.627 albertel 3730: # ------------------------------------------------------ critical inc interface
3731:
3732: sub cinc {
3733: return &inc(@_,'critical');
3734: }
3735:
1.449 matthew 3736: # --------------------------------------------------------------- inc interface
3737:
3738: sub inc {
1.627 albertel 3739: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3740: if (!$udomain) { $udomain=$env{'user.domain'}; }
3741: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3742: my $uhome=&homeserver($uname,$udomain);
3743: my $items='';
3744: if (! ref($store)) {
3745: # got a single value, so use that instead
3746: $items = &escape($store).'=&';
3747: } elsif (ref($store) eq 'SCALAR') {
3748: $items = &escape($$store).'=&';
3749: } elsif (ref($store) eq 'ARRAY') {
3750: $items = join('=&',map {&escape($_);} @{$store});
3751: } elsif (ref($store) eq 'HASH') {
3752: while (my($key,$value) = each(%{$store})) {
3753: $items.= &escape($key).'='.&escape($value).'&';
3754: }
3755: }
3756: $items=~s/\&$//;
1.627 albertel 3757: if ($critical) {
3758: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3759: } else {
3760: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3761: }
1.449 matthew 3762: }
3763:
1.12 www 3764: # --------------------------------------------------------------- put interface
3765:
3766: sub put {
1.134 albertel 3767: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3768: if (!$udomain) { $udomain=$env{'user.domain'}; }
3769: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3770: my $uhome=&homeserver($uname,$udomain);
1.12 www 3771: my $items='';
1.800 albertel 3772: foreach my $item (keys(%$storehash)) {
3773: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3774: }
1.12 www 3775: $items=~s/\&$//;
1.134 albertel 3776: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3777: }
3778:
1.631 albertel 3779: # ------------------------------------------------------------ newput interface
3780:
3781: sub newput {
3782: my ($namespace,$storehash,$udomain,$uname)=@_;
3783: if (!$udomain) { $udomain=$env{'user.domain'}; }
3784: if (!$uname) { $uname=$env{'user.name'}; }
3785: my $uhome=&homeserver($uname,$udomain);
3786: my $items='';
3787: foreach my $key (keys(%$storehash)) {
3788: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3789: }
3790: $items=~s/\&$//;
3791: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3792: }
3793:
3794: # --------------------------------------------------------- putstore interface
3795:
1.524 raeburn 3796: sub putstore {
1.715 albertel 3797: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3798: if (!$udomain) { $udomain=$env{'user.domain'}; }
3799: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3800: my $uhome=&homeserver($uname,$udomain);
3801: my $items='';
1.715 albertel 3802: foreach my $key (keys(%$storehash)) {
3803: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3804: }
1.715 albertel 3805: $items=~s/\&$//;
1.716 albertel 3806: my $esc_symb=&escape($symb);
3807: my $esc_v=&escape($version);
1.715 albertel 3808: my $reply =
1.716 albertel 3809: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3810: $uhome);
3811: if ($reply eq 'unknown_cmd') {
1.716 albertel 3812: # gfall back to way things use to be done
1.715 albertel 3813: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3814: $uname);
1.524 raeburn 3815: }
1.715 albertel 3816: return $reply;
3817: }
3818:
3819: sub old_putstore {
1.716 albertel 3820: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3821: if (!$udomain) { $udomain=$env{'user.domain'}; }
3822: if (!$uname) { $uname=$env{'user.name'}; }
3823: my $uhome=&homeserver($uname,$udomain);
3824: my %newstorehash;
1.800 albertel 3825: foreach my $item (keys(%$storehash)) {
3826: my $key = $version.':'.&escape($symb).':'.$item;
3827: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3828: }
3829: my $items='';
3830: my %allitems = ();
1.800 albertel 3831: foreach my $item (keys(%newstorehash)) {
3832: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3833: my $key = $1.':keys:'.$2;
3834: $allitems{$key} .= $3.':';
3835: }
1.800 albertel 3836: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3837: }
1.800 albertel 3838: foreach my $item (keys(%allitems)) {
3839: $allitems{$item} =~ s/\:$//;
3840: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3841: }
3842: $items=~s/\&$//;
3843: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3844: }
3845:
1.47 www 3846: # ------------------------------------------------------ critical put interface
3847:
3848: sub cput {
1.134 albertel 3849: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3850: if (!$udomain) { $udomain=$env{'user.domain'}; }
3851: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3852: my $uhome=&homeserver($uname,$udomain);
1.47 www 3853: my $items='';
1.800 albertel 3854: foreach my $item (keys(%$storehash)) {
3855: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3856: }
1.47 www 3857: $items=~s/\&$//;
1.134 albertel 3858: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3859: }
3860:
3861: # -------------------------------------------------------------- eget interface
3862:
3863: sub eget {
1.133 albertel 3864: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3865: my $items='';
1.800 albertel 3866: foreach my $item (@$storearr) {
3867: $items.=&escape($item).'&';
1.191 harris41 3868: }
1.12 www 3869: $items=~s/\&$//;
1.620 albertel 3870: if (!$udomain) { $udomain=$env{'user.domain'}; }
3871: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3872: my $uhome=&homeserver($uname,$udomain);
3873: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3874: my @pairs=split(/\&/,$rep);
3875: my %returnhash=();
1.42 www 3876: my $i=0;
1.800 albertel 3877: foreach my $item (@$storearr) {
3878: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3879: $i++;
1.191 harris41 3880: }
1.12 www 3881: return %returnhash;
3882: }
3883:
1.667 albertel 3884: # ------------------------------------------------------------ tmpput interface
3885: sub tmpput {
1.802 raeburn 3886: my ($storehash,$server,$context)=@_;
1.667 albertel 3887: my $items='';
1.800 albertel 3888: foreach my $item (keys(%$storehash)) {
3889: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3890: }
3891: $items=~s/\&$//;
1.802 raeburn 3892: if (defined($context)) {
3893: $items .= ':'.&escape($context);
3894: }
1.667 albertel 3895: return &reply("tmpput:$items",$server);
3896: }
3897:
3898: # ------------------------------------------------------------ tmpget interface
3899: sub tmpget {
1.688 albertel 3900: my ($token,$server)=@_;
3901: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3902: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3903: my %returnhash;
3904: foreach my $item (split(/\&/,$rep)) {
3905: my ($key,$value)=split(/=/,$item);
3906: $returnhash{&unescape($key)}=&thaw_unescape($value);
3907: }
3908: return %returnhash;
3909: }
3910:
1.688 albertel 3911: # ------------------------------------------------------------ tmpget interface
3912: sub tmpdel {
3913: my ($token,$server)=@_;
3914: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3915: return &reply("tmpdel:$token",$server);
3916: }
3917:
1.765 albertel 3918: # -------------------------------------------------- portfolio access checking
3919:
3920: sub portfolio_access {
1.766 albertel 3921: my ($requrl) = @_;
1.765 albertel 3922: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3923: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3924: if ($result) {
3925: my %setters;
3926: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3927: my ($startblock,$endblock) =
3928: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3929: if ($startblock && $endblock) {
3930: return 'B';
3931: }
3932: } else {
3933: my ($startblock,$endblock) =
3934: &Apache::loncommon::blockcheck(\%setters,'port');
3935: if ($startblock && $endblock) {
3936: return 'B';
3937: }
3938: }
3939: }
1.765 albertel 3940: if ($result eq 'ok') {
1.766 albertel 3941: return 'F';
1.765 albertel 3942: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3943: return 'A';
1.765 albertel 3944: }
1.766 albertel 3945: return '';
1.765 albertel 3946: }
3947:
3948: sub get_portfolio_access {
1.767 albertel 3949: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3950:
3951: if (!ref($access_hash)) {
3952: my $current_perms = &get_portfile_permissions($udom,$unum);
3953: my %access_controls = &get_access_controls($current_perms,$group,
3954: $file_name);
3955: $access_hash = $access_controls{$file_name};
3956: }
3957:
1.765 albertel 3958: my ($public,$guest,@domains,@users,@courses,@groups);
3959: my $now = time;
3960: if (ref($access_hash) eq 'HASH') {
3961: foreach my $key (keys(%{$access_hash})) {
3962: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3963: if ($start > $now) {
3964: next;
3965: }
3966: if ($end && $end<$now) {
3967: next;
3968: }
3969: if ($scope eq 'public') {
3970: $public = $key;
3971: last;
3972: } elsif ($scope eq 'guest') {
3973: $guest = $key;
3974: } elsif ($scope eq 'domains') {
3975: push(@domains,$key);
3976: } elsif ($scope eq 'users') {
3977: push(@users,$key);
3978: } elsif ($scope eq 'course') {
3979: push(@courses,$key);
3980: } elsif ($scope eq 'group') {
3981: push(@groups,$key);
3982: }
3983: }
3984: if ($public) {
3985: return 'ok';
3986: }
3987: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3988: if ($guest) {
3989: return $guest;
3990: }
3991: } else {
3992: if (@domains > 0) {
3993: foreach my $domkey (@domains) {
3994: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3995: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3996: return 'ok';
3997: }
3998: }
3999: }
4000: }
4001: if (@users > 0) {
4002: foreach my $userkey (@users) {
1.865 raeburn 4003: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4004: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4005: if (ref($item) eq 'HASH') {
4006: if (($item->{'uname'} eq $env{'user.name'}) &&
4007: ($item->{'udom'} eq $env{'user.domain'})) {
4008: return 'ok';
4009: }
4010: }
4011: }
4012: }
1.765 albertel 4013: }
4014: }
4015: my %roleshash;
4016: my @courses_and_groups = @courses;
4017: push(@courses_and_groups,@groups);
4018: if (@courses_and_groups > 0) {
4019: my (%allgroups,%allroles);
4020: my ($start,$end,$role,$sec,$group);
4021: foreach my $envkey (%env) {
1.811 albertel 4022: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4023: my $cid = $2.'_'.$3;
4024: if ($1 eq 'gr') {
4025: $group = $4;
4026: $allgroups{$cid}{$group} = $env{$envkey};
4027: } else {
4028: if ($4 eq '') {
4029: $sec = 'none';
4030: } else {
4031: $sec = $4;
4032: }
4033: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4034: }
1.811 albertel 4035: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4036: my $cid = $2.'_'.$3;
4037: if ($4 eq '') {
4038: $sec = 'none';
4039: } else {
4040: $sec = $4;
4041: }
4042: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4043: }
4044: }
4045: if (keys(%allroles) == 0) {
4046: return;
4047: }
4048: foreach my $key (@courses_and_groups) {
4049: my %content = %{$$access_hash{$key}};
4050: my $cnum = $content{'number'};
4051: my $cdom = $content{'domain'};
4052: my $cid = $cdom.'_'.$cnum;
4053: if (!exists($allroles{$cid})) {
4054: next;
4055: }
4056: foreach my $role_id (keys(%{$content{'roles'}})) {
4057: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4058: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4059: my @status = @{$content{'roles'}{$role_id}{'access'}};
4060: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4061: foreach my $role (keys(%{$allroles{$cid}})) {
4062: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4063: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4064: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4065: if (grep/^all$/,@sections) {
4066: return 'ok';
4067: } else {
4068: if (grep/^$sec$/,@sections) {
4069: return 'ok';
4070: }
4071: }
4072: }
4073: }
4074: if (keys(%{$allgroups{$cid}}) == 0) {
4075: if (grep/^none$/,@groups) {
4076: return 'ok';
4077: }
4078: } else {
4079: if (grep/^all$/,@groups) {
4080: return 'ok';
4081: }
4082: foreach my $group (keys(%{$allgroups{$cid}})) {
4083: if (grep/^$group$/,@groups) {
4084: return 'ok';
4085: }
4086: }
4087: }
4088: }
4089: }
4090: }
4091: }
4092: }
4093: if ($guest) {
4094: return $guest;
4095: }
4096: }
4097: }
4098: return;
4099: }
4100:
4101: sub course_group_datechecker {
4102: my ($dates,$now,$status) = @_;
4103: my ($start,$end) = split(/\./,$dates);
4104: if (!$start && !$end) {
4105: return 'ok';
4106: }
4107: if (grep/^active$/,@{$status}) {
4108: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4109: return 'ok';
4110: }
4111: }
4112: if (grep/^previous$/,@{$status}) {
4113: if ($end > $now ) {
4114: return 'ok';
4115: }
4116: }
4117: if (grep/^future$/,@{$status}) {
4118: if ($start > $now) {
4119: return 'ok';
4120: }
4121: }
4122: return;
4123: }
4124:
4125: sub parse_portfolio_url {
4126: my ($url) = @_;
4127:
4128: my ($type,$udom,$unum,$group,$file_name);
4129:
1.823 albertel 4130: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4131: $type = 1;
4132: $udom = $1;
4133: $unum = $2;
4134: $file_name = $3;
1.823 albertel 4135: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4136: $type = 2;
4137: $udom = $1;
4138: $unum = $2;
4139: $group = $3;
4140: $file_name = $3.'/'.$4;
4141: }
4142: if (wantarray) {
4143: return ($type,$udom,$unum,$file_name,$group);
4144: }
4145: return $type;
4146: }
4147:
4148: sub is_portfolio_url {
4149: my ($url) = @_;
4150: return scalar(&parse_portfolio_url($url));
4151: }
4152:
1.798 raeburn 4153: sub is_portfolio_file {
4154: my ($file) = @_;
1.820 raeburn 4155: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4156: return 1;
4157: }
4158: return;
4159: }
4160:
4161:
1.341 www 4162: # ---------------------------------------------- Custom access rule evaluation
4163:
4164: sub customaccess {
4165: my ($priv,$uri)=@_;
1.807 albertel 4166: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4167: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4168: $udom = &LONCAPA::clean_domain($udom);
4169: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4170: my $access=0;
1.800 albertel 4171: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4172: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4173: if ($type eq 'user') {
4174: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4175: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4176: if ($tdom) {
4177: if ($tdom ne $env{'user.domain'}) { next; }
4178: }
1.896 albertel 4179: if ($tuname) {
4180: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4181: }
4182: $access=($effect eq 'allow');
4183: last;
4184: }
4185: } else {
4186: if ($role) {
4187: if ($role ne $urole) { next; }
4188: }
4189: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4190: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4191: if ($tdom) {
4192: if ($tdom ne $udom) { next; }
4193: }
4194: if ($tcrs) {
4195: if ($tcrs ne $ucrs) { next; }
4196: }
4197: if ($tsec) {
4198: if ($tsec ne $usec) { next; }
4199: }
4200: $access=($effect eq 'allow');
4201: last;
4202: }
4203: if ($realm eq '' && $role eq '') {
4204: $access=($effect eq 'allow');
4205: }
1.402 bowersj2 4206: }
1.341 www 4207: }
4208: return $access;
4209: }
4210:
1.103 harris41 4211: # ------------------------------------------------- Check for a user privilege
1.12 www 4212:
4213: sub allowed {
1.810 raeburn 4214: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4215: my $ver_orguri=$uri;
1.439 www 4216: $uri=&deversion($uri);
1.152 www 4217: my $orguri=$uri;
1.52 www 4218: $uri=&declutter($uri);
1.809 raeburn 4219:
1.810 raeburn 4220: if ($priv eq 'evb') {
4221: # Evade communication block restrictions for specified role in a course
4222: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4223: return $1;
4224: } else {
4225: return;
4226: }
4227: }
4228:
1.620 albertel 4229: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4230: # Free bre access to adm and meta resources
1.775 albertel 4231: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4232: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4233: && ($priv eq 'bre')) {
1.14 www 4234: return 'F';
1.159 www 4235: }
4236:
1.545 banghart 4237: # Free bre access to user's own portfolio contents
1.714 raeburn 4238: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4239: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4240: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4241: my %setters;
4242: my ($startblock,$endblock) =
4243: &Apache::loncommon::blockcheck(\%setters,'port');
4244: if ($startblock && $endblock) {
4245: return 'B';
4246: } else {
4247: return 'F';
4248: }
1.545 banghart 4249: }
4250:
1.762 raeburn 4251: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4252: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4253: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4254: if (exists($env{'request.course.id'})) {
4255: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4256: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4257: if (($domain eq $cdom) && ($name eq $cnum)) {
4258: my $courseprivid=$env{'request.course.id'};
4259: $courseprivid=~s/\_/\//;
4260: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4261: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4262: return $1;
1.762 raeburn 4263: } else {
4264: if ($env{'request.course.sec'}) {
4265: $courseprivid.='/'.$env{'request.course.sec'};
4266: }
4267: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4268: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4269: return $2;
4270: }
1.714 raeburn 4271: }
4272: }
4273: }
4274: }
4275:
1.159 www 4276: # Free bre to public access
4277:
4278: if ($priv eq 'bre') {
1.238 www 4279: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4280: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4281: return 'F';
4282: }
1.238 www 4283: if ($copyright eq 'priv') {
4284: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4285: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4286: return '';
4287: }
4288: }
4289: if ($copyright eq 'domain') {
4290: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4291: unless (($env{'user.domain'} eq $1) ||
4292: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4293: return '';
4294: }
1.262 matthew 4295: }
1.620 albertel 4296: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4297: # Library role, so allow browsing of resources in this domain.
4298: return 'F';
1.238 www 4299: }
1.341 www 4300: if ($copyright eq 'custom') {
4301: unless (&customaccess($priv,$uri)) { return ''; }
4302: }
1.14 www 4303: }
1.264 matthew 4304: # Domain coordinator is trying to create a course
1.620 albertel 4305: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4306: # uri is the requested domain in this case.
4307: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4308: # a role of dc for the domain in question.
1.620 albertel 4309: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4310: }
1.29 www 4311:
1.52 www 4312: my $thisallowed='';
4313: my $statecond=0;
4314: my $courseprivid='';
4315:
4316: # Course
4317:
1.620 albertel 4318: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4319: $thisallowed.=$1;
4320: }
1.29 www 4321:
1.52 www 4322: # Domain
4323:
1.620 albertel 4324: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4325: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4326: $thisallowed.=$1;
4327: }
1.52 www 4328:
4329: # Course: uri itself is a course
1.66 www 4330: my $courseuri=$uri;
4331: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4332: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4333:
1.620 albertel 4334: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4335: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4336: $thisallowed.=$1;
4337: }
1.29 www 4338:
1.665 albertel 4339: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4340: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4341: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4342: $thisallowed='';
1.671 raeburn 4343: my ($match)=&is_on_map($uri);
4344: if ($match) {
4345: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4346: =~/\Q$priv\E\&([^\:]*)/) {
4347: $thisallowed.=$1;
4348: }
4349: } else {
1.705 albertel 4350: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4351: if ($refuri) {
4352: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4353: $thisallowed='F';
1.671 raeburn 4354: } else {
4355: $refuri=&declutter($refuri);
4356: my ($match) = &is_on_map($refuri);
4357: if ($match) {
4358: $thisallowed='F';
4359: }
1.669 raeburn 4360: }
1.671 raeburn 4361: }
4362: }
1.314 www 4363: }
1.492 albertel 4364:
1.766 albertel 4365: if ($priv eq 'bre'
4366: && $thisallowed ne 'F'
4367: && $thisallowed ne '2'
4368: && &is_portfolio_url($uri)) {
4369: $thisallowed = &portfolio_access($uri);
4370: }
4371:
1.52 www 4372: # Full access at system, domain or course-wide level? Exit.
1.29 www 4373:
4374: if ($thisallowed=~/F/) {
4375: return 'F';
4376: }
4377:
1.52 www 4378: # If this is generating or modifying users, exit with special codes
1.29 www 4379:
1.643 www 4380: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4381: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4382: my ($audom,$auname)=split('/',$uri);
1.643 www 4383: # no author name given, so this just checks on the general right to make a co-author in this domain
4384: unless ($auname) { return $thisallowed; }
4385: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4386: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4387: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4388: ($audom ne $env{'request.role.domain'}))) { return ''; }
4389: }
1.52 www 4390: return $thisallowed;
4391: }
4392: #
1.103 harris41 4393: # Gathered so far: system, domain and course wide privileges
1.52 www 4394: #
4395: # Course: See if uri or referer is an individual resource that is part of
4396: # the course
4397:
1.620 albertel 4398: if ($env{'request.course.id'}) {
1.232 www 4399:
1.620 albertel 4400: $courseprivid=$env{'request.course.id'};
4401: if ($env{'request.course.sec'}) {
4402: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4403: }
4404: $courseprivid=~s/\_/\//;
4405: my $checkreferer=1;
1.232 www 4406: my ($match,$cond)=&is_on_map($uri);
4407: if ($match) {
4408: $statecond=$cond;
1.620 albertel 4409: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4410: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4411: $thisallowed.=$1;
4412: $checkreferer=0;
4413: }
1.29 www 4414: }
1.83 www 4415:
1.148 www 4416: if ($checkreferer) {
1.620 albertel 4417: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4418: unless ($refuri) {
1.800 albertel 4419: foreach my $key (keys(%env)) {
4420: if ($key=~/^httpref\..*\*/) {
4421: my $pattern=$key;
1.156 www 4422: $pattern=~s/^httpref\.\/res\///;
1.148 www 4423: $pattern=~s/\*/\[\^\/\]\+/g;
4424: $pattern=~s/\//\\\//g;
1.152 www 4425: if ($orguri=~/$pattern/) {
1.800 albertel 4426: $refuri=$env{$key};
1.148 www 4427: }
4428: }
1.191 harris41 4429: }
1.148 www 4430: }
1.232 www 4431:
1.148 www 4432: if ($refuri) {
1.152 www 4433: $refuri=&declutter($refuri);
1.232 www 4434: my ($match,$cond)=&is_on_map($refuri);
4435: if ($match) {
4436: my $refstatecond=$cond;
1.620 albertel 4437: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4438: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4439: $thisallowed.=$1;
1.53 www 4440: $uri=$refuri;
4441: $statecond=$refstatecond;
1.52 www 4442: }
4443: }
1.148 www 4444: }
1.29 www 4445: }
1.52 www 4446: }
1.29 www 4447:
1.52 www 4448: #
1.103 harris41 4449: # Gathered now: all privileges that could apply, and condition number
1.52 www 4450: #
4451: #
4452: # Full or no access?
4453: #
1.29 www 4454:
1.52 www 4455: if ($thisallowed=~/F/) {
4456: return 'F';
4457: }
1.29 www 4458:
1.52 www 4459: unless ($thisallowed) {
4460: return '';
4461: }
1.29 www 4462:
1.52 www 4463: # Restrictions exist, deal with them
4464: #
4465: # C:according to course preferences
4466: # R:according to resource settings
4467: # L:unless locked
4468: # X:according to user session state
4469: #
4470:
4471: # Possibly locked functionality, check all courses
1.54 www 4472: # Locks might take effect only after 10 minutes cache expiration for other
4473: # courses, and 2 minutes for current course
1.52 www 4474:
4475: my $envkey;
4476: if ($thisallowed=~/L/) {
1.620 albertel 4477: foreach $envkey (keys %env) {
1.54 www 4478: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4479: my $courseid=$2;
4480: my $roleid=$1.'.'.$2;
1.92 www 4481: $courseid=~s/^\///;
1.54 www 4482: my $expiretime=600;
1.620 albertel 4483: if ($env{'request.role'} eq $roleid) {
1.54 www 4484: $expiretime=120;
4485: }
4486: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4487: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4488: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4489: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4490: }
1.620 albertel 4491: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4492: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4493: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4494: &log($env{'user.domain'},$env{'user.name'},
4495: $env{'user.home'},
1.57 www 4496: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4497: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4498: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4499: return '';
4500: }
4501: }
1.620 albertel 4502: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4503: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4504: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4505: &log($env{'user.domain'},$env{'user.name'},
4506: $env{'user.home'},
1.57 www 4507: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4508: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4509: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4510: return '';
4511: }
4512: }
4513: }
1.29 www 4514: }
1.52 www 4515: }
4516:
4517: #
4518: # Rest of the restrictions depend on selected course
4519: #
4520:
1.620 albertel 4521: unless ($env{'request.course.id'}) {
1.766 albertel 4522: if ($thisallowed eq 'A') {
4523: return 'A';
1.814 raeburn 4524: } elsif ($thisallowed eq 'B') {
4525: return 'B';
1.766 albertel 4526: } else {
4527: return '1';
4528: }
1.52 www 4529: }
1.29 www 4530:
1.52 www 4531: #
4532: # Now user is definitely in a course
4533: #
1.53 www 4534:
4535:
4536: # Course preferences
4537:
4538: if ($thisallowed=~/C/) {
1.620 albertel 4539: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4540: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4541: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4542: =~/\Q$rolecode\E/) {
1.689 albertel 4543: if ($priv ne 'pch') {
4544: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4545: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4546: $env{'request.course.id'});
4547: }
1.237 www 4548: return '';
4549: }
4550:
1.620 albertel 4551: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4552: =~/\Q$unamedom\E/) {
1.689 albertel 4553: if ($priv ne 'pch') {
4554: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4555: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4556: $env{'request.course.id'});
4557: }
1.54 www 4558: return '';
4559: }
1.53 www 4560: }
4561:
4562: # Resource preferences
4563:
4564: if ($thisallowed=~/R/) {
1.620 albertel 4565: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4566: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4567: if ($priv ne 'pch') {
4568: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4569: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4570: }
4571: return '';
1.54 www 4572: }
1.53 www 4573: }
1.30 www 4574:
1.246 www 4575: # Restricted by state or randomout?
1.30 www 4576:
1.52 www 4577: if ($thisallowed=~/X/) {
1.620 albertel 4578: if ($env{'acc.randomout'}) {
1.579 albertel 4579: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4580: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4581: return '';
4582: }
1.247 www 4583: }
4584: if (&condval($statecond)) {
1.52 www 4585: return '2';
4586: } else {
4587: return '';
4588: }
4589: }
1.30 www 4590:
1.766 albertel 4591: if ($thisallowed eq 'A') {
4592: return 'A';
1.814 raeburn 4593: } elsif ($thisallowed eq 'B') {
4594: return 'B';
1.766 albertel 4595: }
1.52 www 4596: return 'F';
1.232 www 4597: }
4598:
1.710 albertel 4599: sub split_uri_for_cond {
4600: my $uri=&deversion(&declutter(shift));
4601: my @uriparts=split(/\//,$uri);
4602: my $filename=pop(@uriparts);
4603: my $pathname=join('/',@uriparts);
4604: return ($pathname,$filename);
4605: }
1.232 www 4606: # --------------------------------------------------- Is a resource on the map?
4607:
4608: sub is_on_map {
1.710 albertel 4609: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4610: #Trying to find the conditional for the file
1.620 albertel 4611: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4612: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4613: if ($match) {
1.289 bowersj2 4614: return (1,$1);
4615: } else {
1.434 www 4616: return (0,0);
1.289 bowersj2 4617: }
1.12 www 4618: }
4619:
1.427 www 4620: # --------------------------------------------------------- Get symb from alias
4621:
4622: sub get_symb_from_alias {
4623: my $symb=shift;
4624: my ($map,$resid,$url)=&decode_symb($symb);
4625: # Already is a symb
4626: if ($url) { return $symb; }
4627: # Must be an alias
4628: my $aliassymb='';
4629: my %bighash;
1.620 albertel 4630: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4631: &GDBM_READER(),0640)) {
4632: my $rid=$bighash{'mapalias_'.$symb};
4633: if ($rid) {
4634: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4635: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4636: $resid,$bighash{'src_'.$rid});
1.427 www 4637: }
4638: untie %bighash;
4639: }
4640: return $aliassymb;
4641: }
4642:
1.12 www 4643: # ----------------------------------------------------------------- Define Role
4644:
4645: sub definerole {
4646: if (allowed('mcr','/')) {
4647: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4648: foreach my $role (split(':',$sysrole)) {
4649: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4650: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4651: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4652: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4653: return "refused:s:$crole&$cqual";
4654: }
4655: }
1.191 harris41 4656: }
1.800 albertel 4657: foreach my $role (split(':',$domrole)) {
4658: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4659: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4660: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4661: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4662: return "refused:d:$crole&$cqual";
4663: }
4664: }
1.191 harris41 4665: }
1.800 albertel 4666: foreach my $role (split(':',$courole)) {
4667: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4668: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4669: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4670: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4671: return "refused:c:$crole&$cqual";
4672: }
4673: }
1.191 harris41 4674: }
1.620 albertel 4675: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4676: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4677: "rolesdef_$rolename=".
4678: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4679: return reply($command,$env{'user.home'});
1.12 www 4680: } else {
4681: return 'refused';
4682: }
1.105 harris41 4683: }
4684:
4685: # ---------------- Make a metadata query against the network of library servers
4686:
4687: sub metadata_query {
1.244 matthew 4688: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4689: my %rhash;
1.845 albertel 4690: my %libserv = &all_library();
1.244 matthew 4691: my @server_list = (defined($server_array) ? @$server_array
4692: : keys(%libserv) );
4693: for my $server (@server_list) {
1.118 harris41 4694: unless ($custom or $customshow) {
4695: my $reply=&reply("querysend:".&escape($query),$server);
4696: $rhash{$server}=$reply;
4697: }
4698: else {
4699: my $reply=&reply("querysend:".&escape($query).':'.
4700: &escape($custom).':'.&escape($customshow),
4701: $server);
4702: $rhash{$server}=$reply;
4703: }
1.112 harris41 4704: }
1.118 harris41 4705: return \%rhash;
1.240 www 4706: }
4707:
4708: # ----------------------------------------- Send log queries and wait for reply
4709:
4710: sub log_query {
4711: my ($uname,$udom,$query,%filters)=@_;
4712: my $uhome=&homeserver($uname,$udom);
4713: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4714: my $uhost=&hostname($uhome);
1.800 albertel 4715: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4716: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4717: $uhome);
1.479 albertel 4718: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4719: return get_query_reply($queryid);
4720: }
4721:
1.818 raeburn 4722: # -------------------------- Update MySQL table for portfolio file
4723:
4724: sub update_portfolio_table {
1.821 raeburn 4725: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4726: my $homeserver = &homeserver($uname,$udom);
4727: my $queryid=
1.821 raeburn 4728: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4729: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4730: my $reply = &get_query_reply($queryid);
4731: return $reply;
4732: }
4733:
1.899 raeburn 4734: # -------------------------- Update MySQL allusers table
4735:
4736: sub update_allusers_table {
4737: my ($uname,$udom,$names) = @_;
4738: my $homeserver = &homeserver($uname,$udom);
4739: my $queryid=
4740: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
4741: 'lastname='.&escape($names->{'lastname'}).'%%'.
4742: 'firstname='.&escape($names->{'firstname'}).'%%'.
4743: 'middlename='.&escape($names->{'middlename'}).'%%'.
4744: 'generation='.&escape($names->{'generation'}).'%%'.
4745: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
4746: 'id='.&escape($names->{'id'}),$homeserver);
4747: my $reply = &get_query_reply($queryid);
4748: return $reply;
4749: }
4750:
1.508 raeburn 4751: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4752:
4753: sub fetch_enrollment_query {
1.511 raeburn 4754: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4755: my $homeserver;
1.547 raeburn 4756: my $maxtries = 1;
1.508 raeburn 4757: if ($context eq 'automated') {
4758: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4759: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4760: } else {
4761: $homeserver = &homeserver($cnum,$dom);
4762: }
1.838 albertel 4763: my $host=&hostname($homeserver);
1.506 raeburn 4764: my $cmd = '';
1.800 albertel 4765: foreach my $affiliate (keys %{$affiliatesref}) {
4766: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4767: }
4768: $cmd =~ s/%%$//;
4769: $cmd = &escape($cmd);
4770: my $query = 'fetchenrollment';
1.620 albertel 4771: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4772: unless ($queryid=~/^\Q$host\E\_/) {
4773: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4774: return 'error: '.$queryid;
4775: }
1.506 raeburn 4776: my $reply = &get_query_reply($queryid);
1.547 raeburn 4777: my $tries = 1;
4778: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4779: $reply = &get_query_reply($queryid);
4780: $tries ++;
4781: }
1.526 raeburn 4782: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4783: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4784: } else {
1.901 albertel 4785: my @responses = split(/:/,$reply);
1.515 raeburn 4786: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4787: foreach my $line (@responses) {
4788: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4789: $$replyref{$key} = $value;
4790: }
4791: } else {
1.506 raeburn 4792: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4793: foreach my $line (@responses) {
4794: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4795: $$replyref{$key} = $value;
4796: if ($value > 0) {
1.800 albertel 4797: foreach my $item (@{$$affiliatesref{$key}}) {
4798: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4799: my $destname = $pathname.'/'.$filename;
4800: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4801: if ($xml_classlist =~ /^error/) {
4802: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4803: } else {
1.506 raeburn 4804: if ( open(FILE,">$destname") ) {
4805: print FILE &unescape($xml_classlist);
4806: close(FILE);
1.526 raeburn 4807: } else {
4808: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4809: }
4810: }
4811: }
4812: }
4813: }
4814: }
4815: return 'ok';
4816: }
4817: return 'error';
4818: }
4819:
1.242 www 4820: sub get_query_reply {
4821: my $queryid=shift;
1.240 www 4822: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4823: my $reply='';
4824: for (1..100) {
4825: sleep 2;
4826: if (-e $replyfile.'.end') {
1.448 albertel 4827: if (open(my $fh,$replyfile)) {
1.904 albertel 4828: $reply = join('',<$fh>);
4829: close($fh);
1.240 www 4830: } else { return 'error: reply_file_error'; }
1.242 www 4831: return &unescape($reply);
4832: }
1.240 www 4833: }
1.242 www 4834: return 'timeout:'.$queryid;
1.240 www 4835: }
4836:
4837: sub courselog_query {
1.241 www 4838: #
4839: # possible filters:
4840: # url: url or symb
4841: # username
4842: # domain
4843: # action: view, submit, grade
4844: # start: timestamp
4845: # end: timestamp
4846: #
1.240 www 4847: my (%filters)=@_;
1.620 albertel 4848: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4849: if ($filters{'url'}) {
4850: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4851: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4852: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4853: }
1.620 albertel 4854: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4855: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4856: return &log_query($cname,$cdom,'courselog',%filters);
4857: }
4858:
4859: sub userlog_query {
1.858 raeburn 4860: #
4861: # possible filters:
4862: # action: log check role
4863: # start: timestamp
4864: # end: timestamp
4865: #
1.240 www 4866: my ($uname,$udom,%filters)=@_;
4867: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4868: }
4869:
1.506 raeburn 4870: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4871:
4872: sub auto_run {
1.508 raeburn 4873: my ($cnum,$cdom) = @_;
1.876 raeburn 4874: my $response = 0;
4875: my $settings;
4876: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
4877: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4878: $settings = $domconfig{'autoenroll'};
4879: if ($settings->{'run'} eq '1') {
4880: $response = 1;
4881: }
4882: } else {
1.934 raeburn 4883: my $homeserver;
4884: if (&is_course($cdom,$cnum)) {
4885: $homeserver = &homeserver($cnum,$cdom);
4886: } else {
4887: $homeserver = &domain($cdom,'primary');
4888: }
4889: if ($homeserver ne 'no_host') {
4890: $response = &reply('autorun:'.$cdom,$homeserver);
4891: }
1.876 raeburn 4892: }
1.506 raeburn 4893: return $response;
4894: }
1.776 albertel 4895:
1.506 raeburn 4896: sub auto_get_sections {
1.508 raeburn 4897: my ($cnum,$cdom,$inst_coursecode) = @_;
4898: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4899: my @secs = ();
1.511 raeburn 4900: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4901: unless ($response eq 'refused') {
1.901 albertel 4902: @secs = split(/:/,$response);
1.506 raeburn 4903: }
4904: return @secs;
4905: }
1.776 albertel 4906:
1.506 raeburn 4907: sub auto_new_course {
1.508 raeburn 4908: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4909: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4910: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4911: return $response;
4912: }
1.776 albertel 4913:
1.506 raeburn 4914: sub auto_validate_courseID {
1.508 raeburn 4915: my ($cnum,$cdom,$inst_course_id) = @_;
4916: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4917: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4918: return $response;
4919: }
1.776 albertel 4920:
1.506 raeburn 4921: sub auto_create_password {
1.873 raeburn 4922: my ($cnum,$cdom,$authparam,$udom) = @_;
4923: my ($homeserver,$response);
1.506 raeburn 4924: my $create_passwd = 0;
4925: my $authchk = '';
1.873 raeburn 4926: if ($udom =~ /^$match_domain$/) {
4927: $homeserver = &domain($udom,'primary');
4928: }
4929: if ($homeserver eq '') {
4930: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
4931: $homeserver = &homeserver($cnum,$cdom);
4932: }
4933: }
4934: if ($homeserver eq '') {
4935: $authchk = 'nodomain';
1.506 raeburn 4936: } else {
1.873 raeburn 4937: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4938: if ($response eq 'refused') {
4939: $authchk = 'refused';
4940: } else {
1.901 albertel 4941: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 4942: }
1.506 raeburn 4943: }
4944: return ($authparam,$create_passwd,$authchk);
4945: }
4946:
1.706 raeburn 4947: sub auto_photo_permission {
4948: my ($cnum,$cdom,$students) = @_;
4949: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4950: my ($outcome,$perm_reqd,$conditions) =
4951: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4952: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4953: return (undef,undef);
4954: }
1.706 raeburn 4955: return ($outcome,$perm_reqd,$conditions);
4956: }
4957:
4958: sub auto_checkphotos {
4959: my ($uname,$udom,$pid) = @_;
4960: my $homeserver = &homeserver($uname,$udom);
4961: my ($result,$resulttype);
4962: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4963: &escape($uname).':'.&escape($pid),
4964: $homeserver));
1.709 albertel 4965: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4966: return (undef,undef);
4967: }
1.706 raeburn 4968: if ($outcome) {
4969: ($result,$resulttype) = split(/:/,$outcome);
4970: }
4971: return ($result,$resulttype);
4972: }
4973:
4974: sub auto_photochoice {
4975: my ($cnum,$cdom) = @_;
4976: my $homeserver = &homeserver($cnum,$cdom);
4977: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4978: &escape($cdom),
4979: $homeserver)));
1.709 albertel 4980: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4981: return (undef,undef);
4982: }
1.706 raeburn 4983: return ($update,$comment);
4984: }
4985:
4986: sub auto_photoupdate {
4987: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4988: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4989: my $host=&hostname($homeserver);
1.706 raeburn 4990: my $cmd = '';
4991: my $maxtries = 1;
1.800 albertel 4992: foreach my $affiliate (keys(%{$affiliatesref})) {
4993: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4994: }
4995: $cmd =~ s/%%$//;
4996: $cmd = &escape($cmd);
4997: my $query = 'institutionalphotos';
4998: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4999: unless ($queryid=~/^\Q$host\E\_/) {
5000: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5001: return 'error: '.$queryid;
5002: }
5003: my $reply = &get_query_reply($queryid);
5004: my $tries = 1;
5005: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5006: $reply = &get_query_reply($queryid);
5007: $tries ++;
5008: }
5009: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5010: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5011: } else {
5012: my @responses = split(/:/,$reply);
5013: my $outcome = shift(@responses);
5014: foreach my $item (@responses) {
5015: my ($key,$value) = split(/=/,$item);
5016: $$photo{$key} = $value;
5017: }
5018: return $outcome;
5019: }
5020: return 'error';
5021: }
5022:
1.521 raeburn 5023: sub auto_instcode_format {
1.793 albertel 5024: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5025: $cat_order) = @_;
1.521 raeburn 5026: my $courses = '';
1.772 raeburn 5027: my @homeservers;
1.521 raeburn 5028: if ($caller eq 'global') {
1.841 albertel 5029: my %servers = &get_servers($codedom,'library');
5030: foreach my $tryserver (keys(%servers)) {
5031: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5032: push(@homeservers,$tryserver);
5033: }
1.584 raeburn 5034: }
1.521 raeburn 5035: } else {
1.772 raeburn 5036: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5037: }
1.793 albertel 5038: foreach my $code (keys(%{$instcodes})) {
5039: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5040: }
5041: chop($courses);
1.772 raeburn 5042: my $ok_response = 0;
5043: my $response;
5044: while (@homeservers > 0 && $ok_response == 0) {
5045: my $server = shift(@homeservers);
5046: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5047: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5048: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5049: split(/:/,$response);
1.772 raeburn 5050: %{$codes} = (%{$codes},&str2hash($codes_str));
5051: push(@{$codetitles},&str2array($codetitles_str));
5052: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5053: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5054: $ok_response = 1;
5055: }
5056: }
5057: if ($ok_response) {
1.521 raeburn 5058: return 'ok';
1.772 raeburn 5059: } else {
5060: return $response;
1.521 raeburn 5061: }
5062: }
5063:
1.792 raeburn 5064: sub auto_instcode_defaults {
5065: my ($domain,$returnhash,$code_order) = @_;
5066: my @homeservers;
1.841 albertel 5067:
5068: my %servers = &get_servers($domain,'library');
5069: foreach my $tryserver (keys(%servers)) {
5070: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5071: push(@homeservers,$tryserver);
5072: }
1.792 raeburn 5073: }
1.841 albertel 5074:
1.792 raeburn 5075: my $response;
1.841 albertel 5076: foreach my $server (@homeservers) {
1.792 raeburn 5077: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5078: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5079:
5080: foreach my $pair (split(/\&/,$response)) {
5081: my ($name,$value)=split(/\=/,$pair);
5082: if ($name eq 'code_order') {
5083: @{$code_order} = split(/\&/,&unescape($value));
5084: } else {
5085: $returnhash->{&unescape($name)}=&unescape($value);
5086: }
5087: }
5088: return 'ok';
1.792 raeburn 5089: }
1.841 albertel 5090:
5091: return $response;
1.792 raeburn 5092: }
5093:
1.777 albertel 5094: sub auto_validate_class_sec {
1.918 raeburn 5095: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5096: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5097: my $ownerlist;
5098: if (ref($owners) eq 'ARRAY') {
5099: $ownerlist = join(',',@{$owners});
5100: } else {
5101: $ownerlist = $owners;
5102: }
1.773 raeburn 5103: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5104: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5105: return $response;
5106: }
5107:
1.679 raeburn 5108: # ------------------------------------------------------- Course Group routines
5109:
5110: sub get_coursegroups {
1.809 raeburn 5111: my ($cdom,$cnum,$group,$namespace) = @_;
5112: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5113: }
5114:
1.679 raeburn 5115: sub modify_coursegroup {
5116: my ($cdom,$cnum,$groupsettings) = @_;
5117: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5118: }
5119:
1.809 raeburn 5120: sub toggle_coursegroup_status {
5121: my ($cdom,$cnum,$group,$action) = @_;
5122: my ($from_namespace,$to_namespace);
5123: if ($action eq 'delete') {
5124: $from_namespace = 'coursegroups';
5125: $to_namespace = 'deleted_groups';
5126: } else {
5127: $from_namespace = 'deleted_groups';
5128: $to_namespace = 'coursegroups';
5129: }
5130: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5131: if (my $tmp = &error(%curr_group)) {
5132: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5133: return ('read error',$tmp);
5134: } else {
5135: my %savedsettings = %curr_group;
1.809 raeburn 5136: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5137: my $deloutcome;
5138: if ($result eq 'ok') {
1.809 raeburn 5139: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5140: } else {
5141: return ('write error',$result);
5142: }
5143: if ($deloutcome eq 'ok') {
5144: return 'ok';
5145: } else {
5146: return ('delete error',$deloutcome);
5147: }
5148: }
5149: }
5150:
1.679 raeburn 5151: sub modify_group_roles {
5152: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
5153: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5154: my $role = 'gr/'.&escape($userprivs);
5155: my ($uname,$udom) = split(/:/,$user);
5156: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 5157: if ($result eq 'ok') {
5158: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5159: }
1.679 raeburn 5160: return $result;
5161: }
5162:
5163: sub modify_coursegroup_membership {
5164: my ($cdom,$cnum,$membership) = @_;
5165: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5166: return $result;
5167: }
5168:
1.682 raeburn 5169: sub get_active_groups {
5170: my ($udom,$uname,$cdom,$cnum) = @_;
5171: my $now = time;
5172: my %groups = ();
5173: foreach my $key (keys(%env)) {
1.811 albertel 5174: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5175: my ($start,$end) = split(/\./,$env{$key});
5176: if (($end!=0) && ($end<$now)) { next; }
5177: if (($start!=0) && ($start>$now)) { next; }
5178: if ($1 eq $cdom && $2 eq $cnum) {
5179: $groups{$3} = $env{$key} ;
5180: }
5181: }
5182: }
5183: return %groups;
5184: }
5185:
1.683 raeburn 5186: sub get_group_membership {
5187: my ($cdom,$cnum,$group) = @_;
5188: return(&dump('groupmembership',$cdom,$cnum,$group));
5189: }
5190:
5191: sub get_users_groups {
5192: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5193: my @usersgroups;
1.683 raeburn 5194: my $cachetime=1800;
5195:
5196: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5197: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5198: if (defined($cached)) {
1.734 albertel 5199: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5200: } else {
5201: $grouplist = '';
1.816 raeburn 5202: my $courseurl = &courseid_to_courseurl($courseid);
5203: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5204: my $access_end = $env{'course.'.$courseid.
5205: '.default_enrollment_end_date'};
5206: my $now = time;
5207: foreach my $key (keys(%roleshash)) {
5208: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5209: my $group = $1;
5210: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5211: my $start = $2;
5212: my $end = $1;
5213: if ($start == -1) { next; } # deleted from group
5214: if (($start!=0) && ($start>$now)) { next; }
5215: if (($end!=0) && ($end<$now)) {
5216: if ($access_end && $access_end < $now) {
5217: if ($access_end - $end < 86400) {
5218: push(@usersgroups,$group);
1.733 raeburn 5219: }
5220: }
1.817 raeburn 5221: next;
1.733 raeburn 5222: }
1.817 raeburn 5223: push(@usersgroups,$group);
1.683 raeburn 5224: }
5225: }
5226: }
1.817 raeburn 5227: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5228: $grouplist = join(':',@usersgroups);
5229: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5230: }
1.733 raeburn 5231: return @usersgroups;
1.683 raeburn 5232: }
5233:
5234: sub devalidate_getgroups_cache {
5235: my ($udom,$uname,$cdom,$cnum)=@_;
5236: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5237:
1.683 raeburn 5238: my $hashid="$udom:$uname:$courseid";
5239: &devalidate_cache_new('getgroups',$hashid);
5240: }
5241:
1.12 www 5242: # ------------------------------------------------------------------ Plain Text
5243:
5244: sub plaintext {
1.742 raeburn 5245: my ($short,$type,$cid) = @_;
1.758 albertel 5246: if ($short =~ /^cr/) {
5247: return (split('/',$short))[-1];
5248: }
1.742 raeburn 5249: if (!defined($cid)) {
5250: $cid = $env{'request.course.id'};
5251: }
5252: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5253: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5254: '.plaintext'});
5255: }
5256: my %rolenames = (
5257: Course => 'std',
5258: Group => 'alt1',
5259: );
5260: if (defined($type) &&
5261: defined($rolenames{$type}) &&
5262: defined($prp{$short}{$rolenames{$type}})) {
5263: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5264: } else {
5265: return &Apache::lonlocal::mt($prp{$short}{'std'});
5266: }
1.12 www 5267: }
5268:
5269: # ----------------------------------------------------------------- Assign Role
5270:
5271: sub assignrole {
1.357 www 5272: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 5273: my $mrole;
5274: if ($role =~ /^cr\//) {
1.393 www 5275: my $cwosec=$url;
1.811 albertel 5276: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5277: unless (&allowed('ccr',$cwosec)) {
1.104 www 5278: &logthis('Refused custom assignrole: '.
5279: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5280: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5281: return 'refused';
5282: }
1.21 www 5283: $mrole='cr';
1.678 raeburn 5284: } elsif ($role =~ /^gr\//) {
5285: my $cwogrp=$url;
1.811 albertel 5286: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5287: unless (&allowed('mdg',$cwogrp)) {
5288: &logthis('Refused group assignrole: '.
5289: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5290: $env{'user.name'}.' at '.$env{'user.domain'});
5291: return 'refused';
5292: }
5293: $mrole='gr';
1.21 www 5294: } else {
1.82 www 5295: my $cwosec=$url;
1.811 albertel 5296: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5297: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5298: my $refused;
5299: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5300: if (!(&allowed('c'.$role,$url))) {
5301: $refused = 1;
5302: }
5303: } else {
5304: $refused = 1;
5305: }
5306: if ($refused) {
5307: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5308: ' '.$role.' '.$end.' '.$start.' by '.
5309: $env{'user.name'}.' at '.$env{'user.domain'});
5310: return 'refused';
5311: }
1.104 www 5312: }
1.21 www 5313: $mrole=$role;
5314: }
1.620 albertel 5315: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5316: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5317: if ($end) { $command.='_'.$end; }
1.21 www 5318: if ($start) {
5319: if ($end) {
1.81 www 5320: $command.='_'.$start;
1.21 www 5321: } else {
1.81 www 5322: $command.='_0_'.$start;
1.21 www 5323: }
5324: }
1.739 raeburn 5325: my $origstart = $start;
5326: my $origend = $end;
1.357 www 5327: # actually delete
5328: if ($deleteflag) {
1.373 www 5329: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5330: # modify command to delete the role
1.620 albertel 5331: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5332: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5333: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5334: # set start and finish to negative values for userrolelog
5335: $start=-1;
5336: $end=-1;
5337: }
5338: }
5339: # send command
1.349 www 5340: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5341: # log new user role if status is ok
1.349 www 5342: if ($answer eq 'ok') {
1.663 raeburn 5343: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5344: # for course roles, perform group memberships changes triggered by role change.
5345: unless ($role =~ /^gr/) {
5346: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
5347: $origstart);
5348: }
1.349 www 5349: }
5350: return $answer;
1.169 harris41 5351: }
5352:
5353: # -------------------------------------------------- Modify user authentication
1.197 www 5354: # Overrides without validation
5355:
1.169 harris41 5356: sub modifyuserauth {
5357: my ($udom,$uname,$umode,$upass)=@_;
5358: my $uhome=&homeserver($uname,$udom);
1.197 www 5359: unless (&allowed('mau',$udom)) { return 'refused'; }
5360: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5361: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5362: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5363: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5364: &escape($upass),$uhome);
1.620 albertel 5365: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5366: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5367: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5368: &log($udom,,$uname,$uhome,
1.620 albertel 5369: 'Authentication changed by '.$env{'user.domain'}.', '.
5370: $env{'user.name'}.', '.$umode.
1.197 www 5371: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5372: unless ($reply eq 'ok') {
1.197 www 5373: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5374: return 'error: '.$reply;
5375: }
1.170 harris41 5376: return 'ok';
1.80 www 5377: }
5378:
1.81 www 5379: # --------------------------------------------------------------- Modify a user
1.80 www 5380:
1.81 www 5381: sub modifyuser {
1.206 matthew 5382: my ($udom, $uname, $uid,
5383: $umode, $upass, $first,
5384: $middle, $last, $gene,
1.387 www 5385: $forceid, $desiredhome, $email)=@_;
1.807 albertel 5386: $udom= &LONCAPA::clean_domain($udom);
5387: $uname=&LONCAPA::clean_username($uname);
1.81 www 5388: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5389: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5390: $last.', '.$gene.'(forceid: '.$forceid.')'.
5391: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5392: ' desiredhome not specified').
1.620 albertel 5393: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5394: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5395: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5396: # ----------------------------------------------------------------- Create User
1.406 albertel 5397: if (($uhome eq 'no_host') &&
5398: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5399: my $unhome='';
1.844 albertel 5400: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5401: $unhome = $desiredhome;
1.620 albertel 5402: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5403: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5404: } else { # load balancing routine for determining $unhome
1.81 www 5405: my $loadm=10000000;
1.841 albertel 5406: my %servers = &get_servers($udom,'library');
5407: foreach my $tryserver (keys(%servers)) {
5408: my $answer=reply('load',$tryserver);
5409: if (($answer=~/\d+/) && ($answer<$loadm)) {
5410: $loadm=$answer;
5411: $unhome=$tryserver;
5412: }
1.80 www 5413: }
5414: }
5415: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5416: return 'error: unable to find a home server for '.$uname.
5417: ' in domain '.$udom;
1.80 www 5418: }
5419: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5420: &escape($upass),$unhome);
5421: unless ($reply eq 'ok') {
5422: return 'error: '.$reply;
5423: }
1.230 stredwic 5424: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5425: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5426: return 'error: unable verify users home machine.';
1.80 www 5427: }
1.209 matthew 5428: } # End of creation of new user
1.80 www 5429: # ---------------------------------------------------------------------- Add ID
5430: if ($uid) {
5431: $uid=~tr/A-Z/a-z/;
5432: my %uidhash=&idrget($udom,$uname);
1.196 www 5433: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5434: && (!$forceid)) {
1.80 www 5435: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5436: return 'error: user id "'.$uid.'" does not match '.
5437: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5438: }
5439: } else {
5440: &idput($udom,($uname => $uid));
5441: }
5442: }
5443: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5444: my @tmp=&get('environment',
1.899 raeburn 5445: ['firstname','middlename','lastname','generation','id',
5446: 'permanentemail'],
1.134 albertel 5447: $udom,$uname);
1.313 matthew 5448: my %names;
5449: if ($tmp[0] =~ m/^error:.*/) {
5450: %names=();
5451: } else {
5452: %names = @tmp;
5453: }
1.388 www 5454: #
5455: # Make sure to not trash student environment if instructor does not bother
5456: # to supply name and email information
5457: #
5458: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5459: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5460: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5461: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5462: if ($email) {
5463: $email=~s/[^\w\@\.\-\,]//gs;
5464: if ($email=~/\@/) { $names{'notification'} = $email;
5465: $names{'critnotification'} = $email;
5466: $names{'permanentemail'} = $email; }
5467: }
1.899 raeburn 5468: if ($uid) { $names{'id'} = $uid; }
1.134 albertel 5469: my $reply = &put('environment', \%names, $udom,$uname);
5470: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5471: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5472: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5473: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5474: $umode.', '.$first.', '.$middle.', '.
5475: $last.', '.$gene.' by '.
1.620 albertel 5476: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5477: return 'ok';
1.80 www 5478: }
5479:
1.81 www 5480: # -------------------------------------------------------------- Modify student
1.80 www 5481:
1.81 www 5482: sub modifystudent {
5483: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5484: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5485: if (!$cid) {
1.620 albertel 5486: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5487: return 'not_in_class';
5488: }
1.80 www 5489: }
5490: # --------------------------------------------------------------- Make the user
1.81 www 5491: my $reply=&modifyuser
1.209 matthew 5492: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5493: $desiredhome,$email);
1.80 www 5494: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5495: # This will cause &modify_student_enrollment to get the uid from the
5496: # students environment
5497: $uid = undef if (!$forceid);
1.455 albertel 5498: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5499: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5500: return $reply;
5501: }
5502:
5503: sub modify_student_enrollment {
1.515 raeburn 5504: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5505: my ($cdom,$cnum,$chome);
5506: if (!$cid) {
1.620 albertel 5507: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5508: return 'not_in_class';
5509: }
1.620 albertel 5510: $cdom=$env{'course.'.$cid.'.domain'};
5511: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5512: } else {
5513: ($cdom,$cnum)=split(/_/,$cid);
5514: }
1.620 albertel 5515: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5516: if (!$chome) {
1.457 raeburn 5517: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5518: }
1.455 albertel 5519: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5520: # Make sure the user exists
1.81 www 5521: my $uhome=&homeserver($uname,$udom);
5522: if (($uhome eq '') || ($uhome eq 'no_host')) {
5523: return 'error: no such user';
5524: }
1.297 matthew 5525: # Get student data if we were not given enough information
5526: if (!defined($first) || $first eq '' ||
5527: !defined($last) || $last eq '' ||
5528: !defined($uid) || $uid eq '' ||
5529: !defined($middle) || $middle eq '' ||
5530: !defined($gene) || $gene eq '') {
1.294 matthew 5531: # They did not supply us with enough data to enroll the student, so
5532: # we need to pick up more information.
1.297 matthew 5533: my %tmp = &get('environment',
1.294 matthew 5534: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5535: ,$udom,$uname);
5536:
1.800 albertel 5537: #foreach my $key (keys(%tmp)) {
5538: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5539: #}
1.294 matthew 5540: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5541: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5542: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5543: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5544: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5545: }
1.556 albertel 5546: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5547: my $reply=cput('classlist',
5548: {"$uname:$udom" =>
1.515 raeburn 5549: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5550: $cdom,$cnum);
1.81 www 5551: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5552: return 'error: '.$reply;
1.652 albertel 5553: } else {
5554: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5555: }
1.297 matthew 5556: # Add student role to user
1.83 www 5557: my $uurl='/'.$cid;
1.81 www 5558: $uurl=~s/\_/\//g;
5559: if ($usec) {
5560: $uurl.='/'.$usec;
5561: }
5562: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5563: }
5564:
1.556 albertel 5565: sub format_name {
5566: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5567: my $name;
5568: if ($first ne 'lastname') {
5569: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5570: } else {
5571: if ($lastname=~/\S/) {
5572: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5573: $name=~s/\s+,/,/;
5574: } else {
5575: $name.= $firstname.' '.$middlename.' '.$generation;
5576: }
5577: }
5578: $name=~s/^\s+//;
5579: $name=~s/\s+$//;
5580: $name=~s/\s+/ /g;
5581: return $name;
5582: }
5583:
1.84 www 5584: # ------------------------------------------------- Write to course preferences
5585:
5586: sub writecoursepref {
5587: my ($courseid,%prefs)=@_;
5588: $courseid=~s/^\///;
5589: $courseid=~s/\_/\//g;
5590: my ($cdomain,$cnum)=split(/\//,$courseid);
5591: my $chome=homeserver($cnum,$cdomain);
5592: if (($chome eq '') || ($chome eq 'no_host')) {
5593: return 'error: no such course';
5594: }
5595: my $cstring='';
1.800 albertel 5596: foreach my $pref (keys(%prefs)) {
5597: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5598: }
1.84 www 5599: $cstring=~s/\&$//;
5600: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5601: }
5602:
5603: # ---------------------------------------------------------- Make/modify course
5604:
5605: sub createcourse {
1.741 raeburn 5606: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5607: $course_owner,$crstype)=@_;
1.84 www 5608: $url=&declutter($url);
5609: my $cid='';
1.264 matthew 5610: unless (&allowed('ccc',$udom)) {
1.84 www 5611: return 'refused';
5612: }
5613: # ------------------------------------------------------------------- Create ID
1.674 www 5614: my $uname=int(1+rand(9)).
5615: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5616: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5617: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5618: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5619: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5620: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5621: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5622: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5623: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5624: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5625: return 'error: unable to generate unique course-ID';
5626: }
5627: }
1.264 matthew 5628: # ------------------------------------------------ Check supplied server name
1.620 albertel 5629: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5630: if (! &is_library($course_server)) {
1.264 matthew 5631: return 'error:bad server name '.$course_server;
5632: }
1.84 www 5633: # ------------------------------------------------------------- Make the course
5634: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5635: $course_server);
1.84 www 5636: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5637: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5638: if (($uhome eq '') || ($uhome eq 'no_host')) {
5639: return 'error: no such course';
5640: }
1.271 www 5641: # ----------------------------------------------------------------- Course made
1.516 raeburn 5642: # log existence
1.918 raeburn 5643: my $newcourse = {
5644: $udom.'_'.$uname => {
1.921 raeburn 5645: description => $description,
5646: inst_code => $inst_code,
5647: owner => $course_owner,
5648: type => $crstype,
1.918 raeburn 5649: },
5650: };
1.921 raeburn 5651: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 5652: # set toplevel url
1.271 www 5653: my $topurl=$url;
5654: unless ($nonstandard) {
5655: # ------------------------------------------ For standard courses, make top url
5656: my $mapurl=&clutter($url);
1.278 www 5657: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5658: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5659: <map>
5660: <resource id="1" type="start"></resource>
5661: <resource id="2" src="$mapurl"></resource>
5662: <resource id="3" type="finish"></resource>
5663: <link index="1" from="1" to="2"></link>
5664: <link index="2" from="2" to="3"></link>
5665: </map>
5666: ENDINITMAP
5667: $topurl=&declutter(
1.638 albertel 5668: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5669: );
5670: }
5671: # ----------------------------------------------------------- Write preferences
1.84 www 5672: &writecoursepref($udom.'_'.$uname,
5673: ('description' => $description,
1.271 www 5674: 'url' => $topurl));
1.84 www 5675: return '/'.$udom.'/'.$uname;
5676: }
5677:
1.813 albertel 5678: sub is_course {
5679: my ($cdom,$cnum) = @_;
5680: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918 raeburn 5681: undef,'.',undef,1);
1.813 albertel 5682: if (exists($courses{$cdom.'_'.$cnum})) {
5683: return 1;
5684: }
5685: return 0;
5686: }
5687:
1.21 www 5688: # ---------------------------------------------------------- Assign Custom Role
5689:
5690: sub assigncustomrole {
1.357 www 5691: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5692: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5693: $end,$start,$deleteflag);
1.21 www 5694: }
5695:
5696: # ----------------------------------------------------------------- Revoke Role
5697:
5698: sub revokerole {
1.357 www 5699: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5700: my $now=time;
1.357 www 5701: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5702: }
5703:
5704: # ---------------------------------------------------------- Revoke Custom Role
5705:
5706: sub revokecustomrole {
1.357 www 5707: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5708: my $now=time;
1.357 www 5709: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5710: $deleteflag);
1.17 www 5711: }
5712:
1.533 banghart 5713: # ------------------------------------------------------------ Disk usage
1.535 albertel 5714: sub diskusage {
1.533 banghart 5715: my ($udom,$uname,$directoryRoot)=@_;
5716: $directoryRoot =~ s/\/$//;
1.535 albertel 5717: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5718: return $listing;
1.512 banghart 5719: }
5720:
1.566 banghart 5721: sub is_locked {
5722: my ($file_name, $domain, $user) = @_;
5723: my @check;
5724: my $is_locked;
5725: push @check, $file_name;
1.613 albertel 5726: my %locked = &get('file_permissions',\@check,
1.620 albertel 5727: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5728: my ($tmp)=keys(%locked);
5729: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5730:
1.566 banghart 5731: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5732: $is_locked = 'false';
5733: foreach my $entry (@{$locked{$file_name}}) {
5734: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5735: $is_locked = 'true';
5736: last;
1.745 raeburn 5737: }
5738: }
1.566 banghart 5739: } else {
5740: $is_locked = 'false';
5741: }
5742: }
5743:
1.759 albertel 5744: sub declutter_portfile {
5745: my ($file) = @_;
1.833 albertel 5746: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5747: return $file;
5748: }
5749:
1.559 banghart 5750: # ------------------------------------------------------------- Mark as Read Only
5751:
5752: sub mark_as_readonly {
5753: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5754: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5755: my ($tmp)=keys(%current_permissions);
5756: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5757: foreach my $file (@{$files}) {
1.759 albertel 5758: $file = &declutter_portfile($file);
1.561 banghart 5759: push(@{$current_permissions{$file}},$what);
1.559 banghart 5760: }
1.613 albertel 5761: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5762: return;
5763: }
5764:
1.572 banghart 5765: # ------------------------------------------------------------Save Selected Files
5766:
5767: sub save_selected_files {
5768: my ($user, $path, @files) = @_;
5769: my $filename = $user."savedfiles";
1.573 banghart 5770: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 5771: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5772: foreach my $file (@files) {
1.620 albertel 5773: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5774: }
5775: foreach my $file (@other_files) {
1.574 banghart 5776: print (OUT $file."\n");
1.572 banghart 5777: }
1.574 banghart 5778: close (OUT);
1.572 banghart 5779: return 'ok';
5780: }
5781:
1.574 banghart 5782: sub clear_selected_files {
5783: my ($user) = @_;
5784: my $filename = $user."savedfiles";
5785: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5786: print (OUT undef);
5787: close (OUT);
5788: return ("ok");
5789: }
5790:
1.572 banghart 5791: sub files_in_path {
5792: my ($user, $path) = @_;
5793: my $filename = $user."savedfiles";
5794: my %return_files;
1.574 banghart 5795: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5796: while (my $line_in = <IN>) {
1.574 banghart 5797: chomp ($line_in);
5798: my @paths_and_file = split (m!/!, $line_in);
5799: my $file_part = pop (@paths_and_file);
5800: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5801: $path_part.='/';
5802: my $path_and_file = $path_part.$file_part;
5803: if ($path_part eq $path) {
5804: $return_files{$file_part}= 'selected';
5805: }
5806: }
1.574 banghart 5807: close (IN);
5808: return (\%return_files);
1.572 banghart 5809: }
5810:
5811: # called in portfolio select mode, to show files selected NOT in current directory
5812: sub files_not_in_path {
5813: my ($user, $path) = @_;
5814: my $filename = $user."savedfiles";
5815: my @return_files;
5816: my $path_part;
1.800 albertel 5817: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5818: while (my $line = <IN>) {
1.572 banghart 5819: #ok, I know it's clunky, but I want it to work
1.800 albertel 5820: my @paths_and_file = split(m|/|, $line);
5821: my $file_part = pop(@paths_and_file);
5822: chomp($file_part);
5823: my $path_part = join('/', @paths_and_file);
1.572 banghart 5824: $path_part .= '/';
5825: my $path_and_file = $path_part.$file_part;
5826: if ($path_part ne $path) {
1.800 albertel 5827: push(@return_files, ($path_and_file));
1.572 banghart 5828: }
5829: }
1.800 albertel 5830: close(OUT);
1.574 banghart 5831: return (@return_files);
1.572 banghart 5832: }
5833:
1.745 raeburn 5834: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5835:
1.745 raeburn 5836: sub get_portfile_permissions {
5837: my ($domain,$user) = @_;
1.613 albertel 5838: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5839: my ($tmp)=keys(%current_permissions);
5840: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5841: return \%current_permissions;
5842: }
5843:
5844: #---------------------------------------------Get portfolio file access controls
5845:
1.749 raeburn 5846: sub get_access_controls {
1.745 raeburn 5847: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5848: my %access;
5849: my $real_file = $file;
5850: $file =~ s/\.meta$//;
1.745 raeburn 5851: if (defined($file)) {
1.749 raeburn 5852: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5853: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5854: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5855: }
5856: }
1.745 raeburn 5857: } else {
1.749 raeburn 5858: foreach my $key (keys(%{$current_permissions})) {
5859: if ($key =~ /\0accesscontrol$/) {
5860: if (defined($group)) {
5861: if ($key !~ m-^\Q$group\E/-) {
5862: next;
5863: }
5864: }
5865: my ($fullpath) = split(/\0/,$key);
5866: if (ref($$current_permissions{$key}) eq 'HASH') {
5867: foreach my $control (keys(%{$$current_permissions{$key}})) {
5868: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5869: }
5870: }
5871: }
5872: }
5873: }
5874: return %access;
5875: }
5876:
5877: sub modify_access_controls {
5878: my ($file_name,$changes,$domain,$user)=@_;
5879: my ($outcome,$deloutcome);
5880: my %store_permissions;
5881: my %new_values;
5882: my %new_control;
5883: my %translation;
5884: my @deletions = ();
5885: my $now = time;
5886: if (exists($$changes{'activate'})) {
5887: if (ref($$changes{'activate'}) eq 'HASH') {
5888: my @newitems = sort(keys(%{$$changes{'activate'}}));
5889: my $numnew = scalar(@newitems);
5890: for (my $i=0; $i<$numnew; $i++) {
5891: my $newkey = $newitems[$i];
5892: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5893: if ($newkey =~ /^\d+:/) {
5894: $newkey =~ s/^(\d+)/$newid/;
5895: $translation{$1} = $newid;
5896: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5897: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5898: $translation{$1} = $newid;
5899: }
1.749 raeburn 5900: $new_values{$file_name."\0".$newkey} =
5901: $$changes{'activate'}{$newitems[$i]};
5902: $new_control{$newkey} = $now;
5903: }
5904: }
5905: }
5906: my %todelete;
5907: my %changed_items;
5908: foreach my $action ('delete','update') {
5909: if (exists($$changes{$action})) {
5910: if (ref($$changes{$action}) eq 'HASH') {
5911: foreach my $key (keys(%{$$changes{$action}})) {
5912: my ($itemnum) = ($key =~ /^([^:]+):/);
5913: if ($action eq 'delete') {
5914: $todelete{$itemnum} = 1;
5915: } else {
5916: $changed_items{$itemnum} = $key;
5917: }
5918: }
1.745 raeburn 5919: }
5920: }
1.749 raeburn 5921: }
5922: # get lock on access controls for file.
5923: my $lockhash = {
5924: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5925: ':'.$env{'user.domain'},
5926: };
5927: my $tries = 0;
5928: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5929:
5930: while (($gotlock ne 'ok') && $tries <3) {
5931: $tries ++;
5932: sleep 1;
5933: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5934: }
5935: if ($gotlock eq 'ok') {
5936: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5937: my ($tmp)=keys(%curr_permissions);
5938: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5939: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5940: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5941: if (ref($curr_controls) eq 'HASH') {
5942: foreach my $control_item (keys(%{$curr_controls})) {
5943: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5944: if (defined($todelete{$itemnum})) {
5945: push(@deletions,$file_name."\0".$control_item);
5946: } else {
5947: if (defined($changed_items{$itemnum})) {
5948: $new_control{$changed_items{$itemnum}} = $now;
5949: push(@deletions,$file_name."\0".$control_item);
5950: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5951: } else {
5952: $new_control{$control_item} = $$curr_controls{$control_item};
5953: }
5954: }
1.745 raeburn 5955: }
5956: }
5957: }
1.749 raeburn 5958: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5959: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5960: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5961: # remove lock
5962: my @del_lock = ($file_name."\0".'locked_access_records');
5963: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5964: my ($file,$group);
5965: if (&is_course($domain,$user)) {
5966: ($group,$file) = split(/\//,$file_name,2);
5967: } else {
5968: $file = $file_name;
5969: }
5970: my $sqlresult =
5971: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5972: $group);
1.749 raeburn 5973: } else {
5974: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5975: }
1.749 raeburn 5976: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5977: }
5978:
1.827 raeburn 5979: sub make_public_indefinitely {
5980: my ($requrl) = @_;
5981: my $now = time;
5982: my $action = 'activate';
5983: my $aclnum = 0;
5984: if (&is_portfolio_url($requrl)) {
5985: my (undef,$udom,$unum,$file_name,$group) =
5986: &parse_portfolio_url($requrl);
5987: my $current_perms = &get_portfile_permissions($udom,$unum);
5988: my %access_controls = &get_access_controls($current_perms,
5989: $group,$file_name);
5990: foreach my $key (keys(%{$access_controls{$file_name}})) {
5991: my ($num,$scope,$end,$start) =
5992: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5993: if ($scope eq 'public') {
5994: if ($start <= $now && $end == 0) {
5995: $action = 'none';
5996: } else {
5997: $action = 'update';
5998: $aclnum = $num;
5999: }
6000: last;
6001: }
6002: }
6003: if ($action eq 'none') {
6004: return 'ok';
6005: } else {
6006: my %changes;
6007: my $newend = 0;
6008: my $newstart = $now;
6009: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6010: $changes{$action}{$newkey} = {
6011: type => 'public',
6012: time => {
6013: start => $newstart,
6014: end => $newend,
6015: },
6016: };
6017: my ($outcome,$deloutcome,$new_values,$translation) =
6018: &modify_access_controls($file_name,\%changes,$udom,$unum);
6019: return $outcome;
6020: }
6021: } else {
6022: return 'invalid';
6023: }
6024: }
6025:
1.745 raeburn 6026: #------------------------------------------------------Get Marked as Read Only
6027:
6028: sub get_marked_as_readonly {
6029: my ($domain,$user,$what,$group) = @_;
6030: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6031: my @readonly_files;
1.629 banghart 6032: my $cmp1=$what;
6033: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6034: while (my ($file_name,$value) = each(%{$current_permissions})) {
6035: if (defined($group)) {
6036: if ($file_name !~ m-^\Q$group\E/-) {
6037: next;
6038: }
6039: }
1.561 banghart 6040: if (ref($value) eq "ARRAY"){
6041: foreach my $stored_what (@{$value}) {
1.629 banghart 6042: my $cmp2=$stored_what;
1.759 albertel 6043: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6044: $cmp2=join('',@{$stored_what});
1.745 raeburn 6045: }
1.629 banghart 6046: if ($cmp1 eq $cmp2) {
1.561 banghart 6047: push(@readonly_files, $file_name);
1.745 raeburn 6048: last;
1.563 banghart 6049: } elsif (!defined($what)) {
6050: push(@readonly_files, $file_name);
1.745 raeburn 6051: last;
1.561 banghart 6052: }
6053: }
1.745 raeburn 6054: }
1.561 banghart 6055: }
6056: return @readonly_files;
6057: }
1.577 banghart 6058: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6059:
1.577 banghart 6060: sub get_marked_as_readonly_hash {
1.745 raeburn 6061: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6062: my %readonly_files;
1.745 raeburn 6063: while (my ($file_name,$value) = each(%{$current_permissions})) {
6064: if (defined($group)) {
6065: if ($file_name !~ m-^\Q$group\E/-) {
6066: next;
6067: }
6068: }
1.577 banghart 6069: if (ref($value) eq "ARRAY"){
6070: foreach my $stored_what (@{$value}) {
1.745 raeburn 6071: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6072: foreach my $lock_descriptor(@{$stored_what}) {
6073: if ($lock_descriptor eq 'graded') {
6074: $readonly_files{$file_name} = 'graded';
6075: } elsif ($lock_descriptor eq 'handback') {
6076: $readonly_files{$file_name} = 'handback';
6077: } else {
6078: if (!exists($readonly_files{$file_name})) {
6079: $readonly_files{$file_name} = 'locked';
6080: }
6081: }
1.745 raeburn 6082: }
1.750 banghart 6083: }
1.577 banghart 6084: }
6085: }
6086: }
6087: return %readonly_files;
6088: }
1.559 banghart 6089: # ------------------------------------------------------------ Unmark as Read Only
6090:
6091: sub unmark_as_readonly {
1.629 banghart 6092: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6093: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6094: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6095: $file_name = &declutter_portfile($file_name);
1.634 albertel 6096: my $symb_crs = $what;
6097: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6098: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6099: my ($tmp)=keys(%current_permissions);
6100: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6101: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6102: foreach my $file (@readonly_files) {
1.759 albertel 6103: my $clean_file = &declutter_portfile($file);
6104: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6105: my $current_locks = $current_permissions{$file};
1.563 banghart 6106: my @new_locks;
6107: my @del_keys;
6108: if (ref($current_locks) eq "ARRAY"){
6109: foreach my $locker (@{$current_locks}) {
1.632 albertel 6110: my $compare=$locker;
1.749 raeburn 6111: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6112: $compare=join('',@{$locker});
1.746 raeburn 6113: if ($compare ne $symb_crs) {
6114: push(@new_locks, $locker);
6115: }
1.563 banghart 6116: }
6117: }
1.650 albertel 6118: if (scalar(@new_locks) > 0) {
1.563 banghart 6119: $current_permissions{$file} = \@new_locks;
6120: } else {
6121: push(@del_keys, $file);
1.613 albertel 6122: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6123: delete($current_permissions{$file});
1.563 banghart 6124: }
6125: }
1.561 banghart 6126: }
1.613 albertel 6127: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6128: return;
6129: }
1.512 banghart 6130:
1.17 www 6131: # ------------------------------------------------------------ Directory lister
6132:
6133: sub dirlist {
1.253 stredwic 6134: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
6135:
1.18 www 6136: $uri=~s/^\///;
6137: $uri=~s/\/$//;
1.253 stredwic 6138: my ($udom, $uname);
6139: (undef,$udom,$uname)=split(/\//,$uri);
6140: if(defined($userdomain)) {
6141: $udom = $userdomain;
6142: }
6143: if(defined($username)) {
6144: $uname = $username;
6145: }
6146:
6147: my $dirRoot = $perlvar{'lonDocRoot'};
6148: if(defined($alternateDirectoryRoot)) {
6149: $dirRoot = $alternateDirectoryRoot;
6150: $dirRoot =~ s/\/$//;
1.751 banghart 6151: }
1.253 stredwic 6152:
6153: if($udom) {
6154: if($uname) {
1.800 albertel 6155: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6156: &homeserver($uname,$udom));
1.605 matthew 6157: my @listing_results;
6158: if ($listing eq 'unknown_cmd') {
1.800 albertel 6159: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6160: &homeserver($uname,$udom));
1.605 matthew 6161: @listing_results = split(/:/,$listing);
6162: } else {
6163: @listing_results = map { &unescape($_); } split(/:/,$listing);
6164: }
6165: return @listing_results;
1.253 stredwic 6166: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 6167: my %allusers;
1.841 albertel 6168: my %servers = &get_servers($udom,'library');
6169: foreach my $tryserver (keys(%servers)) {
6170: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6171: $udom, $tryserver);
6172: my @listing_results;
6173: if ($listing eq 'unknown_cmd') {
6174: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6175: $udom, $tryserver);
6176: @listing_results = split(/:/,$listing);
6177: } else {
6178: @listing_results =
6179: map { &unescape($_); } split(/:/,$listing);
6180: }
6181: if ($listing_results[0] ne 'no_such_dir' &&
6182: $listing_results[0] ne 'empty' &&
6183: $listing_results[0] ne 'con_lost') {
6184: foreach my $line (@listing_results) {
6185: my ($entry) = split(/&/,$line,2);
6186: $allusers{$entry} = 1;
6187: }
6188: }
1.253 stredwic 6189: }
6190: my $alluserstr='';
1.800 albertel 6191: foreach my $user (sort(keys(%allusers))) {
6192: $alluserstr.=$user.'&user:';
1.253 stredwic 6193: }
6194: $alluserstr=~s/:$//;
6195: return split(/:/,$alluserstr);
6196: } else {
1.800 albertel 6197: return ('missing user name');
1.253 stredwic 6198: }
6199: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 6200: my @all_domains = sort(&all_domains());
6201: foreach my $domain (@all_domains) {
6202: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6203: }
6204: return @all_domains;
6205: } else {
1.800 albertel 6206: return ('missing domain');
1.275 stredwic 6207: }
6208: }
6209:
6210: # --------------------------------------------- GetFileTimestamp
6211: # This function utilizes dirlist and returns the date stamp for
6212: # when it was last modified. It will also return an error of -1
6213: # if an error occurs
6214:
1.410 matthew 6215: ##
6216: ## FIXME: This subroutine assumes its caller knows something about the
6217: ## directory structure of the home server for the student ($root).
6218: ## Not a good assumption to make. Since this is for looking up files
6219: ## in user directories, the full path should be constructed by lond, not
6220: ## whatever machine we request data from.
6221: ##
1.275 stredwic 6222: sub GetFileTimestamp {
6223: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 6224: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6225: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 6226: my $subdir=$studentName.'__';
6227: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6228: my $proname="$studentDomain/$subdir/$studentName";
6229: $proname .= '/'.$filename;
1.375 matthew 6230: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
6231: $studentName, $root);
1.275 stredwic 6232: my @stats = split('&', $fileStat);
6233: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6234: # @stats contains first the filename, then the stat output
6235: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6236: } else {
6237: return -1;
1.253 stredwic 6238: }
1.26 www 6239: }
6240:
1.712 albertel 6241: sub stat_file {
6242: my ($uri) = @_;
1.787 albertel 6243: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6244:
1.712 albertel 6245: my ($udom,$uname,$file,$dir);
6246: if ($uri =~ m-^/(uploaded|editupload)/-) {
6247: ($udom,$uname,$file) =
1.811 albertel 6248: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6249: $file = 'userfiles/'.$file;
1.740 www 6250: $dir = &propath($udom,$uname);
1.712 albertel 6251: }
6252: if ($uri =~ m-^/res/-) {
6253: ($udom,$uname) =
1.807 albertel 6254: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6255: $file = $uri;
6256: }
6257:
6258: if (!$udom || !$uname || !$file) {
6259: # unable to handle the uri
6260: return ();
6261: }
6262:
6263: my ($result) = &dirlist($file,$udom,$uname,$dir);
6264: my @stats = split('&', $result);
1.721 banghart 6265:
1.712 albertel 6266: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6267: shift(@stats); #filename is first
6268: return @stats;
6269: }
6270: return ();
6271: }
6272:
1.26 www 6273: # -------------------------------------------------------- Value of a Condition
6274:
1.713 albertel 6275: # gets the value of a specific preevaluated condition
6276: # stored in the string $env{user.state.<cid>}
6277: # or looks up a condition reference in the bighash and if if hasn't
6278: # already been evaluated recurses into docondval to get the value of
6279: # the condition, then memoizing it to
6280: # $env{user.state.<cid>.<condition>}
1.40 www 6281: sub directcondval {
6282: my $number=shift;
1.620 albertel 6283: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6284: &Apache::lonuserstate::evalstate();
6285: }
1.713 albertel 6286: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6287: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6288: } elsif ($number =~ /^_/) {
6289: my $sub_condition;
6290: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6291: &GDBM_READER(),0640)) {
6292: $sub_condition=$bighash{'conditions'.$number};
6293: untie(%bighash);
6294: }
6295: my $value = &docondval($sub_condition);
6296: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
6297: return $value;
6298: }
1.620 albertel 6299: if ($env{'user.state.'.$env{'request.course.id'}}) {
6300: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6301: } else {
6302: return 2;
6303: }
6304: }
6305:
1.713 albertel 6306: # get the collection of conditions for this resource
1.26 www 6307: sub condval {
6308: my $condidx=shift;
1.54 www 6309: my $allpathcond='';
1.713 albertel 6310: foreach my $cond (split(/\|/,$condidx)) {
6311: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6312: $allpathcond.=
6313: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6314: }
1.191 harris41 6315: }
1.54 www 6316: $allpathcond=~s/\|$//;
1.713 albertel 6317: return &docondval($allpathcond);
6318: }
6319:
6320: #evaluates an expression of conditions
6321: sub docondval {
6322: my ($allpathcond) = @_;
6323: my $result=0;
6324: if ($env{'request.course.id'}
6325: && defined($allpathcond)) {
6326: my $operand='|';
6327: my @stack;
6328: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6329: if ($chunk eq '(') {
6330: push @stack,($operand,$result);
6331: } elsif ($chunk eq ')') {
6332: my $before=pop @stack;
6333: if (pop @stack eq '&') {
6334: $result=$result>$before?$before:$result;
6335: } else {
6336: $result=$result>$before?$result:$before;
6337: }
6338: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6339: $operand=$chunk;
6340: } else {
6341: my $new=directcondval($chunk);
6342: if ($operand eq '&') {
6343: $result=$result>$new?$new:$result;
6344: } else {
6345: $result=$result>$new?$result:$new;
6346: }
6347: }
6348: }
1.26 www 6349: }
6350: return $result;
1.421 albertel 6351: }
6352:
6353: # ---------------------------------------------------- Devalidate courseresdata
6354:
6355: sub devalidatecourseresdata {
6356: my ($coursenum,$coursedomain)=@_;
6357: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6358: &devalidate_cache_new('courseres',$hashid);
1.28 www 6359: }
6360:
1.763 www 6361:
1.200 www 6362: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6363: #
6364: # Parameters:
6365: # $coursenum - Number of the course.
6366: # $coursedomain - Domain at which the course was created.
6367: # Returns:
6368: # A hash of the course parameters along (I think) with timestamps
6369: # and version info.
1.877 foxr 6370:
1.624 albertel 6371: sub get_courseresdata {
6372: my ($coursenum,$coursedomain)=@_;
1.200 www 6373: my $coursehom=&homeserver($coursenum,$coursedomain);
6374: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6375: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6376: my %dumpreply;
1.417 albertel 6377: unless (defined($cached)) {
1.624 albertel 6378: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6379: $result=\%dumpreply;
1.251 albertel 6380: my ($tmp) = keys(%dumpreply);
6381: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6382: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6383: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6384: return $tmp;
1.416 albertel 6385: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6386: $result=undef;
1.599 albertel 6387: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6388: }
6389: }
1.624 albertel 6390: return $result;
6391: }
6392:
1.633 albertel 6393: sub devalidateuserresdata {
6394: my ($uname,$udom)=@_;
6395: my $hashid="$udom:$uname";
6396: &devalidate_cache_new('userres',$hashid);
6397: }
6398:
1.624 albertel 6399: sub get_userresdata {
6400: my ($uname,$udom)=@_;
6401: #most student don\'t have any data set, check if there is some data
6402: if (&EXT_cache_status($udom,$uname)) { return undef; }
6403:
6404: my $hashid="$udom:$uname";
6405: my ($result,$cached)=&is_cached_new('userres',$hashid);
6406: if (!defined($cached)) {
6407: my %resourcedata=&dump('resourcedata',$udom,$uname);
6408: $result=\%resourcedata;
6409: &do_cache_new('userres',$hashid,$result,600);
6410: }
6411: my ($tmp)=keys(%$result);
6412: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6413: return $result;
6414: }
6415: #error 2 occurs when the .db doesn't exist
6416: if ($tmp!~/error: 2 /) {
1.672 albertel 6417: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6418: " Trying to get resource data for ".
6419: $uname." at ".$udom.": ".
6420: $tmp."</font>");
6421: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6422: #&EXT_cache_set($udom,$uname);
6423: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6424: undef($tmp); # not really an error so don't send it back
1.624 albertel 6425: }
6426: return $tmp;
6427: }
1.879 foxr 6428: #----------------------------------------------- resdata - return resource data
6429: # Purpose:
6430: # Return resource data for either users or for a course.
6431: # Parameters:
6432: # $name - Course/user name.
6433: # $domain - Name of the domain the user/course is registered on.
6434: # $type - Type of thing $name is (must be 'course' or 'user'
6435: # @which - Array of names of resources desired.
6436: # Returns:
6437: # The value of the first reasource in @which that is found in the
6438: # resource hash.
6439: # Exceptional Conditions:
6440: # If the $type passed in is not valid (not the string 'course' or
6441: # 'user', an undefined reference is returned.
6442: # If none of the resources are found, an undef is returned
1.624 albertel 6443: sub resdata {
6444: my ($name,$domain,$type,@which)=@_;
6445: my $result;
6446: if ($type eq 'course') {
6447: $result=&get_courseresdata($name,$domain);
6448: } elsif ($type eq 'user') {
6449: $result=&get_userresdata($name,$domain);
6450: }
6451: if (!ref($result)) { return $result; }
1.251 albertel 6452: foreach my $item (@which) {
1.927 albertel 6453: if (defined($result->{$item->[0]})) {
6454: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6455: }
1.250 albertel 6456: }
1.291 albertel 6457: return undef;
1.200 www 6458: }
6459:
1.379 matthew 6460: #
6461: # EXT resource caching routines
6462: #
6463:
6464: sub clear_EXT_cache_status {
1.383 albertel 6465: &delenv('cache.EXT.');
1.379 matthew 6466: }
6467:
6468: sub EXT_cache_status {
6469: my ($target_domain,$target_user) = @_;
1.383 albertel 6470: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6471: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6472: # We know already the user has no data
6473: return 1;
6474: } else {
6475: return 0;
6476: }
6477: }
6478:
6479: sub EXT_cache_set {
6480: my ($target_domain,$target_user) = @_;
1.383 albertel 6481: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 6482: #&appenv($cachename => time);
1.379 matthew 6483: }
6484:
1.28 www 6485: # --------------------------------------------------------- Value of a Variable
1.58 www 6486: sub EXT {
1.715 albertel 6487:
1.395 albertel 6488: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6489: unless ($varname) { return ''; }
1.218 albertel 6490: #get real user name/domain, courseid and symb
6491: my $courseid;
1.359 albertel 6492: my $publicuser;
1.427 www 6493: if ($symbparm) {
6494: $symbparm=&get_symb_from_alias($symbparm);
6495: }
1.218 albertel 6496: if (!($uname && $udom)) {
1.790 albertel 6497: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6498: if (!$symbparm) { $symbparm=$cursymb; }
6499: } else {
1.620 albertel 6500: $courseid=$env{'request.course.id'};
1.218 albertel 6501: }
1.48 www 6502: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6503: my $rest;
1.320 albertel 6504: if (defined($therest[0])) {
1.48 www 6505: $rest=join('.',@therest);
6506: } else {
6507: $rest='';
6508: }
1.320 albertel 6509:
1.57 www 6510: my $qualifierrest=$qualifier;
6511: if ($rest) { $qualifierrest.='.'.$rest; }
6512: my $spacequalifierrest=$space;
6513: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6514: if ($realm eq 'user') {
1.48 www 6515: # --------------------------------------------------------------- user.resource
6516: if ($space eq 'resource') {
1.651 albertel 6517: if ( (defined($Apache::lonhomework::parsing_a_problem)
6518: || defined($Apache::lonhomework::parsing_a_task))
6519: &&
1.744 albertel 6520: ($symbparm eq &symbread()) ) {
6521: # if we are in the middle of processing the resource the
6522: # get the value we are planning on committing
6523: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6524: return $Apache::lonhomework::results{$qualifierrest};
6525: } else {
6526: return $Apache::lonhomework::history{$qualifierrest};
6527: }
1.335 albertel 6528: } else {
1.359 albertel 6529: my %restored;
1.620 albertel 6530: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6531: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6532: } else {
6533: %restored=&restore($symbparm,$courseid,$udom,$uname);
6534: }
1.335 albertel 6535: return $restored{$qualifierrest};
6536: }
1.48 www 6537: # ----------------------------------------------------------------- user.access
6538: } elsif ($space eq 'access') {
1.218 albertel 6539: # FIXME - not supporting calls for a specific user
1.48 www 6540: return &allowed($qualifier,$rest);
6541: # ------------------------------------------ user.preferences, user.environment
6542: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6543: if (($uname eq $env{'user.name'}) &&
6544: ($udom eq $env{'user.domain'})) {
6545: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6546: } else {
1.359 albertel 6547: my %returnhash;
6548: if (!$publicuser) {
6549: %returnhash=&userenvironment($udom,$uname,
6550: $qualifierrest);
6551: }
1.218 albertel 6552: return $returnhash{$qualifierrest};
6553: }
1.48 www 6554: # ----------------------------------------------------------------- user.course
6555: } elsif ($space eq 'course') {
1.218 albertel 6556: # FIXME - not supporting calls for a specific user
1.620 albertel 6557: return $env{join('.',('request.course',$qualifier))};
1.48 www 6558: # ------------------------------------------------------------------- user.role
6559: } elsif ($space eq 'role') {
1.218 albertel 6560: # FIXME - not supporting calls for a specific user
1.620 albertel 6561: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6562: if ($qualifier eq 'value') {
6563: return $role;
6564: } elsif ($qualifier eq 'extent') {
6565: return $where;
6566: }
6567: # ----------------------------------------------------------------- user.domain
6568: } elsif ($space eq 'domain') {
1.218 albertel 6569: return $udom;
1.48 www 6570: # ------------------------------------------------------------------- user.name
6571: } elsif ($space eq 'name') {
1.218 albertel 6572: return $uname;
1.48 www 6573: # ---------------------------------------------------- Any other user namespace
1.29 www 6574: } else {
1.359 albertel 6575: my %reply;
6576: if (!$publicuser) {
6577: %reply=&get($space,[$qualifierrest],$udom,$uname);
6578: }
6579: return $reply{$qualifierrest};
1.48 www 6580: }
1.236 www 6581: } elsif ($realm eq 'query') {
6582: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6583: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6584: [$spacequalifierrest]);
1.620 albertel 6585: return $env{'form.'.$spacequalifierrest};
1.236 www 6586: } elsif ($realm eq 'request') {
1.48 www 6587: # ------------------------------------------------------------- request.browser
6588: if ($space eq 'browser') {
1.430 www 6589: if ($qualifier eq 'textremote') {
1.676 albertel 6590: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6591: return 1;
6592: } else {
6593: return 0;
6594: }
6595: } else {
1.620 albertel 6596: return $env{'browser.'.$qualifier};
1.430 www 6597: }
1.57 www 6598: # ------------------------------------------------------------ request.filename
6599: } else {
1.620 albertel 6600: return $env{'request.'.$spacequalifierrest};
1.29 www 6601: }
1.28 www 6602: } elsif ($realm eq 'course') {
1.48 www 6603: # ---------------------------------------------------------- course.description
1.620 albertel 6604: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6605: } elsif ($realm eq 'resource') {
1.165 www 6606:
1.620 albertel 6607: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6608: if (!$symbparm) { $symbparm=&symbread(); }
6609: }
1.693 albertel 6610:
6611: if ($space eq 'title') {
6612: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6613: return &gettitle($symbparm);
6614: }
6615:
6616: if ($space eq 'map') {
6617: my ($map) = &decode_symb($symbparm);
6618: return &symbread($map);
6619: }
1.905 albertel 6620: if ($space eq 'filename') {
6621: if ($symbparm) {
6622: return &clutter((&decode_symb($symbparm))[2]);
6623: }
6624: return &hreflocation('',$env{'request.filename'});
6625: }
1.693 albertel 6626:
6627: my ($section, $group, @groups);
1.593 albertel 6628: my ($courselevelm,$courselevel);
1.539 albertel 6629: if ($symbparm && defined($courseid) &&
1.620 albertel 6630: $courseid eq $env{'request.course.id'}) {
1.165 www 6631:
1.218 albertel 6632: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6633:
1.60 www 6634: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6635: my $symbp=$symbparm;
1.735 albertel 6636: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6637:
6638: my $symbparm=$symbp.'.'.$spacequalifierrest;
6639: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6640:
1.620 albertel 6641: if (($env{'user.name'} eq $uname) &&
6642: ($env{'user.domain'} eq $udom)) {
6643: $section=$env{'request.course.sec'};
1.733 raeburn 6644: @groups = split(/:/,$env{'request.course.groups'});
6645: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6646: } else {
1.539 albertel 6647: if (! defined($usection)) {
1.551 albertel 6648: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6649: } else {
6650: $section = $usection;
6651: }
1.733 raeburn 6652: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6653: }
6654:
6655: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6656: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6657: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6658:
1.593 albertel 6659: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6660: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6661: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6662:
1.60 www 6663: # ----------------------------------------------------------- first, check user
1.624 albertel 6664:
6665: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 6666: ([$courselevelr,'resource'],
6667: [$courselevelm,'map' ],
6668: [$courselevel, 'course' ]));
1.931 albertel 6669: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 6670:
1.594 albertel 6671: # ------------------------------------------------ second, check some of course
1.684 raeburn 6672: my $coursereply;
1.691 raeburn 6673: if (@groups > 0) {
6674: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6675: $mapparm,$spacequalifierrest);
1.927 albertel 6676: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 6677: }
1.96 www 6678:
1.684 raeburn 6679: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 6680: $env{'course.'.$courseid.'.domain'},
6681: 'course',
6682: ([$seclevelr, 'resource'],
6683: [$seclevelm, 'map' ],
6684: [$seclevel, 'course' ],
6685: [$courselevelr,'resource']));
6686: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 6687:
1.60 www 6688: # ------------------------------------------------------ third, check map parms
1.218 albertel 6689: my %parmhash=();
6690: my $thisparm='';
6691: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6692: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6693: &GDBM_READER(),0640)) {
1.218 albertel 6694: $thisparm=$parmhash{$symbparm};
6695: untie(%parmhash);
6696: }
1.927 albertel 6697: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 6698: }
1.594 albertel 6699: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6700:
1.218 albertel 6701: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6702: my $filename;
6703: if (!$symbparm) { $symbparm=&symbread(); }
6704: if ($symbparm) {
1.409 www 6705: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6706: } else {
1.620 albertel 6707: $filename=$env{'request.filename'};
1.282 albertel 6708: }
6709: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 6710: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 6711: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 6712: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 6713:
1.927 albertel 6714: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 6715: if ($symbparm && defined($courseid) &&
1.620 albertel 6716: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6717: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6718: $env{'course.'.$courseid.'.domain'},
6719: 'course',
1.927 albertel 6720: ([$courselevelm,'map' ],
6721: [$courselevel, 'course']));
6722: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 6723: }
1.145 www 6724: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6725: unless ($space eq '0') {
1.336 albertel 6726: my @parts=split(/_/,$space);
6727: my $id=pop(@parts);
6728: my $part=join('_',@parts);
6729: if ($part eq '') { $part='0'; }
1.927 albertel 6730: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6731: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 6732: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 6733: }
1.395 albertel 6734: if ($recurse) { return undef; }
6735: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 6736: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 6737: # ---------------------------------------------------- Any other user namespace
6738: } elsif ($realm eq 'environment') {
6739: # ----------------------------------------------------------------- environment
1.620 albertel 6740: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6741: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6742: } else {
1.770 albertel 6743: if ($uname eq 'anonymous' && $udom eq '') {
6744: return '';
6745: }
1.219 albertel 6746: my %returnhash=&userenvironment($udom,$uname,
6747: $spacequalifierrest);
6748: return $returnhash{$spacequalifierrest};
6749: }
1.28 www 6750: } elsif ($realm eq 'system') {
1.48 www 6751: # ----------------------------------------------------------------- system.time
6752: if ($space eq 'time') {
6753: return time;
6754: }
1.696 albertel 6755: } elsif ($realm eq 'server') {
6756: # ----------------------------------------------------------------- system.time
6757: if ($space eq 'name') {
6758: return $ENV{'SERVER_NAME'};
6759: }
1.28 www 6760: }
1.48 www 6761: return '';
1.61 www 6762: }
6763:
1.927 albertel 6764: sub get_reply {
6765: my ($reply_value) = @_;
1.940 raeburn 6766: if (ref($reply_value) eq 'ARRAY') {
6767: if (wantarray) {
6768: return @$reply_value;
6769: }
6770: return $reply_value->[0];
6771: } else {
6772: return $reply_value;
1.927 albertel 6773: }
6774: }
6775:
1.691 raeburn 6776: sub check_group_parms {
6777: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6778: my @groupitems = ();
6779: my $resultitem;
1.927 albertel 6780: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 6781: foreach my $group (@{$groups}) {
6782: foreach my $level (@levels) {
1.927 albertel 6783: my $item = $courseid.'.['.$group.'].'.$level->[0];
6784: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 6785: }
6786: }
6787: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6788: $env{'course.'.$courseid.'.domain'},
6789: 'course',@groupitems);
6790: return $coursereply;
6791: }
6792:
6793: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6794: my ($courseid,@groups) = @_;
6795: @groups = sort(@groups);
1.691 raeburn 6796: return @groups;
6797: }
6798:
1.395 albertel 6799: sub packages_tab_default {
6800: my ($uri,$varname)=@_;
6801: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6802:
6803: my (@extension,@specifics,$do_default);
6804: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6805: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6806: if ($pack_type eq 'default') {
6807: $do_default=1;
6808: } elsif ($pack_type eq 'extension') {
6809: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 6810: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 6811: # only look at packages defaults for packages that this id is
1.738 albertel 6812: push(@specifics,[$package,$pack_type,$pack_part]);
6813: }
6814: }
6815: # first look for a package that matches the requested part id
6816: foreach my $package (@specifics) {
6817: my (undef,$pack_type,$pack_part)=@{$package};
6818: next if ($pack_part ne $part);
6819: if (defined($packagetab{"$pack_type&$name&default"})) {
6820: return $packagetab{"$pack_type&$name&default"};
6821: }
6822: }
6823: # look for any possible matching non extension_ package
6824: foreach my $package (@specifics) {
6825: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6826: if (defined($packagetab{"$pack_type&$name&default"})) {
6827: return $packagetab{"$pack_type&$name&default"};
6828: }
1.585 albertel 6829: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6830: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6831: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6832: }
6833: }
1.738 albertel 6834: # look for any posible extension_ match
6835: foreach my $package (@extension) {
6836: my ($package,$pack_type)=@{$package};
6837: if (defined($packagetab{"$pack_type&$name&default"})) {
6838: return $packagetab{"$pack_type&$name&default"};
6839: }
6840: if (defined($packagetab{$package."&$name&default"})) {
6841: return $packagetab{$package."&$name&default"};
6842: }
6843: }
6844: # look for a global default setting
6845: if ($do_default && defined($packagetab{"default&$name&default"})) {
6846: return $packagetab{"default&$name&default"};
6847: }
1.395 albertel 6848: return undef;
6849: }
6850:
1.334 albertel 6851: sub add_prefix_and_part {
6852: my ($prefix,$part)=@_;
6853: my $keyroot;
6854: if (defined($prefix) && $prefix !~ /^__/) {
6855: # prefix that has a part already
6856: $keyroot=$prefix;
6857: } elsif (defined($prefix)) {
6858: # prefix that is missing a part
6859: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6860: } else {
6861: # no prefix at all
6862: if (defined($part)) { $keyroot='_'.$part; }
6863: }
6864: return $keyroot;
6865: }
6866:
1.71 www 6867: # ---------------------------------------------------------------- Get metadata
6868:
1.599 albertel 6869: my %metaentry;
1.71 www 6870: sub metadata {
1.176 www 6871: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6872: $uri=&declutter($uri);
1.288 albertel 6873: # if it is a non metadata possible uri return quickly
1.529 albertel 6874: if (($uri eq '') ||
6875: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6876: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 6877: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
6878: return undef;
6879: }
6880: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
6881: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 6882: return undef;
1.288 albertel 6883: }
1.73 www 6884: my $filename=$uri;
6885: $uri=~s/\.meta$//;
1.172 www 6886: #
6887: # Is the metadata already cached?
1.177 www 6888: # Look at timestamp of caching
1.172 www 6889: # Everything is cached by the main uri, libraries are never directly cached
6890: #
1.428 albertel 6891: if (!defined($liburi)) {
1.599 albertel 6892: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6893: if (defined($cached)) { return $result->{':'.$what}; }
6894: }
6895: {
1.172 www 6896: #
6897: # Is this a recursive call for a library?
6898: #
1.599 albertel 6899: # if (! exists($metacache{$uri})) {
6900: # $metacache{$uri}={};
6901: # }
1.924 albertel 6902: my $cachetime = 60*60;
1.171 www 6903: if ($liburi) {
6904: $liburi=&declutter($liburi);
6905: $filename=$liburi;
1.401 bowersj2 6906: } else {
1.599 albertel 6907: &devalidate_cache_new('meta',$uri);
6908: undef(%metaentry);
1.401 bowersj2 6909: }
1.140 www 6910: my %metathesekeys=();
1.73 www 6911: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6912: my $metastring;
1.924 albertel 6913: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 6914: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 6915: $metastring =
1.929 albertel 6916: &Apache::lonnet::ssi_body($which,
1.924 albertel 6917: ('grade_target' => 'meta'));
6918: $cachetime = 1; # only want this cached in the child not long term
6919: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 6920: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6921: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6922: $metastring=&getfile($file);
1.489 albertel 6923: }
1.208 albertel 6924: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6925: my $token;
1.140 www 6926: undef %metathesekeys;
1.71 www 6927: while ($token=$parser->get_token) {
1.339 albertel 6928: if ($token->[0] eq 'S') {
6929: if (defined($token->[2]->{'package'})) {
1.172 www 6930: #
6931: # This is a package - get package info
6932: #
1.339 albertel 6933: my $package=$token->[2]->{'package'};
6934: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6935: if (defined($token->[2]->{'id'})) {
6936: $keyroot.='_'.$token->[2]->{'id'};
6937: }
1.599 albertel 6938: if ($metaentry{':packages'}) {
6939: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6940: } else {
1.599 albertel 6941: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6942: }
1.736 albertel 6943: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6944: my $part=$keyroot;
6945: $part=~s/^\_//;
1.736 albertel 6946: if ($pack_entry=~/^\Q$package\E\&/ ||
6947: $pack_entry=~/^\Q$package\E_0\&/) {
6948: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6949: # ignore package.tab specified default values
6950: # here &package_tab_default() will fetch those
6951: if ($subp eq 'default') { next; }
1.736 albertel 6952: my $value=$packagetab{$pack_entry};
1.432 albertel 6953: my $unikey;
6954: if ($pack =~ /_0$/) {
6955: $unikey='parameter_0_'.$name;
6956: $part=0;
6957: } else {
6958: $unikey='parameter'.$keyroot.'_'.$name;
6959: }
1.339 albertel 6960: if ($subp eq 'display') {
6961: $value.=' [Part: '.$part.']';
6962: }
1.599 albertel 6963: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6964: $metathesekeys{$unikey}=1;
1.599 albertel 6965: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6966: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6967: }
1.599 albertel 6968: if (defined($metaentry{':'.$unikey.'.default'})) {
6969: $metaentry{':'.$unikey}=
6970: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6971: }
1.339 albertel 6972: }
6973: }
6974: } else {
1.172 www 6975: #
6976: # This is not a package - some other kind of start tag
1.339 albertel 6977: #
6978: my $entry=$token->[1];
6979: my $unikey;
6980: if ($entry eq 'import') {
6981: $unikey='';
6982: } else {
6983: $unikey=$entry;
6984: }
6985: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6986:
6987: if (defined($token->[2]->{'id'})) {
6988: $unikey.='_'.$token->[2]->{'id'};
6989: }
1.175 www 6990:
1.339 albertel 6991: if ($entry eq 'import') {
1.175 www 6992: #
6993: # Importing a library here
1.339 albertel 6994: #
6995: if ($depthcount<20) {
6996: my $location=$parser->get_text('/import');
6997: my $dir=$filename;
6998: $dir=~s|[^/]*$||;
6999: $location=&filelocation($dir,$location);
1.736 albertel 7000: my $metadata =
7001: &metadata($uri,'keys', $location,$unikey,
7002: $depthcount+1);
7003: foreach my $meta (split(',',$metadata)) {
7004: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7005: $metathesekeys{$meta}=1;
1.339 albertel 7006: }
7007: }
7008: } else {
7009:
7010: if (defined($token->[2]->{'name'})) {
7011: $unikey.='_'.$token->[2]->{'name'};
7012: }
7013: $metathesekeys{$unikey}=1;
1.736 albertel 7014: foreach my $param (@{$token->[3]}) {
7015: $metaentry{':'.$unikey.'.'.$param} =
7016: $token->[2]->{$param};
1.339 albertel 7017: }
7018: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7019: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7020: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7021: # only ws inside the tag, and not in default, so use default
7022: # as value
1.599 albertel 7023: $metaentry{':'.$unikey}=$default;
1.908 albertel 7024: } elsif ( $internaltext =~ /\S/ ) {
7025: # something interesting inside the tag
7026: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7027: } else {
1.908 albertel 7028: # no interesting values, don't set a default
1.339 albertel 7029: }
1.172 www 7030: # end of not-a-package not-a-library import
1.339 albertel 7031: }
1.172 www 7032: # end of not-a-package start tag
1.339 albertel 7033: }
1.172 www 7034: # the next is the end of "start tag"
1.339 albertel 7035: }
7036: }
1.483 albertel 7037: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7038: $extension = lc($extension);
7039: if ($extension eq 'htm') { $extension='html'; }
7040:
1.737 albertel 7041: foreach my $key (keys(%packagetab)) {
1.483 albertel 7042: #no specific packages #how's our extension
7043: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7044: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7045: \%metathesekeys);
7046: }
1.883 albertel 7047:
7048: if (!exists($metaentry{':packages'})
7049: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7050: foreach my $key (keys(%packagetab)) {
1.483 albertel 7051: #no specific packages well let's get default then
7052: if ($key!~/^default&/) { next; }
1.488 albertel 7053: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7054: \%metathesekeys);
7055: }
7056: }
1.338 www 7057: # are there custom rights to evaluate
1.599 albertel 7058: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7059:
1.338 www 7060: #
7061: # Importing a rights file here
1.339 albertel 7062: #
7063: unless ($depthcount) {
1.599 albertel 7064: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7065: my $dir=$filename;
7066: $dir=~s|[^/]*$||;
7067: $location=&filelocation($dir,$location);
1.736 albertel 7068: my $rights_metadata =
7069: &metadata($uri,'keys',$location,'_rights',
7070: $depthcount+1);
7071: foreach my $rights (split(',',$rights_metadata)) {
7072: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7073: $metathesekeys{$rights}=1;
1.339 albertel 7074: }
7075: }
7076: }
1.737 albertel 7077: # uniqifiy package listing
7078: my %seen;
7079: my @uniq_packages =
7080: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7081: $metaentry{':packages'} = join(',',@uniq_packages);
7082:
7083: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7084: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7085: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7086: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7087: # this is the end of "was not already recently cached
1.71 www 7088: }
1.599 albertel 7089: return $metaentry{':'.$what};
1.261 albertel 7090: }
7091:
1.488 albertel 7092: sub metadata_create_package_def {
1.483 albertel 7093: my ($uri,$key,$package,$metathesekeys)=@_;
7094: my ($pack,$name,$subp)=split(/\&/,$key);
7095: if ($subp eq 'default') { next; }
7096:
1.599 albertel 7097: if (defined($metaentry{':packages'})) {
7098: $metaentry{':packages'}.=','.$package;
1.483 albertel 7099: } else {
1.599 albertel 7100: $metaentry{':packages'}=$package;
1.483 albertel 7101: }
7102: my $value=$packagetab{$key};
7103: my $unikey;
7104: $unikey='parameter_0_'.$name;
1.599 albertel 7105: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7106: $$metathesekeys{$unikey}=1;
1.599 albertel 7107: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7108: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7109: }
1.599 albertel 7110: if (defined($metaentry{':'.$unikey.'.default'})) {
7111: $metaentry{':'.$unikey}=
7112: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7113: }
7114: }
7115:
1.261 albertel 7116: sub metadata_generate_part0 {
7117: my ($metadata,$metacache,$uri) = @_;
7118: my %allnames;
1.737 albertel 7119: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7120: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7121: my $part=$$metacache{':'.$metakey.'.part'};
7122: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7123: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7124: $allnames{$name}=$part;
7125: }
7126: }
7127: }
7128: foreach my $name (keys(%allnames)) {
7129: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7130: my $key=":parameter_0_$name";
1.261 albertel 7131: $$metacache{"$key.part"}='0';
7132: $$metacache{"$key.name"}=$name;
1.428 albertel 7133: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7134: $allnames{$name}.'_'.$name.
7135: '.type'};
1.428 albertel 7136: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7137: '.display'};
1.644 www 7138: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7139: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7140: $$metacache{"$key.display"}=$olddis;
7141: }
1.71 www 7142: }
7143:
1.764 albertel 7144: # ------------------------------------------------------ Devalidate title cache
7145:
7146: sub devalidate_title_cache {
7147: my ($url)=@_;
7148: if (!$env{'request.course.id'}) { return; }
7149: my $symb=&symbread($url);
7150: if (!$symb) { return; }
7151: my $key=$env{'request.course.id'}."\0".$symb;
7152: &devalidate_cache_new('title',$key);
7153: }
7154:
1.301 www 7155: # ------------------------------------------------- Get the title of a resource
7156:
7157: sub gettitle {
7158: my $urlsymb=shift;
7159: my $symb=&symbread($urlsymb);
1.534 albertel 7160: if ($symb) {
1.620 albertel 7161: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7162: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7163: if (defined($cached)) {
7164: return $result;
7165: }
1.534 albertel 7166: my ($map,$resid,$url)=&decode_symb($symb);
7167: my $title='';
1.907 albertel 7168: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7169: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7170: } else {
7171: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7172: &GDBM_READER(),0640)) {
7173: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7174: $title=$bighash{'title_'.$mapid.'.'.$resid};
7175: untie(%bighash);
7176: }
1.534 albertel 7177: }
7178: $title=~s/\&colon\;/\:/gs;
7179: if ($title) {
1.599 albertel 7180: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7181: }
7182: $urlsymb=$url;
7183: }
7184: my $title=&metadata($urlsymb,'title');
7185: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7186: return $title;
1.301 www 7187: }
1.613 albertel 7188:
1.614 albertel 7189: sub get_slot {
7190: my ($which,$cnum,$cdom)=@_;
7191: if (!$cnum || !$cdom) {
1.790 albertel 7192: (undef,my $courseid)=&whichuser();
1.620 albertel 7193: $cdom=$env{'course.'.$courseid.'.domain'};
7194: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7195: }
1.703 albertel 7196: my $key=join("\0",'slots',$cdom,$cnum,$which);
7197: my %slotinfo;
7198: if (exists($remembered{$key})) {
7199: $slotinfo{$which} = $remembered{$key};
7200: } else {
7201: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7202: &Apache::lonhomework::showhash(%slotinfo);
7203: my ($tmp)=keys(%slotinfo);
7204: if ($tmp=~/^error:/) { return (); }
7205: $remembered{$key} = $slotinfo{$which};
7206: }
1.616 albertel 7207: if (ref($slotinfo{$which}) eq 'HASH') {
7208: return %{$slotinfo{$which}};
7209: }
7210: return $slotinfo{$which};
1.614 albertel 7211: }
1.31 www 7212: # ------------------------------------------------- Update symbolic store links
7213:
7214: sub symblist {
7215: my ($mapname,%newhash)=@_;
1.438 www 7216: $mapname=&deversion(&declutter($mapname));
1.31 www 7217: my %hash;
1.620 albertel 7218: if (($env{'request.course.fn'}) && (%newhash)) {
7219: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7220: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7221: foreach my $url (keys %newhash) {
7222: next if ($url eq 'last_known'
7223: && $env{'form.no_update_last_known'});
7224: $hash{declutter($url)}=&encode_symb($mapname,
7225: $newhash{$url}->[1],
7226: $newhash{$url}->[0]);
1.191 harris41 7227: }
1.31 www 7228: if (untie(%hash)) {
7229: return 'ok';
7230: }
7231: }
7232: }
7233: return 'error';
1.212 www 7234: }
7235:
7236: # --------------------------------------------------------------- Verify a symb
7237:
7238: sub symbverify {
1.510 www 7239: my ($symb,$thisurl)=@_;
7240: my $thisfn=$thisurl;
1.439 www 7241: $thisfn=&declutter($thisfn);
1.215 www 7242: # direct jump to resource in page or to a sequence - will construct own symbs
7243: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7244: # check URL part
1.409 www 7245: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7246:
1.431 www 7247: unless ($url eq $thisfn) { return 0; }
1.213 www 7248:
1.216 www 7249: $symb=&symbclean($symb);
1.510 www 7250: $thisurl=&deversion($thisurl);
1.439 www 7251: $thisfn=&deversion($thisfn);
1.213 www 7252:
7253: my %bighash;
7254: my $okay=0;
1.431 www 7255:
1.620 albertel 7256: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7257: &GDBM_READER(),0640)) {
1.510 www 7258: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7259: unless ($ids) {
1.510 www 7260: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7261: }
7262: if ($ids) {
7263: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7264: foreach my $id (split(/\,/,$ids)) {
7265: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7266: if (
7267: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7268: eq $symb) {
1.620 albertel 7269: if (($env{'request.role.adv'}) ||
1.800 albertel 7270: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7271: $okay=1;
7272: }
7273: }
1.216 www 7274: }
7275: }
1.213 www 7276: untie(%bighash);
7277: }
7278: return $okay;
1.31 www 7279: }
7280:
1.210 www 7281: # --------------------------------------------------------------- Clean-up symb
7282:
7283: sub symbclean {
7284: my $symb=shift;
1.568 albertel 7285: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7286: # remove version from map
7287: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7288:
1.210 www 7289: # remove version from URL
7290: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7291:
1.507 www 7292: # remove wrapper
7293:
1.510 www 7294: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7295: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7296: return $symb;
1.409 www 7297: }
7298:
7299: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7300:
7301: sub encode_symb {
7302: my ($map,$resid,$url)=@_;
7303: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7304: }
1.409 www 7305:
7306: sub decode_symb {
1.568 albertel 7307: my $symb=shift;
7308: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7309: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7310: return (&fixversion($map),$resid,&fixversion($url));
7311: }
7312:
7313: sub fixversion {
7314: my $fn=shift;
1.609 banghart 7315: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7316: my %bighash;
7317: my $uri=&clutter($fn);
1.620 albertel 7318: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7319: # is this cached?
1.599 albertel 7320: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7321: if (defined($cached)) { return $result; }
7322: # unfortunately not cached, or expired
1.620 albertel 7323: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7324: &GDBM_READER(),0640)) {
7325: if ($bighash{'version_'.$uri}) {
7326: my $version=$bighash{'version_'.$uri};
1.444 www 7327: unless (($version eq 'mostrecent') ||
7328: ($version==&getversion($uri))) {
1.440 www 7329: $uri=~s/\.(\w+)$/\.$version\.$1/;
7330: }
7331: }
7332: untie %bighash;
1.413 www 7333: }
1.599 albertel 7334: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7335: }
7336:
7337: sub deversion {
7338: my $url=shift;
7339: $url=~s/\.\d+\.(\w+)$/\.$1/;
7340: return $url;
1.210 www 7341: }
7342:
1.31 www 7343: # ------------------------------------------------------ Return symb list entry
7344:
7345: sub symbread {
1.249 www 7346: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7347: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7348: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7349: # no filename provided? try from environment
1.44 www 7350: unless ($thisfn) {
1.620 albertel 7351: if ($env{'request.symb'}) {
7352: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7353: }
1.620 albertel 7354: $thisfn=$env{'request.filename'};
1.44 www 7355: }
1.569 albertel 7356: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7357: # is that filename actually a symb? Verify, clean, and return
7358: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7359: if (&symbverify($thisfn,$1)) {
1.620 albertel 7360: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7361: }
1.242 www 7362: }
1.44 www 7363: $thisfn=declutter($thisfn);
1.31 www 7364: my %hash;
1.37 www 7365: my %bighash;
7366: my $syval='';
1.620 albertel 7367: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7368: my $targetfn = $thisfn;
1.609 banghart 7369: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7370: $targetfn = 'adm/wrapper/'.$thisfn;
7371: }
1.687 albertel 7372: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7373: $targetfn=$1;
7374: }
1.620 albertel 7375: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7376: &GDBM_READER(),0640)) {
1.481 raeburn 7377: $syval=$hash{$targetfn};
1.37 www 7378: untie(%hash);
7379: }
7380: # ---------------------------------------------------------- There was an entry
7381: if ($syval) {
1.601 albertel 7382: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7383: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 7384: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 7385: #return $env{$cache_str}='';
1.601 albertel 7386: #}
7387: #$syval.=$1;
7388: #}
1.37 www 7389: } else {
7390: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7391: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7392: &GDBM_READER(),0640)) {
1.37 www 7393: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7394: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7395: unless ($ids) {
7396: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7397: }
7398: unless ($ids) {
7399: # alias?
7400: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7401: }
1.37 www 7402: if ($ids) {
7403: # ------------------------------------------------------------------- Has ID(s)
7404: my @possibilities=split(/\,/,$ids);
1.39 www 7405: if ($#possibilities==0) {
7406: # ----------------------------------------------- There is only one possibility
1.37 www 7407: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7408: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7409: $resid,$thisfn);
1.249 www 7410: } elsif (!$donotrecurse) {
1.39 www 7411: # ------------------------------------------ There is more than one possibility
7412: my $realpossible=0;
1.800 albertel 7413: foreach my $id (@possibilities) {
7414: my $file=$bighash{'src_'.$id};
1.39 www 7415: if (&allowed('bre',$file)) {
1.800 albertel 7416: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7417: if ($bighash{'map_type_'.$mapid} ne 'page') {
7418: $realpossible++;
1.626 albertel 7419: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7420: $resid,$thisfn);
1.39 www 7421: }
7422: }
1.191 harris41 7423: }
1.39 www 7424: if ($realpossible!=1) { $syval=''; }
1.249 www 7425: } else {
7426: $syval='';
1.37 www 7427: }
7428: }
7429: untie(%bighash)
1.481 raeburn 7430: }
1.31 www 7431: }
1.62 www 7432: if ($syval) {
1.620 albertel 7433: return $env{$cache_str}=$syval;
1.62 www 7434: }
1.31 www 7435: }
1.44 www 7436: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 7437: return $env{$cache_str}='';
1.31 www 7438: }
7439:
7440: # ---------------------------------------------------------- Return random seed
7441:
1.32 www 7442: sub numval {
7443: my $txt=shift;
7444: $txt=~tr/A-J/0-9/;
7445: $txt=~tr/a-j/0-9/;
7446: $txt=~tr/K-T/0-9/;
7447: $txt=~tr/k-t/0-9/;
7448: $txt=~tr/U-Z/0-5/;
7449: $txt=~tr/u-z/0-5/;
7450: $txt=~s/\D//g;
1.564 albertel 7451: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7452: return int($txt);
1.368 albertel 7453: }
7454:
1.484 albertel 7455: sub numval2 {
7456: my $txt=shift;
7457: $txt=~tr/A-J/0-9/;
7458: $txt=~tr/a-j/0-9/;
7459: $txt=~tr/K-T/0-9/;
7460: $txt=~tr/k-t/0-9/;
7461: $txt=~tr/U-Z/0-5/;
7462: $txt=~tr/u-z/0-5/;
7463: $txt=~s/\D//g;
7464: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7465: my $total;
7466: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7467: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7468: return int($total);
7469: }
7470:
1.575 albertel 7471: sub numval3 {
7472: use integer;
7473: my $txt=shift;
7474: $txt=~tr/A-J/0-9/;
7475: $txt=~tr/a-j/0-9/;
7476: $txt=~tr/K-T/0-9/;
7477: $txt=~tr/k-t/0-9/;
7478: $txt=~tr/U-Z/0-5/;
7479: $txt=~tr/u-z/0-5/;
7480: $txt=~s/\D//g;
7481: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7482: my $total;
7483: foreach my $val (@txts) { $total+=$val; }
7484: if ($_64bit) { $total=(($total<<32)>>32); }
7485: return $total;
7486: }
7487:
1.675 albertel 7488: sub digest {
7489: my ($data)=@_;
7490: my $digest=&Digest::MD5::md5($data);
7491: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7492: my ($e,$f);
7493: {
7494: use integer;
7495: $e=($a+$b);
7496: $f=($c+$d);
7497: if ($_64bit) {
7498: $e=(($e<<32)>>32);
7499: $f=(($f<<32)>>32);
7500: }
7501: }
7502: if (wantarray) {
7503: return ($e,$f);
7504: } else {
7505: my $g;
7506: {
7507: use integer;
7508: $g=($e+$f);
7509: if ($_64bit) {
7510: $g=(($g<<32)>>32);
7511: }
7512: }
7513: return $g;
7514: }
7515: }
7516:
1.368 albertel 7517: sub latest_rnd_algorithm_id {
1.675 albertel 7518: return '64bit5';
1.366 albertel 7519: }
1.32 www 7520:
1.503 albertel 7521: sub get_rand_alg {
7522: my ($courseid)=@_;
1.790 albertel 7523: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7524: if ($courseid) {
1.620 albertel 7525: return $env{"course.$courseid.rndseed"};
1.503 albertel 7526: }
7527: return &latest_rnd_algorithm_id();
7528: }
7529:
1.562 albertel 7530: sub validCODE {
7531: my ($CODE)=@_;
7532: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7533: return 0;
7534: }
7535:
1.491 albertel 7536: sub getCODE {
1.620 albertel 7537: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7538: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7539: defined($Apache::lonhomework::parsing_a_task) ) &&
7540: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7541: return $Apache::lonhomework::history{'resource.CODE'};
7542: }
7543: return undef;
7544: }
7545:
1.31 www 7546: sub rndseed {
1.155 albertel 7547: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7548: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7549: if (!defined($symb)) {
1.366 albertel 7550: unless ($symb=$wsymb) { return time; }
7551: }
7552: if (!$courseid) { $courseid=$wcourseid; }
7553: if (!$domain) { $domain=$wdomain; }
7554: if (!$username) { $username=$wusername }
1.503 albertel 7555: my $which=&get_rand_alg();
1.803 albertel 7556:
1.491 albertel 7557: if (defined(&getCODE())) {
1.675 albertel 7558: if ($which eq '64bit5') {
7559: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7560: } elsif ($which eq '64bit4') {
1.575 albertel 7561: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7562: } else {
7563: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7564: }
1.675 albertel 7565: } elsif ($which eq '64bit5') {
7566: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7567: } elsif ($which eq '64bit4') {
7568: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7569: } elsif ($which eq '64bit3') {
7570: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7571: } elsif ($which eq '64bit2') {
7572: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7573: } elsif ($which eq '64bit') {
7574: return &rndseed_64bit($symb,$courseid,$domain,$username);
7575: }
7576: return &rndseed_32bit($symb,$courseid,$domain,$username);
7577: }
7578:
7579: sub rndseed_32bit {
7580: my ($symb,$courseid,$domain,$username)=@_;
7581: {
7582: use integer;
7583: my $symbchck=unpack("%32C*",$symb) << 27;
7584: my $symbseed=numval($symb) << 22;
7585: my $namechck=unpack("%32C*",$username) << 17;
7586: my $nameseed=numval($username) << 12;
7587: my $domainseed=unpack("%32C*",$domain) << 7;
7588: my $courseseed=unpack("%32C*",$courseid);
7589: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7590: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7591: #&logthis("rndseed :$num:$symb");
1.564 albertel 7592: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7593: return $num;
7594: }
7595: }
7596:
7597: sub rndseed_64bit {
7598: my ($symb,$courseid,$domain,$username)=@_;
7599: {
7600: use integer;
7601: my $symbchck=unpack("%32S*",$symb) << 21;
7602: my $symbseed=numval($symb) << 10;
7603: my $namechck=unpack("%32S*",$username);
7604:
7605: my $nameseed=numval($username) << 21;
7606: my $domainseed=unpack("%32S*",$domain) << 10;
7607: my $courseseed=unpack("%32S*",$courseid);
7608:
7609: my $num1=$symbchck+$symbseed+$namechck;
7610: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7611: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7612: #&logthis("rndseed :$num:$symb");
1.564 albertel 7613: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7614: return "$num1,$num2";
1.155 albertel 7615: }
1.366 albertel 7616: }
7617:
1.443 albertel 7618: sub rndseed_64bit2 {
7619: my ($symb,$courseid,$domain,$username)=@_;
7620: {
7621: use integer;
7622: # strings need to be an even # of cahracters long, it it is odd the
7623: # last characters gets thrown away
7624: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7625: my $symbseed=numval($symb) << 10;
7626: my $namechck=unpack("%32S*",$username.' ');
7627:
7628: my $nameseed=numval($username) << 21;
1.501 albertel 7629: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7630: my $courseseed=unpack("%32S*",$courseid.' ');
7631:
7632: my $num1=$symbchck+$symbseed+$namechck;
7633: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7634: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7635: #&logthis("rndseed :$num:$symb");
1.803 albertel 7636: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7637: return "$num1,$num2";
7638: }
7639: }
7640:
7641: sub rndseed_64bit3 {
7642: my ($symb,$courseid,$domain,$username)=@_;
7643: {
7644: use integer;
7645: # strings need to be an even # of cahracters long, it it is odd the
7646: # last characters gets thrown away
7647: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7648: my $symbseed=numval2($symb) << 10;
7649: my $namechck=unpack("%32S*",$username.' ');
7650:
7651: my $nameseed=numval2($username) << 21;
1.443 albertel 7652: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7653: my $courseseed=unpack("%32S*",$courseid.' ');
7654:
7655: my $num1=$symbchck+$symbseed+$namechck;
7656: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7657: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7658: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7659: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7660:
1.503 albertel 7661: return "$num1:$num2";
1.443 albertel 7662: }
7663: }
7664:
1.575 albertel 7665: sub rndseed_64bit4 {
7666: my ($symb,$courseid,$domain,$username)=@_;
7667: {
7668: use integer;
7669: # strings need to be an even # of cahracters long, it it is odd the
7670: # last characters gets thrown away
7671: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7672: my $symbseed=numval3($symb) << 10;
7673: my $namechck=unpack("%32S*",$username.' ');
7674:
7675: my $nameseed=numval3($username) << 21;
7676: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7677: my $courseseed=unpack("%32S*",$courseid.' ');
7678:
7679: my $num1=$symbchck+$symbseed+$namechck;
7680: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7681: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7682: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7683: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7684:
7685: return "$num1:$num2";
7686: }
7687: }
7688:
1.675 albertel 7689: sub rndseed_64bit5 {
7690: my ($symb,$courseid,$domain,$username)=@_;
7691: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7692: return "$num1:$num2";
7693: }
7694:
1.366 albertel 7695: sub rndseed_CODE_64bit {
7696: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7697: {
1.366 albertel 7698: use integer;
1.443 albertel 7699: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7700: my $symbseed=numval2($symb);
1.491 albertel 7701: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7702: my $CODEseed=numval(&getCODE());
1.443 albertel 7703: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7704: my $num1=$symbseed+$CODEchck;
7705: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7706: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7707: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7708: if ($_64bit) { $num1=(($num1<<32)>>32); }
7709: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7710: return "$num1:$num2";
1.366 albertel 7711: }
7712: }
7713:
1.575 albertel 7714: sub rndseed_CODE_64bit4 {
7715: my ($symb,$courseid,$domain,$username)=@_;
7716: {
7717: use integer;
7718: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7719: my $symbseed=numval3($symb);
7720: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7721: my $CODEseed=numval3(&getCODE());
7722: my $courseseed=unpack("%32S*",$courseid.' ');
7723: my $num1=$symbseed+$CODEchck;
7724: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7725: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7726: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7727: if ($_64bit) { $num1=(($num1<<32)>>32); }
7728: if ($_64bit) { $num2=(($num2<<32)>>32); }
7729: return "$num1:$num2";
7730: }
7731: }
7732:
1.675 albertel 7733: sub rndseed_CODE_64bit5 {
7734: my ($symb,$courseid,$domain,$username)=@_;
7735: my $code = &getCODE();
7736: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7737: return "$num1:$num2";
7738: }
7739:
1.366 albertel 7740: sub setup_random_from_rndseed {
7741: my ($rndseed)=@_;
1.503 albertel 7742: if ($rndseed =~/([,:])/) {
7743: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7744: &Math::Random::random_set_seed(abs($num1),abs($num2));
7745: } else {
7746: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7747: }
1.36 albertel 7748: }
7749:
1.474 albertel 7750: sub latest_receipt_algorithm_id {
1.835 albertel 7751: return 'receipt3';
1.474 albertel 7752: }
7753:
1.480 www 7754: sub recunique {
7755: my $fucourseid=shift;
7756: my $unique;
1.835 albertel 7757: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7758: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7759: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7760: } else {
7761: $unique=$perlvar{'lonReceipt'};
7762: }
7763: return unpack("%32C*",$unique);
7764: }
7765:
7766: sub recprefix {
7767: my $fucourseid=shift;
7768: my $prefix;
1.835 albertel 7769: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7770: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7771: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7772: } else {
7773: $prefix=$perlvar{'lonHostID'};
7774: }
7775: return unpack("%32C*",$prefix);
7776: }
7777:
1.76 www 7778: sub ireceipt {
1.474 albertel 7779: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7780:
7781: my $return =&recprefix($fucourseid).'-';
7782:
7783: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7784: $env{'request.state'} eq 'construct') {
7785: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7786: return $return;
7787: }
7788:
1.76 www 7789: my $cuname=unpack("%32C*",$funame);
7790: my $cudom=unpack("%32C*",$fudom);
7791: my $cucourseid=unpack("%32C*",$fucourseid);
7792: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7793: my $cunique=&recunique($fucourseid);
1.474 albertel 7794: my $cpart=unpack("%32S*",$part);
1.835 albertel 7795: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7796:
1.790 albertel 7797: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7798:
7799: $return.= ($cunique%$cuname+
7800: $cunique%$cudom+
7801: $cusymb%$cuname+
7802: $cusymb%$cudom+
7803: $cucourseid%$cuname+
7804: $cucourseid%$cudom+
7805: $cpart%$cuname+
7806: $cpart%$cudom);
7807: } else {
7808: $return.= ($cunique%$cuname+
7809: $cunique%$cudom+
7810: $cusymb%$cuname+
7811: $cusymb%$cudom+
7812: $cucourseid%$cuname+
7813: $cucourseid%$cudom);
7814: }
7815: return $return;
1.76 www 7816: }
7817:
7818: sub receipt {
1.474 albertel 7819: my ($part)=@_;
1.790 albertel 7820: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7821: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7822: }
1.260 ng 7823:
1.790 albertel 7824: sub whichuser {
7825: my ($passedsymb)=@_;
7826: my ($symb,$courseid,$domain,$name,$publicuser);
7827: if (defined($env{'form.grade_symb'})) {
7828: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7829: my $allowed=&allowed('vgr',$tmp_courseid);
7830: if (!$allowed &&
7831: exists($env{'request.course.sec'}) &&
7832: $env{'request.course.sec'} !~ /^\s*$/) {
7833: $allowed=&allowed('vgr',$tmp_courseid.
7834: '/'.$env{'request.course.sec'});
7835: }
7836: if ($allowed) {
7837: ($symb)=&get_env_multiple('form.grade_symb');
7838: $courseid=$tmp_courseid;
7839: ($domain)=&get_env_multiple('form.grade_domain');
7840: ($name)=&get_env_multiple('form.grade_username');
7841: return ($symb,$courseid,$domain,$name,$publicuser);
7842: }
7843: }
7844: if (!$passedsymb) {
7845: $symb=&symbread();
7846: } else {
7847: $symb=$passedsymb;
7848: }
7849: $courseid=$env{'request.course.id'};
7850: $domain=$env{'user.domain'};
7851: $name=$env{'user.name'};
7852: if ($name eq 'public' && $domain eq 'public') {
7853: if (!defined($env{'form.username'})) {
7854: $env{'form.username'}.=time.rand(10000000);
7855: }
7856: $name.=$env{'form.username'};
7857: }
7858: return ($symb,$courseid,$domain,$name,$publicuser);
7859:
7860: }
7861:
1.36 albertel 7862: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7863: # returns either the contents of the file or
7864: # -1 if the file doesn't exist
1.481 raeburn 7865: #
7866: # if the target is a file that was uploaded via DOCS,
7867: # a check will be made to see if a current copy exists on the local server,
7868: # if it does this will be served, otherwise a copy will be retrieved from
7869: # the home server for the course and stored in /home/httpd/html/userfiles on
7870: # the local server.
1.472 albertel 7871:
1.36 albertel 7872: sub getfile {
1.538 albertel 7873: my ($file) = @_;
1.609 banghart 7874: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7875: &repcopy($file);
7876: return &readfile($file);
7877: }
7878:
7879: sub repcopy_userfile {
7880: my ($file)=@_;
1.609 banghart 7881: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7882: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7883: my ($cdom,$cnum,$filename) =
1.811 albertel 7884: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7885: my $uri="/uploaded/$cdom/$cnum/$filename";
7886: if (-e "$file") {
1.828 www 7887: # we already have a local copy, check it out
1.538 albertel 7888: my @fileinfo = stat($file);
1.828 www 7889: my $rtncode;
7890: my $info;
1.538 albertel 7891: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7892: if ($lwpresp ne 'ok') {
1.828 www 7893: # there is no such file anymore, even though we had a local copy
1.482 albertel 7894: if ($rtncode eq '404') {
1.538 albertel 7895: unlink($file);
1.482 albertel 7896: }
7897: return -1;
7898: }
7899: if ($info < $fileinfo[9]) {
1.828 www 7900: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7901: return 'ok';
1.828 www 7902: } else {
7903: # the file is outdated, get rid of it
7904: unlink($file);
1.482 albertel 7905: }
1.828 www 7906: }
7907: # one way or the other, at this point, we don't have the file
7908: # construct the correct path for the file
7909: my @parts = ($cdom,$cnum);
7910: if ($filename =~ m|^(.+)/[^/]+$|) {
7911: push @parts, split(/\//,$1);
7912: }
7913: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7914: foreach my $part (@parts) {
7915: $path .= '/'.$part;
7916: if (!-e $path) {
7917: mkdir($path,0770);
1.482 albertel 7918: }
7919: }
1.828 www 7920: # now the path exists for sure
7921: # get a user agent
7922: my $ua=new LWP::UserAgent;
7923: my $transferfile=$file.'.in.transfer';
7924: # FIXME: this should flock
7925: if (-e $transferfile) { return 'ok'; }
7926: my $request;
7927: $uri=~s/^\///;
1.838 albertel 7928: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7929: my $response=$ua->request($request,$transferfile);
7930: # did it work?
7931: if ($response->is_error()) {
7932: unlink($transferfile);
7933: &logthis("Userfile repcopy failed for $uri");
7934: return -1;
7935: }
7936: # worked, rename the transfer file
7937: rename($transferfile,$file);
1.607 raeburn 7938: return 'ok';
1.481 raeburn 7939: }
7940:
1.517 albertel 7941: sub tokenwrapper {
7942: my $uri=shift;
1.552 albertel 7943: $uri=~s|^http\://([^/]+)||;
7944: $uri=~s|^/||;
1.620 albertel 7945: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7946: my $token=$1;
1.552 albertel 7947: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7948: if ($udom && $uname && $file) {
7949: $file=~s|(\?\.*)*$||;
1.620 albertel 7950: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7951: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7952: (($uri=~/\?/)?'&':'?').'token='.$token.
7953: '&tokenissued='.$perlvar{'lonHostID'};
7954: } else {
7955: return '/adm/notfound.html';
7956: }
7957: }
7958:
1.828 www 7959: # call with reqtype HEAD: get last modification time
7960: # call with reqtype GET: get the file contents
7961: # Do not call this with reqtype GET for large files! It loads everything into memory
7962: #
1.481 raeburn 7963: sub getuploaded {
7964: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7965: $uri=~s/^\///;
1.838 albertel 7966: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7967: my $ua=new LWP::UserAgent;
7968: my $request=new HTTP::Request($reqtype,$uri);
7969: my $response=$ua->request($request);
7970: $$rtncode = $response->code;
1.482 albertel 7971: if (! $response->is_success()) {
7972: return 'failed';
7973: }
7974: if ($reqtype eq 'HEAD') {
1.486 www 7975: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7976: } elsif ($reqtype eq 'GET') {
7977: $$info = $response->content;
1.472 albertel 7978: }
1.482 albertel 7979: return 'ok';
1.36 albertel 7980: }
7981:
1.481 raeburn 7982: sub readfile {
7983: my $file = shift;
7984: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7985: my $fh;
7986: open($fh,"<$file");
7987: my $a='';
1.800 albertel 7988: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7989: return $a;
7990: }
7991:
1.36 albertel 7992: sub filelocation {
1.590 banghart 7993: my ($dir,$file) = @_;
7994: my $location;
7995: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7996:
7997: if ($file =~ m-^/adm/-) {
7998: $file=~s-^/adm/wrapper/-/-;
7999: $file=~s-^/adm/coursedocs/showdoc/-/-;
8000: }
1.882 albertel 8001:
1.590 banghart 8002: if ($file=~m:^/~:) { # is a contruction space reference
8003: $location = $file;
8004: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8005: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8006: # is a correct contruction space reference
8007: $location = $file;
1.609 banghart 8008: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8009: my ($udom,$uname,$filename)=
1.811 albertel 8010: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8011: my $home=&homeserver($uname,$udom);
8012: my $is_me=0;
8013: my @ids=¤t_machine_ids();
8014: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8015: if ($is_me) {
1.740 www 8016: $location=&propath($udom,$uname).
1.590 banghart 8017: '/userfiles/'.$filename;
8018: } else {
8019: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8020: $udom.'/'.$uname.'/'.$filename;
8021: }
1.882 albertel 8022: } elsif ($file =~ m-^/adm/-) {
8023: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8024: } else {
8025: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8026: $file=~s:^/res/:/:;
8027: if ( !( $file =~ m:^/:) ) {
8028: $location = $dir. '/'.$file;
8029: } else {
8030: $location = '/home/httpd/html/res'.$file;
8031: }
1.59 albertel 8032: }
1.590 banghart 8033: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8034: while ($location=~m{/\.\./}) {
8035: if ($location =~ m{/[^/]+/\.\./}) {
8036: $location=~ s{/[^/]+/\.\./}{/}g;
8037: } else {
8038: $location=~ s{/\.\./}{/}g;
8039: }
8040: } #remove dir/..
1.590 banghart 8041: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8042: return $location;
1.46 www 8043: }
1.36 albertel 8044:
1.46 www 8045: sub hreflocation {
8046: my ($dir,$file)=@_;
1.460 albertel 8047: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 8048: $file=filelocation($dir,$file);
1.700 albertel 8049: } elsif ($file=~m-^/adm/-) {
8050: $file=~s-^/adm/wrapper/-/-;
8051: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8052: }
8053: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8054: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8055: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8056: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8057: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8058: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8059: -/uploaded/$1/$2/-x;
1.46 www 8060: }
1.913 albertel 8061: if ($file=~ m{^/userfiles/}) {
8062: $file =~ s{^/userfiles/}{/uploaded/};
8063: }
1.462 albertel 8064: return $file;
1.465 albertel 8065: }
8066:
8067: sub current_machine_domains {
1.853 albertel 8068: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8069: }
8070:
8071: sub machine_domains {
8072: my ($hostname) = @_;
1.465 albertel 8073: my @domains;
1.838 albertel 8074: my %hostname = &all_hostnames();
1.465 albertel 8075: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8076: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8077: if ($hostname eq $name) {
1.844 albertel 8078: push(@domains,&host_domain($id));
1.465 albertel 8079: }
8080: }
8081: return @domains;
8082: }
8083:
8084: sub current_machine_ids {
1.853 albertel 8085: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8086: }
8087:
8088: sub machine_ids {
8089: my ($hostname) = @_;
8090: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8091: my @ids;
1.888 albertel 8092: my %name_to_host = &all_names();
1.889 albertel 8093: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8094: return @{ $name_to_host{$hostname} };
8095: }
8096: return;
1.31 www 8097: }
8098:
1.824 raeburn 8099: sub additional_machine_domains {
8100: my @domains;
8101: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8102: while( my $line = <$fh>) {
8103: $line =~ s/\s//g;
8104: push(@domains,$line);
8105: }
8106: return @domains;
8107: }
8108:
8109: sub default_login_domain {
8110: my $domain = $perlvar{'lonDefDomain'};
8111: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8112: foreach my $posdom (¤t_machine_domains(),
8113: &additional_machine_domains()) {
8114: if (lc($posdom) eq lc($testdomain)) {
8115: $domain=$posdom;
8116: last;
8117: }
8118: }
8119: return $domain;
8120: }
8121:
1.31 www 8122: # ------------------------------------------------------------- Declutters URLs
8123:
8124: sub declutter {
8125: my $thisfn=shift;
1.569 albertel 8126: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8127: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8128: $thisfn=~s/^\///;
1.697 albertel 8129: $thisfn=~s|^adm/wrapper/||;
8130: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8131: $thisfn=~s/^res\///;
1.235 www 8132: $thisfn=~s/\?.+$//;
1.268 www 8133: return $thisfn;
8134: }
8135:
8136: # ------------------------------------------------------------- Clutter up URLs
8137:
8138: sub clutter {
8139: my $thisfn='/'.&declutter(shift);
1.887 albertel 8140: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8141: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8142: $thisfn='/res'.$thisfn;
8143: }
1.694 albertel 8144: if ($thisfn !~m|/adm|) {
1.695 albertel 8145: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8146: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8147: } else {
8148: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8149: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8150: if ($embstyle eq 'ssi'
8151: || ($embstyle eq 'hdn')
8152: || ($embstyle eq 'rat')
8153: || ($embstyle eq 'prv')
8154: || ($embstyle eq 'ign')) {
8155: #do nothing with these
8156: } elsif (($embstyle eq 'img')
1.695 albertel 8157: || ($embstyle eq 'emb')
8158: || ($embstyle eq 'wrp')) {
8159: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8160: } elsif ($embstyle eq 'unk'
8161: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8162: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8163: } else {
1.718 www 8164: # &logthis("Got a blank emb style");
1.695 albertel 8165: }
1.694 albertel 8166: }
8167: }
1.31 www 8168: return $thisfn;
1.12 www 8169: }
8170:
1.787 albertel 8171: sub clutter_with_no_wrapper {
8172: my $uri = &clutter(shift);
8173: if ($uri =~ m-^/adm/-) {
8174: $uri =~ s-^/adm/wrapper/-/-;
8175: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8176: }
8177: return $uri;
8178: }
8179:
1.557 albertel 8180: sub freeze_escape {
8181: my ($value)=@_;
8182: if (ref($value)) {
8183: $value=&nfreeze($value);
8184: return '__FROZEN__'.&escape($value);
8185: }
8186: return &escape($value);
8187: }
8188:
1.11 www 8189:
1.557 albertel 8190: sub thaw_unescape {
8191: my ($value)=@_;
8192: if ($value =~ /^__FROZEN__/) {
8193: substr($value,0,10,undef);
8194: $value=&unescape($value);
8195: return &thaw($value);
8196: }
8197: return &unescape($value);
8198: }
8199:
1.436 albertel 8200: sub correct_line_ends {
8201: my ($result)=@_;
8202: $$result =~s/\r\n/\n/mg;
8203: $$result =~s/\r/\n/mg;
1.415 albertel 8204: }
1.1 albertel 8205: # ================================================================ Main Program
8206:
1.184 www 8207: sub goodbye {
1.204 albertel 8208: &logthis("Starting Shut down");
1.443 albertel 8209: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8210: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8211: #converted
1.599 albertel 8212: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8213: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8214: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8215: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8216: #1.1 only
1.870 albertel 8217: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8218: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8219: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8220: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8221: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8222: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8223: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8224: &flushcourselogs();
8225: &logthis("Shutting down");
8226: }
8227:
1.852 albertel 8228: sub get_dns {
1.869 albertel 8229: my ($url,$func,$ignore_cache) = @_;
8230: if (!$ignore_cache) {
8231: my ($content,$cached)=
8232: &Apache::lonnet::is_cached_new('dns',$url);
8233: if ($cached) {
8234: &$func($content);
8235: return;
8236: }
8237: }
8238:
8239: my %alldns;
1.852 albertel 8240: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8241: foreach my $dns (<$config>) {
8242: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 8243: $alldns{$1} = 1;
8244: }
8245: while (%alldns) {
8246: my ($dns) = keys(%alldns);
8247: delete($alldns{$dns});
1.852 albertel 8248: my $ua=new LWP::UserAgent;
8249: my $request=new HTTP::Request('GET',"http://$dns$url");
8250: my $response=$ua->request($request);
8251: next if ($response->is_error());
8252: my @content = split("\n",$response->content);
1.869 albertel 8253: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8254: &$func(\@content);
1.869 albertel 8255: return;
1.852 albertel 8256: }
8257: close($config);
1.871 albertel 8258: my $which = (split('/',$url))[3];
8259: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8260: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8261: my @content = <$config>;
8262: &$func(\@content);
8263: return;
1.852 albertel 8264: }
1.327 albertel 8265: # ------------------------------------------------------------ Read domain file
8266: {
1.852 albertel 8267: my $loaded;
1.846 albertel 8268: my %domain;
8269:
1.852 albertel 8270: sub parse_domain_tab {
8271: my ($lines) = @_;
8272: foreach my $line (@$lines) {
8273: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8274:
1.846 albertel 8275: chomp($line);
1.852 albertel 8276: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8277: my %this_domain;
8278: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8279: 'lang_def', 'city', 'longi', 'lati',
8280: 'primary') {
8281: $this_domain{$field} = shift(@elements);
8282: }
8283: $domain{$name} = \%this_domain;
1.852 albertel 8284: }
8285: }
1.864 albertel 8286:
8287: sub reset_domain_info {
8288: undef($loaded);
8289: undef(%domain);
8290: }
8291:
1.852 albertel 8292: sub load_domain_tab {
1.869 albertel 8293: my ($ignore_cache) = @_;
8294: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8295: my $fh;
8296: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8297: my @lines = <$fh>;
8298: &parse_domain_tab(\@lines);
1.448 albertel 8299: }
1.852 albertel 8300: close($fh);
8301: $loaded = 1;
1.327 albertel 8302: }
1.846 albertel 8303:
8304: sub domain {
1.852 albertel 8305: &load_domain_tab() if (!$loaded);
8306:
1.846 albertel 8307: my ($name,$what) = @_;
8308: return if ( !exists($domain{$name}) );
8309:
8310: if (!$what) {
8311: return $domain{$name}{'description'};
8312: }
8313: return $domain{$name}{$what};
8314: }
1.327 albertel 8315: }
8316:
8317:
1.1 albertel 8318: # ------------------------------------------------------------- Read hosts file
8319: {
1.838 albertel 8320: my %hostname;
1.844 albertel 8321: my %hostdom;
1.845 albertel 8322: my %libserv;
1.852 albertel 8323: my $loaded;
1.888 albertel 8324: my %name_to_host;
1.852 albertel 8325:
8326: sub parse_hosts_tab {
8327: my ($file) = @_;
8328: foreach my $configline (@$file) {
8329: next if ($configline =~ /^(\#|\s*$ )/x);
8330: next if ($configline =~ /^\^/);
8331: chomp($configline);
8332: my ($id,$domain,$role,$name)=split(/:/,$configline);
8333: $name=~s/\s//g;
8334: if ($id && $domain && $role && $name) {
8335: $hostname{$id}=$name;
1.888 albertel 8336: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8337: $hostdom{$id}=$domain;
8338: if ($role eq 'library') { $libserv{$id}=$name; }
8339: }
8340: }
8341: }
1.864 albertel 8342:
8343: sub reset_hosts_info {
1.897 albertel 8344: &purge_remembered();
1.864 albertel 8345: &reset_domain_info();
8346: &reset_hosts_ip_info();
1.892 albertel 8347: undef(%name_to_host);
1.864 albertel 8348: undef(%hostname);
8349: undef(%hostdom);
8350: undef(%libserv);
8351: undef($loaded);
8352: }
1.1 albertel 8353:
1.852 albertel 8354: sub load_hosts_tab {
1.869 albertel 8355: my ($ignore_cache) = @_;
8356: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8357: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8358: my @config = <$config>;
8359: &parse_hosts_tab(\@config);
8360: close($config);
8361: $loaded=1;
1.1 albertel 8362: }
1.852 albertel 8363:
1.838 albertel 8364: sub hostname {
1.852 albertel 8365: &load_hosts_tab() if (!$loaded);
8366:
1.838 albertel 8367: my ($lonid) = @_;
8368: return $hostname{$lonid};
8369: }
1.845 albertel 8370:
1.838 albertel 8371: sub all_hostnames {
1.852 albertel 8372: &load_hosts_tab() if (!$loaded);
8373:
1.838 albertel 8374: return %hostname;
8375: }
1.845 albertel 8376:
1.888 albertel 8377: sub all_names {
8378: &load_hosts_tab() if (!$loaded);
8379:
8380: return %name_to_host;
8381: }
8382:
1.845 albertel 8383: sub is_library {
1.852 albertel 8384: &load_hosts_tab() if (!$loaded);
8385:
1.845 albertel 8386: return exists($libserv{$_[0]});
8387: }
8388:
8389: sub all_library {
1.852 albertel 8390: &load_hosts_tab() if (!$loaded);
8391:
1.845 albertel 8392: return %libserv;
8393: }
8394:
1.841 albertel 8395: sub get_servers {
1.852 albertel 8396: &load_hosts_tab() if (!$loaded);
8397:
1.841 albertel 8398: my ($domain,$type) = @_;
8399: my %possible_hosts = ($type eq 'library') ? %libserv
8400: : %hostname;
8401: my %result;
1.842 albertel 8402: if (ref($domain) eq 'ARRAY') {
8403: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8404: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8405: $result{$host} = $hostname;
8406: }
8407: }
8408: } else {
8409: while ( my ($host,$hostname) = each(%possible_hosts)) {
8410: if ($hostdom{$host} eq $domain) {
8411: $result{$host} = $hostname;
8412: }
1.841 albertel 8413: }
8414: }
8415: return %result;
8416: }
1.845 albertel 8417:
1.844 albertel 8418: sub host_domain {
1.852 albertel 8419: &load_hosts_tab() if (!$loaded);
8420:
1.844 albertel 8421: my ($lonid) = @_;
8422: return $hostdom{$lonid};
8423: }
8424:
1.841 albertel 8425: sub all_domains {
1.852 albertel 8426: &load_hosts_tab() if (!$loaded);
8427:
1.841 albertel 8428: my %seen;
8429: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8430: return @uniq;
8431: }
1.1 albertel 8432: }
8433:
1.847 albertel 8434: {
8435: my %iphost;
1.856 albertel 8436: my %name_to_ip;
8437: my %lonid_to_ip;
1.869 albertel 8438:
1.847 albertel 8439: sub get_hosts_from_ip {
8440: my ($ip) = @_;
8441: my %iphosts = &get_iphost();
8442: if (ref($iphosts{$ip})) {
8443: return @{$iphosts{$ip}};
8444: }
8445: return;
1.839 albertel 8446: }
1.864 albertel 8447:
8448: sub reset_hosts_ip_info {
8449: undef(%iphost);
8450: undef(%name_to_ip);
8451: undef(%lonid_to_ip);
8452: }
1.856 albertel 8453:
8454: sub get_host_ip {
8455: my ($lonid) = @_;
8456: if (exists($lonid_to_ip{$lonid})) {
8457: return $lonid_to_ip{$lonid};
8458: }
8459: my $name=&hostname($lonid);
8460: my $ip = gethostbyname($name);
8461: return if (!$ip || length($ip) ne 4);
8462: $ip=inet_ntoa($ip);
8463: $name_to_ip{$name} = $ip;
8464: $lonid_to_ip{$lonid} = $ip;
8465: return $ip;
8466: }
1.847 albertel 8467:
8468: sub get_iphost {
1.869 albertel 8469: my ($ignore_cache) = @_;
1.894 albertel 8470:
1.869 albertel 8471: if (!$ignore_cache) {
8472: if (%iphost) {
8473: return %iphost;
8474: }
8475: my ($ip_info,$cached)=
8476: &Apache::lonnet::is_cached_new('iphost','iphost');
8477: if ($cached) {
8478: %iphost = %{$ip_info->[0]};
8479: %name_to_ip = %{$ip_info->[1]};
8480: %lonid_to_ip = %{$ip_info->[2]};
8481: return %iphost;
8482: }
8483: }
1.894 albertel 8484:
8485: # get yesterday's info for fallback
8486: my %old_name_to_ip;
8487: my ($ip_info,$cached)=
8488: &Apache::lonnet::is_cached_new('iphost','iphost');
8489: if ($cached) {
8490: %old_name_to_ip = %{$ip_info->[1]};
8491: }
8492:
1.888 albertel 8493: my %name_to_host = &all_names();
8494: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8495: my $ip;
8496: if (!exists($name_to_ip{$name})) {
8497: $ip = gethostbyname($name);
8498: if (!$ip || length($ip) ne 4) {
1.894 albertel 8499: if (defined($old_name_to_ip{$name})) {
8500: $ip = $old_name_to_ip{$name};
8501: &logthis("Can't find $name defaulting to old $ip");
8502: } else {
8503: &logthis("Name $name no IP found");
8504: next;
8505: }
8506: } else {
8507: $ip=inet_ntoa($ip);
1.847 albertel 8508: }
8509: $name_to_ip{$name} = $ip;
8510: } else {
8511: $ip = $name_to_ip{$name};
1.653 albertel 8512: }
1.888 albertel 8513: foreach my $id (@{ $name_to_host{$name} }) {
8514: $lonid_to_ip{$id} = $ip;
8515: }
8516: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8517: }
1.869 albertel 8518: &Apache::lonnet::do_cache_new('iphost','iphost',
8519: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8520: 48*60*60);
1.869 albertel 8521:
1.847 albertel 8522: return %iphost;
1.598 albertel 8523: }
8524: }
8525:
1.862 albertel 8526: BEGIN {
8527:
8528: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8529: unless ($readit) {
8530: {
8531: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8532: %perlvar = (%perlvar,%{$configvars});
8533: }
8534:
8535:
1.1 albertel 8536: # ------------------------------------------------------ Read spare server file
8537: {
1.448 albertel 8538: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 8539:
8540: while (my $configline=<$config>) {
8541: chomp($configline);
1.284 matthew 8542: if ($configline) {
1.784 albertel 8543: my ($host,$type) = split(':',$configline,2);
1.785 albertel 8544: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 8545: push(@{ $spareid{$type} }, $host);
1.1 albertel 8546: }
8547: }
1.448 albertel 8548: close($config);
1.1 albertel 8549: }
1.11 www 8550: # ------------------------------------------------------------ Read permissions
8551: {
1.448 albertel 8552: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 8553:
8554: while (my $configline=<$config>) {
1.448 albertel 8555: chomp($configline);
8556: if ($configline) {
8557: my ($role,$perm)=split(/ /,$configline);
8558: if ($perm ne '') { $pr{$role}=$perm; }
8559: }
1.11 www 8560: }
1.448 albertel 8561: close($config);
1.11 www 8562: }
8563:
8564: # -------------------------------------------- Read plain texts for permissions
8565: {
1.448 albertel 8566: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8567:
8568: while (my $configline=<$config>) {
1.448 albertel 8569: chomp($configline);
8570: if ($configline) {
1.742 raeburn 8571: my ($short,@plain)=split(/:/,$configline);
8572: %{$prp{$short}} = ();
8573: if (@plain > 0) {
8574: $prp{$short}{'std'} = $plain[0];
8575: for (my $i=1; $i<@plain; $i++) {
8576: $prp{$short}{'alt'.$i} = $plain[$i];
8577: }
8578: }
1.448 albertel 8579: }
1.135 www 8580: }
1.448 albertel 8581: close($config);
1.135 www 8582: }
8583:
8584: # ---------------------------------------------------------- Read package table
8585: {
1.448 albertel 8586: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8587:
8588: while (my $configline=<$config>) {
1.483 albertel 8589: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8590: chomp($configline);
8591: my ($short,$plain)=split(/:/,$configline);
8592: my ($pack,$name)=split(/\&/,$short);
8593: if ($plain ne '') {
8594: $packagetab{$pack.'&'.$name.'&name'}=$name;
8595: $packagetab{$short}=$plain;
8596: }
1.11 www 8597: }
1.448 albertel 8598: close($config);
1.329 matthew 8599: }
8600:
8601: # ------------- set up temporary directory
8602: {
8603: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8604:
1.11 www 8605: }
8606:
1.794 albertel 8607: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8608: 'compress_threshold'=> 20_000,
8609: });
1.185 www 8610:
1.281 www 8611: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8612: $dumpcount=0;
1.22 www 8613:
1.163 harris41 8614: &logtouch();
1.672 albertel 8615: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8616: $readit=1;
1.564 albertel 8617: {
8618: use integer;
8619: my $test=(2**32)+1;
1.568 albertel 8620: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8621: &logthis(" Detected 64bit platform ($_64bit)");
8622: }
1.195 www 8623: }
1.1 albertel 8624: }
1.179 www 8625:
1.1 albertel 8626: 1;
1.191 harris41 8627: __END__
8628:
1.243 albertel 8629: =pod
8630:
1.191 harris41 8631: =head1 NAME
8632:
1.243 albertel 8633: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8634:
8635: =head1 SYNOPSIS
8636:
1.243 albertel 8637: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8638:
8639: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8640:
1.243 albertel 8641: Common parameters:
8642:
8643: =over 4
8644:
8645: =item *
8646:
8647: $uname : an internal username (if $cname expecting a course Id specifically)
8648:
8649: =item *
8650:
8651: $udom : a domain (if $cdom expecting a course's domain specifically)
8652:
8653: =item *
8654:
8655: $symb : a resource instance identifier
8656:
8657: =item *
8658:
8659: $namespace : the name of a .db file that contains the data needed or
8660: being set.
8661:
8662: =back
8663:
1.394 bowersj2 8664: =head1 OVERVIEW
1.191 harris41 8665:
1.394 bowersj2 8666: lonnet provides subroutines which interact with the
8667: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8668: about classes, users, and resources.
1.243 albertel 8669:
8670: For many of these objects you can also use this to store data about
8671: them or modify them in various ways.
1.191 harris41 8672:
1.394 bowersj2 8673: =head2 Symbs
1.191 harris41 8674:
1.394 bowersj2 8675: To identify a specific instance of a resource, LON-CAPA uses symbols
8676: or "symbs"X<symb>. These identifiers are built from the URL of the
8677: map, the resource number of the resource in the map, and the URL of
8678: the resource itself. The latter is somewhat redundant, but might help
8679: if maps change.
8680:
8681: An example is
8682:
8683: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8684:
8685: The respective map entry is
8686:
8687: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8688: title="Problem 2">
8689: </resource>
8690:
8691: Symbs are used by the random number generator, as well as to store and
8692: restore data specific to a certain instance of for example a problem.
8693:
8694: =head2 Storing And Retrieving Data
8695:
8696: X<store()>X<cstore()>X<restore()>Three of the most important functions
8697: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8698: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8699: is is the non-critical message twin of cstore. These functions are for
8700: handlers to store a perl hash to a user's permanent data space in an
8701: easy manner, and to retrieve it again on another call. It is expected
8702: that a handler would use this once at the beginning to retrieve data,
8703: and then again once at the end to send only the new data back.
8704:
8705: The data is stored in the user's data directory on the user's
8706: homeserver under the ID of the course.
8707:
8708: The hash that is returned by restore will have all of the previous
8709: value for all of the elements of the hash.
8710:
8711: Example:
8712:
8713: #creating a hash
8714: my %hash;
8715: $hash{'foo'}='bar';
8716:
8717: #storing it
8718: &Apache::lonnet::cstore(\%hash);
8719:
8720: #changing a value
8721: $hash{'foo'}='notbar';
8722:
8723: #adding a new value
8724: $hash{'bar'}='foo';
8725: &Apache::lonnet::cstore(\%hash);
8726:
8727: #retrieving the hash
8728: my %history=&Apache::lonnet::restore();
8729:
8730: #print the hash
8731: foreach my $key (sort(keys(%history))) {
8732: print("\%history{$key} = $history{$key}");
8733: }
8734:
8735: Will print out:
1.191 harris41 8736:
1.394 bowersj2 8737: %history{1:foo} = bar
8738: %history{1:keys} = foo:timestamp
8739: %history{1:timestamp} = 990455579
8740: %history{2:bar} = foo
8741: %history{2:foo} = notbar
8742: %history{2:keys} = foo:bar:timestamp
8743: %history{2:timestamp} = 990455580
8744: %history{bar} = foo
8745: %history{foo} = notbar
8746: %history{timestamp} = 990455580
8747: %history{version} = 2
8748:
8749: Note that the special hash entries C<keys>, C<version> and
8750: C<timestamp> were added to the hash. C<version> will be equal to the
8751: total number of versions of the data that have been stored. The
8752: C<timestamp> attribute will be the UNIX time the hash was
8753: stored. C<keys> is available in every historical section to list which
8754: keys were added or changed at a specific historical revision of a
8755: hash.
8756:
8757: B<Warning>: do not store the hash that restore returns directly. This
8758: will cause a mess since it will restore the historical keys as if the
8759: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8760:
1.394 bowersj2 8761: Calling convention:
1.191 harris41 8762:
1.394 bowersj2 8763: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8764: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8765:
1.394 bowersj2 8766: For more detailed information, see lonnet specific documentation.
1.191 harris41 8767:
1.394 bowersj2 8768: =head1 RETURN MESSAGES
1.191 harris41 8769:
1.394 bowersj2 8770: =over 4
1.191 harris41 8771:
1.394 bowersj2 8772: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8773:
1.394 bowersj2 8774: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8775: when the connection is brought back up
1.191 harris41 8776:
1.394 bowersj2 8777: =item * B<con_failed>: unable to contact remote host and unable to save message
8778: for later delivery
1.191 harris41 8779:
1.394 bowersj2 8780: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8781:
1.394 bowersj2 8782: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8783: that was requested
1.191 harris41 8784:
1.243 albertel 8785: =back
1.191 harris41 8786:
1.243 albertel 8787: =head1 PUBLIC SUBROUTINES
1.191 harris41 8788:
1.243 albertel 8789: =head2 Session Environment Functions
1.191 harris41 8790:
1.243 albertel 8791: =over 4
1.191 harris41 8792:
1.394 bowersj2 8793: =item *
8794: X<appenv()>
8795: B<appenv(%hash)>: the value of %hash is written to
8796: the user envirnoment file, and will be restored for each access this
1.620 albertel 8797: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8798: process
1.191 harris41 8799:
8800: =item *
1.394 bowersj2 8801: X<delenv()>
8802: B<delenv($regexp)>: removes all items from the session
8803: environment file that matches the regular expression in $regexp. The
1.620 albertel 8804: values are also delted from the current processes %env.
1.191 harris41 8805:
1.795 albertel 8806: =item * get_env_multiple($name)
8807:
8808: gets $name from the %env hash, it seemlessly handles the cases where multiple
8809: values may be defined and end up as an array ref.
8810:
8811: returns an array of values
8812:
1.243 albertel 8813: =back
8814:
8815: =head2 User Information
1.191 harris41 8816:
1.243 albertel 8817: =over 4
1.191 harris41 8818:
8819: =item *
1.394 bowersj2 8820: X<queryauthenticate()>
8821: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8822: authentication scheme
8823:
8824: =item *
1.394 bowersj2 8825: X<authenticate()>
8826: B<authenticate($uname,$upass,$udom)>: try to
8827: authenticate user from domain's lib servers (first use the current
8828: one). C<$upass> should be the users password.
1.191 harris41 8829:
8830: =item *
1.394 bowersj2 8831: X<homeserver()>
8832: B<homeserver($uname,$udom)>: find the server which has
8833: the user's directory and files (there must be only one), this caches
8834: the answer, and also caches if there is a borken connection.
1.191 harris41 8835:
8836: =item *
1.394 bowersj2 8837: X<idget()>
8838: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8839: (IDs are a unique resource in a domain, there must be only 1 ID per
8840: username, and only 1 username per ID in a specific domain) (returns
8841: hash: id=>name,id=>name)
1.191 harris41 8842:
8843: =item *
1.394 bowersj2 8844: X<idrget()>
8845: B<idrget($udom,@unames)>: find the IDs behind a list of
8846: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8847:
8848: =item *
1.394 bowersj2 8849: X<idput()>
8850: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8851:
8852: =item *
1.394 bowersj2 8853: X<rolesinit()>
8854: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8855:
8856: =item *
1.551 albertel 8857: X<getsection()>
8858: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8859: course $cname, return section name/number or '' for "not in course"
8860: and '-1' for "no section"
8861:
8862: =item *
1.394 bowersj2 8863: X<userenvironment()>
8864: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8865: passed in @what from the requested user's environment, returns a hash
8866:
1.858 raeburn 8867: =item *
8868: X<userlog_query()>
1.859 albertel 8869: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8870: activity.log file. %filters defines filters applied when parsing the
8871: log file. These can be start or end timestamps, or the type of action
8872: - log to look for Login or Logout events, check for Checkin or
8873: Checkout, role for role selection. The response is in the form
8874: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8875: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8876:
1.243 albertel 8877: =back
8878:
8879: =head2 User Roles
8880:
8881: =over 4
8882:
8883: =item *
8884:
1.810 raeburn 8885: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8886: F: full access
8887: U,I,K: authentication modes (cxx only)
8888: '': forbidden
8889: 1: user needs to choose course
8890: 2: browse allowed
1.766 albertel 8891: A: passphrase authentication needed
1.243 albertel 8892:
8893: =item *
8894:
8895: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8896: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8897: and course level
8898:
8899: =item *
8900:
8901: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8902: explanation of a user role term
8903:
1.832 raeburn 8904: =item *
8905:
1.935 raeburn 8906: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 8907: All arguments are optional. Returns a hash of a roles, either for
8908: co-author/assistant author roles for a user's Construction Space
1.906 albertel 8909: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 8910: In the hash, keys are set to colon-separated $uname,$udom,$role, and
8911: (optionally) if $withsec is true, a fourth colon-separated item - $section.
8912: For each key, value is set to colon-separated start and end times for
8913: the role. If no username and domain are specified, will default to
1.934 raeburn 8914: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 8915: of role statuses (active, future or previous), roles
8916: (e.g., cc,in, st etc.) and domains of the roles which can be used
8917: to restrict the list of roles reported. If no array ref is
8918: provided for types, will default to return only active roles.
1.834 albertel 8919:
1.243 albertel 8920: =back
8921:
8922: =head2 User Modification
8923:
8924: =over 4
8925:
8926: =item *
8927:
8928: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8929: user for the level given by URL. Optional start and end dates (leave empty
8930: string or zero for "no date")
1.191 harris41 8931:
8932: =item *
8933:
1.243 albertel 8934: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8935: change a users, password, possible return values are: ok,
8936: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8937: refused
1.191 harris41 8938:
8939: =item *
8940:
1.243 albertel 8941: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8942:
8943: =item *
8944:
1.243 albertel 8945: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8946: modify user
1.191 harris41 8947:
8948: =item *
8949:
1.286 matthew 8950: modifystudent
8951:
8952: modify a students enrollment and identification information.
8953: The course id is resolved based on the current users environment.
8954: This means the envoking user must be a course coordinator or otherwise
8955: associated with a course.
8956:
1.297 matthew 8957: This call is essentially a wrapper for lonnet::modifyuser and
8958: lonnet::modify_student_enrollment
1.286 matthew 8959:
8960: Inputs:
8961:
8962: =over 4
8963:
8964: =item B<$udom> Students loncapa domain
8965:
8966: =item B<$uname> Students loncapa login name
8967:
8968: =item B<$uid> Students id/student number
8969:
8970: =item B<$umode> Students authentication mode
8971:
8972: =item B<$upass> Students password
8973:
8974: =item B<$first> Students first name
8975:
8976: =item B<$middle> Students middle name
8977:
8978: =item B<$last> Students last name
8979:
8980: =item B<$gene> Students generation
8981:
8982: =item B<$usec> Students section in course
8983:
8984: =item B<$end> Unix time of the roles expiration
8985:
8986: =item B<$start> Unix time of the roles start date
8987:
8988: =item B<$forceid> If defined, allow $uid to be changed
8989:
8990: =item B<$desiredhome> server to use as home server for student
8991:
8992: =back
1.297 matthew 8993:
8994: =item *
8995:
8996: modify_student_enrollment
8997:
8998: Change a students enrollment status in a class. The environment variable
8999: 'role.request.course' must be defined for this function to proceed.
9000:
9001: Inputs:
9002:
9003: =over 4
9004:
9005: =item $udom, students domain
9006:
9007: =item $uname, students name
9008:
9009: =item $uid, students user id
9010:
9011: =item $first, students first name
9012:
9013: =item $middle
9014:
9015: =item $last
9016:
9017: =item $gene
9018:
9019: =item $usec
9020:
9021: =item $end
9022:
9023: =item $start
9024:
9025: =back
9026:
1.191 harris41 9027:
9028: =item *
9029:
1.243 albertel 9030: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9031: custom role; give a custom role to a user for the level given by URL. Specify
9032: name and domain of role author, and role name
1.191 harris41 9033:
9034: =item *
9035:
1.243 albertel 9036: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9037:
9038: =item *
9039:
1.243 albertel 9040: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9041:
9042: =back
9043:
9044: =head2 Course Infomation
9045:
9046: =over 4
1.191 harris41 9047:
9048: =item *
9049:
1.631 albertel 9050: coursedescription($courseid) : returns a hash of information about the
9051: specified course id, including all environment settings for the
9052: course, the description of the course will be in the hash under the
9053: key 'description'
1.191 harris41 9054:
9055: =item *
9056:
1.624 albertel 9057: resdata($name,$domain,$type,@which) : request for current parameter
9058: setting for a specific $type, where $type is either 'course' or 'user',
9059: @what should be a list of parameters to ask about. This routine caches
9060: answers for 5 minutes.
1.243 albertel 9061:
1.877 foxr 9062: =item *
9063:
9064: get_courseresdata($courseid, $domain) : dump the entire course resource
9065: data base, returning a hash that is keyed by the resource name and has
9066: values that are the resource value. I believe that the timestamps and
9067: versions are also returned.
9068:
9069:
1.243 albertel 9070: =back
9071:
9072: =head2 Course Modification
9073:
9074: =over 4
1.191 harris41 9075:
9076: =item *
9077:
1.243 albertel 9078: writecoursepref($courseid,%prefs) : write preferences (environment
9079: database) for a course
1.191 harris41 9080:
9081: =item *
9082:
1.243 albertel 9083: createcourse($udom,$description,$url) : make/modify course
9084:
9085: =back
9086:
9087: =head2 Resource Subroutines
9088:
9089: =over 4
1.191 harris41 9090:
9091: =item *
9092:
1.243 albertel 9093: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9094:
9095: =item *
9096:
1.243 albertel 9097: repcopy($filename) : subscribes to the requested file, and attempts to
9098: replicate from the owning library server, Might return
1.607 raeburn 9099: 'unavailable', 'not_found', 'forbidden', 'ok', or
9100: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9101: resource. Expects the local filesystem pathname
9102: (/home/httpd/html/res/....)
9103:
9104: =back
9105:
9106: =head2 Resource Information
9107:
9108: =over 4
1.191 harris41 9109:
9110: =item *
9111:
1.243 albertel 9112: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9113: a vairety of different possible values, $varname should be a request
9114: string, and the other parameters can be used to specify who and what
9115: one is asking about.
9116:
9117: Possible values for $varname are environment.lastname (or other item
9118: from the envirnment hash), user.name (or someother aspect about the
9119: user), resource.0.maxtries (or some other part and parameter of a
9120: resource)
1.204 albertel 9121:
9122: =item *
9123:
1.243 albertel 9124: directcondval($number) : get current value of a condition; reads from a state
9125: string
1.204 albertel 9126:
9127: =item *
9128:
1.243 albertel 9129: condval($condidx) : value of condition index based on state
1.204 albertel 9130:
9131: =item *
9132:
1.243 albertel 9133: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9134: resource's metadata, $what should be either a specific key, or either
9135: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9136: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9137:
9138: this function automatically caches all requests
1.191 harris41 9139:
9140: =item *
9141:
1.243 albertel 9142: metadata_query($query,$custom,$customshow) : make a metadata query against the
9143: network of library servers; returns file handle of where SQL and regex results
9144: will be stored for query
1.191 harris41 9145:
9146: =item *
9147:
1.243 albertel 9148: symbread($filename) : return symbolic list entry (filename argument optional);
9149: returns the data handle
1.191 harris41 9150:
9151: =item *
9152:
1.243 albertel 9153: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9154: a possible symb for the URL in $thisfn, and if is an encryypted
9155: resource that the user accessed using /enc/ returns a 1 on success, 0
9156: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9157: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9158:
1.191 harris41 9159:
9160: =item *
9161:
1.243 albertel 9162: symbclean($symb) : removes versions numbers from a symb, returns the
9163: cleaned symb
1.191 harris41 9164:
9165: =item *
9166:
1.243 albertel 9167: is_on_map($uri) : checks if the $uri is somewhere on the current
9168: course map, user must be in a course for it to work.
1.191 harris41 9169:
9170: =item *
9171:
1.243 albertel 9172: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9173:
9174: =item *
9175:
1.243 albertel 9176: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9177: a random seed, all arguments are optional, if they aren't sent it uses the
9178: environment to derive them. Note: if symb isn't sent and it can't get one
9179: from &symbread it will use the current time as its return value
1.191 harris41 9180:
9181: =item *
9182:
1.243 albertel 9183: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9184: unfakeable, receipt
1.191 harris41 9185:
9186: =item *
9187:
1.620 albertel 9188: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9189:
9190: =item *
9191:
1.243 albertel 9192: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9193:
9194: =item *
9195:
1.243 albertel 9196: 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 9197:
9198: =item *
9199:
1.243 albertel 9200: 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 9201:
9202: =item *
9203:
1.243 albertel 9204: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9205:
9206: =item *
9207:
1.243 albertel 9208: devalidate($symb) : devalidate temporary spreadsheet calculations,
9209: forcing spreadsheet to reevaluate the resource scores next time.
9210:
9211: =back
9212:
9213: =head2 Storing/Retreiving Data
9214:
9215: =over 4
1.191 harris41 9216:
9217: =item *
9218:
1.243 albertel 9219: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9220: for this url; hashref needs to be given and should be a \%hashname; the
9221: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9222: be derived from the env
1.191 harris41 9223:
9224: =item *
9225:
1.243 albertel 9226: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9227: uses critical subroutine
1.191 harris41 9228:
9229: =item *
9230:
1.243 albertel 9231: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9232: all args are optional
1.191 harris41 9233:
9234: =item *
9235:
1.717 albertel 9236: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9237: dumps the complete (or key matching regexp) namespace into a hash
9238: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9239: normally &store()ed into
9240:
9241: $range should be either an integer '100' (give me the first 100
9242: matching records)
9243: or be two integers sperated by a - with no spaces
9244: '30-50' (give me the 30th through the 50th matching
9245: records)
9246:
9247:
9248: =item *
9249:
9250: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9251: replaces a &store() version of data with a replacement set of data
9252: for a particular resource in a namespace passed in the $storehash hash
9253: reference
9254:
9255: =item *
9256:
1.243 albertel 9257: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9258: works very similar to store/cstore, but all data is stored in a
9259: temporary location and can be reset using tmpreset, $storehash should
9260: be a hash reference, returns nothing on success
1.191 harris41 9261:
9262: =item *
9263:
1.243 albertel 9264: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9265: similar to restore, but all data is stored in a temporary location and
9266: can be reset using tmpreset. Returns a hash of values on success,
9267: error string otherwise.
1.191 harris41 9268:
9269: =item *
9270:
1.243 albertel 9271: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9272: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9273:
9274: =item *
9275:
1.243 albertel 9276: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9277: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9278:
9279: =item *
9280:
1.243 albertel 9281: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9282: namesp ($udom and $uname are optional)
1.191 harris41 9283:
9284: =item *
9285:
1.702 albertel 9286: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9287: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9288: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9289:
1.702 albertel 9290: $range should be either an integer '100' (give me the first 100
9291: matching records)
9292: or be two integers sperated by a - with no spaces
9293: '30-50' (give me the 30th through the 50th matching
9294: records)
1.449 matthew 9295: =item *
9296:
9297: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9298: $store can be a scalar, an array reference, or if the amount to be
9299: incremented is > 1, a hash reference.
9300:
9301: ($udom and $uname are optional)
1.191 harris41 9302:
9303: =item *
9304:
1.243 albertel 9305: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9306: ($udom and $uname are optional)
1.191 harris41 9307:
9308: =item *
9309:
1.243 albertel 9310: cput($namespace,$storehash,$udom,$uname) : critical put
9311: ($udom and $uname are optional)
1.191 harris41 9312:
9313: =item *
9314:
1.748 albertel 9315: newput($namespace,$storehash,$udom,$uname) :
9316:
9317: Attempts to store the items in the $storehash, but only if they don't
9318: currently exist, if this succeeds you can be certain that you have
9319: successfully created a new key value pair in the $namespace db.
9320:
9321:
9322: Args:
9323: $namespace: name of database to store values to
9324: $storehash: hashref to store to the db
9325: $udom: (optional) domain of user containing the db
9326: $uname: (optional) name of user caontaining the db
9327:
9328: Returns:
9329: 'ok' -> succeeded in storing all keys of $storehash
9330: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9331: least <key> already existed in the db (other
9332: requested keys may also already exist)
9333: 'error: <msg>' -> unable to tie the DB or other erorr occured
9334: 'con_lost' -> unable to contact request server
9335: 'refused' -> action was not allowed by remote machine
9336:
9337:
9338: =item *
9339:
1.243 albertel 9340: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9341: reference filled in from namesp (encrypts the return communication)
9342: ($udom and $uname are optional)
1.191 harris41 9343:
9344: =item *
9345:
1.243 albertel 9346: log($udom,$name,$home,$message) : write to permanent log for user; use
9347: critical subroutine
9348:
1.806 raeburn 9349: =item *
9350:
1.860 raeburn 9351: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9352: array reference filled in from namespace found in domain level on either
9353: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9354:
9355: =item *
9356:
1.860 raeburn 9357: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9358: domain level either on specified domain server ($uhome) or primary domain
9359: server ($udom and $uhome are optional)
1.806 raeburn 9360:
1.243 albertel 9361: =back
9362:
9363: =head2 Network Status Functions
9364:
9365: =over 4
1.191 harris41 9366:
9367: =item *
9368:
9369: dirlist($uri) : return directory list based on URI
9370:
9371: =item *
9372:
1.243 albertel 9373: spareserver() : find server with least workload from spare.tab
9374:
9375: =back
9376:
9377: =head2 Apache Request
9378:
9379: =over 4
1.191 harris41 9380:
9381: =item *
9382:
1.243 albertel 9383: ssi($url,%hash) : server side include, does a complete request cycle on url to
9384: localhost, posts hash
9385:
9386: =back
9387:
9388: =head2 Data to String to Data
9389:
9390: =over 4
1.191 harris41 9391:
9392: =item *
9393:
1.243 albertel 9394: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9395: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9396:
9397: =item *
9398:
1.243 albertel 9399: hashref2str($hashref) : convert a hashref into a string complete with
9400: escaping and '=' and '&' separators, supports elements that are
9401: arrayrefs and hashrefs
1.191 harris41 9402:
9403: =item *
9404:
1.243 albertel 9405: arrayref2str($arrayref) : convert an arrayref into a string complete
9406: with escaping and '&' separators, supports elements that are arrayrefs
9407: and hashrefs
1.191 harris41 9408:
9409: =item *
9410:
1.243 albertel 9411: str2hash($string) : convert string to hash using unescaping and
9412: splitting on '=' and '&', supports elements that are arrayrefs and
9413: hashrefs
1.191 harris41 9414:
9415: =item *
9416:
1.243 albertel 9417: str2array($string) : convert string to hash using unescaping and
9418: splitting on '&', supports elements that are arrayrefs and hashrefs
9419:
9420: =back
9421:
9422: =head2 Logging Routines
9423:
9424: =over 4
9425:
9426: These routines allow one to make log messages in the lonnet.log and
9427: lonnet.perm logfiles.
1.191 harris41 9428:
9429: =item *
9430:
1.243 albertel 9431: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9432:
9433: =item *
9434:
1.243 albertel 9435: logthis() : append message to the normal lonnet.log file, it gets
9436: preiodically rolled over and deleted.
1.191 harris41 9437:
9438: =item *
9439:
1.243 albertel 9440: logperm() : append a permanent message to lonnet.perm.log, this log
9441: file never gets deleted by any automated portion of the system, only
9442: messages of critical importance should go in here.
9443:
9444: =back
9445:
9446: =head2 General File Helper Routines
9447:
9448: =over 4
1.191 harris41 9449:
9450: =item *
9451:
1.481 raeburn 9452: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9453: (a) files in /uploaded
9454: (i) If a local copy of the file exists -
9455: compares modification date of local copy with last-modified date for
9456: definitive version stored on home server for course. If local copy is
9457: stale, requests a new version from the home server and stores it.
9458: If the original has been removed from the home server, then local copy
9459: is unlinked.
9460: (ii) If local copy does not exist -
9461: requests the file from the home server and stores it.
9462:
9463: If $caller is 'uploadrep':
9464: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9465: for request for files originally uploaded via DOCS.
9466: - returns 'ok' if fresh local copy now available, -1 otherwise.
9467:
9468: Otherwise:
9469: This indicates a call from the content generation phase of the request.
9470: - returns the entire contents of the file or -1.
9471:
9472: (b) files in /res
9473: - returns the entire contents of a file or -1;
9474: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9475:
1.712 albertel 9476:
9477: =item *
9478:
9479: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9480: reference
9481:
9482: returns either a stat() list of data about the file or an empty list
9483: if the file doesn't exist or couldn't find out about it (connection
9484: problems or user unknown)
9485:
1.191 harris41 9486: =item *
9487:
1.243 albertel 9488: filelocation($dir,$file) : returns file system location of a file
9489: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9490: directory that relative $file lookups are to looked in ($dir of /a/dir
9491: and a file of ../bob will become /a/bob)
1.191 harris41 9492:
9493: =item *
9494:
9495: hreflocation($dir,$file) : returns file system location or a URL; same as
9496: filelocation except for hrefs
9497:
9498: =item *
9499:
9500: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9501:
1.243 albertel 9502: =back
9503:
1.608 albertel 9504: =head2 Usererfile file routines (/uploaded*)
9505:
9506: =over 4
9507:
9508: =item *
9509:
9510: userfileupload(): main rotine for putting a file in a user or course's
9511: filespace, arguments are,
9512:
1.620 albertel 9513: formname - required - this is the name of the element in $env where the
1.608 albertel 9514: filename, and the contents of the file to create/modifed exist
1.620 albertel 9515: the filename is in $env{'form.'.$formname.'.filename'} and the
9516: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 9517: coursedoc - if true, store the file in the course of the active role
9518: of the current user
9519: subdir - required - subdirectory to put the file in under ../userfiles/
9520: if undefined, it will be placed in "unknown"
9521:
9522: (This routine calls clean_filename() to remove any dangerous
9523: characters from the filename, and then calls finuserfileupload() to
9524: complete the transaction)
9525:
9526: returns either the url of the uploaded file (/uploaded/....) if successful
9527: and /adm/notfound.html if unsuccessful
9528:
9529: =item *
9530:
9531: clean_filename(): routine for cleaing a filename up for storage in
9532: userfile space, argument is:
9533:
9534: filename - proposed filename
9535:
9536: returns: the new clean filename
9537:
9538: =item *
9539:
9540: finishuserfileupload(): routine that creaes and sends the file to
9541: userspace, probably shouldn't be called directly
9542:
9543: docuname: username or courseid of destination for the file
9544: docudom: domain of user/course of destination for the file
9545: formname: same as for userfileupload()
9546: fname: filename (inculding subdirectories) for the file
9547:
9548: returns either the url of the uploaded file (/uploaded/....) if successful
9549: and /adm/notfound.html if unsuccessful
9550:
9551: =item *
9552:
9553: renameuserfile(): renames an existing userfile to a new name
9554:
9555: Args:
9556: docuname: username or courseid of destination for the file
9557: docudom: domain of user/course of destination for the file
9558: old: current file name (including any subdirs under userfiles)
9559: new: desired file name (including any subdirs under userfiles)
9560:
9561: =item *
9562:
9563: mkdiruserfile(): creates a directory is a userfiles dir
9564:
9565: Args:
9566: docuname: username or courseid of destination for the file
9567: docudom: domain of user/course of destination for the file
9568: dir: dir to create (including any subdirs under userfiles)
9569:
9570: =item *
9571:
9572: removeuserfile(): removes a file that exists in userfiles
9573:
9574: Args:
9575: docuname: username or courseid of destination for the file
9576: docudom: domain of user/course of destination for the file
9577: fname: filname to delete (including any subdirs under userfiles)
9578:
9579: =item *
9580:
9581: removeuploadedurl(): convience function for removeuserfile()
9582:
9583: Args:
9584: url: a full /uploaded/... url to delete
9585:
1.747 albertel 9586: =item *
9587:
9588: get_portfile_permissions():
9589: Args:
9590: domain: domain of user or course contain the portfolio files
9591: user: name of user or num of course contain the portfolio files
9592: Returns:
9593: hashref of a dump of the proper file_permissions.db
9594:
9595:
9596: =item *
9597:
9598: get_access_controls():
9599:
9600: Args:
9601: current_permissions: the hash ref returned from get_portfile_permissions()
9602: group: (optional) the group you want the files associated with
9603: file: (optional) the file you want access info on
9604:
9605: Returns:
1.749 raeburn 9606: a hash (keys are file names) of hashes containing
9607: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9608: values are XML containing access control settings (see below)
1.747 albertel 9609:
9610: Internal notes:
9611:
1.749 raeburn 9612: access controls are stored in file_permissions.db as key=value pairs.
9613: key -> path to file/file_name\0uniqueID:scope_end_start
9614: where scope -> public,guest,course,group,domains or users.
9615: end -> UNIX time for end of access (0 -> no end date)
9616: start -> UNIX time for start of access
9617:
9618: value -> XML description of access control
9619: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9620: <start></start>
9621: <end></end>
9622:
9623: <password></password> for scope type = guest
9624:
9625: <domain></domain> for scope type = course or group
9626: <number></number>
9627: <roles id="">
9628: <role></role>
9629: <access></access>
9630: <section></section>
9631: <group></group>
9632: </roles>
9633:
9634: <dom></dom> for scope type = domains
9635:
9636: <users> for scope type = users
9637: <user>
9638: <uname></uname>
9639: <udom></udom>
9640: </user>
9641: </users>
9642: </scope>
9643:
9644: Access data is also aggregated for each file in an additional key=value pair:
9645: key -> path to file/file_name\0accesscontrol
9646: value -> reference to hash
9647: hash contains key = value pairs
9648: where key = uniqueID:scope_end_start
9649: value = UNIX time record was last updated
9650:
9651: Used to improve speed of look-ups of access controls for each file.
9652:
9653: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9654:
9655: modify_access_controls():
9656:
9657: Modifies access controls for a portfolio file
9658: Args
9659: 1. file name
9660: 2. reference to hash of required changes,
9661: 3. domain
9662: 4. username
9663: where domain,username are the domain of the portfolio owner
9664: (either a user or a course)
9665:
9666: Returns:
9667: 1. result of additions or updates ('ok' or 'error', with error message).
9668: 2. result of deletions ('ok' or 'error', with error message).
9669: 3. reference to hash of any new or updated access controls.
9670: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9671: key = integer (inbound ID)
9672: value = uniqueID
1.747 albertel 9673:
1.608 albertel 9674: =back
9675:
1.243 albertel 9676: =head2 HTTP Helper Routines
9677:
9678: =over 4
9679:
1.191 harris41 9680: =item *
9681:
9682: escape() : unpack non-word characters into CGI-compatible hex codes
9683:
9684: =item *
9685:
9686: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9687:
1.243 albertel 9688: =back
9689:
9690: =head1 PRIVATE SUBROUTINES
9691:
9692: =head2 Underlying communication routines (Shouldn't call)
9693:
9694: =over 4
9695:
9696: =item *
9697:
9698: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9699:
9700: =item *
9701:
9702: reply() : uses subreply to send a message to remote machine, logs all failures
9703:
9704: =item *
9705:
9706: critical() : passes a critical message to another server; if cannot
9707: get through then place message in connection buffer directory and
9708: returns con_delayed, if incapable of saving message, returns
9709: con_failed
9710:
9711: =item *
9712:
9713: reconlonc() : tries to reconnect lonc client processes.
9714:
9715: =back
9716:
9717: =head2 Resource Access Logging
9718:
9719: =over 4
9720:
9721: =item *
9722:
9723: flushcourselogs() : flush (save) buffer logs and access logs
9724:
9725: =item *
9726:
9727: courselog($what) : save message for course in hash
9728:
9729: =item *
9730:
9731: courseacclog($what) : save message for course using &courselog(). Perform
9732: special processing for specific resource types (problems, exams, quizzes, etc).
9733:
1.191 harris41 9734: =item *
9735:
9736: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9737: as a PerlChildExitHandler
1.243 albertel 9738:
9739: =back
9740:
9741: =head2 Other
9742:
9743: =over 4
9744:
9745: =item *
9746:
9747: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9748:
9749: =back
9750:
9751: =cut
1.877 foxr 9752:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>