Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.4
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.4! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.3 2010/08/17 00:19:24 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.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.3 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
1.1056.4.3 raeburn 199: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
1.1056.4.3 raeburn 214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: }
220: }
221: my ($answer,$loncaparev);
222: my @ids=¤t_machine_ids();
223: if (grep(/^\Q$lonhost\E$/,@ids)) {
224: $answer = $perlvar{'lonVersion'};
225: if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
226: $loncaparev = $1;
227: }
228: } else {
229: $answer = &reply('serverloncaparev',$lonhost);
230: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
231: if ($caller eq 'loncron') {
232: my $ua=new LWP::UserAgent;
233: $ua->timeout(20);
234: my $protocol = $protocol{$lonhost};
235: $protocol = 'http' if ($protocol ne 'https');
236: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
237: my $request=new HTTP::Request('GET',$url);
238: my $response=$ua->request($request);
239: unless ($response->is_error()) {
240: my $content = $response->content;
241: if ($content =~ /<p>VERSION\:\s*([\d.\-]+)<\/p>/) {
242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
248: } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
249: $loncaparev = $1;
250: }
251: }
252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
253: }
254: }
255:
256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 260: if (defined($cached)) {
1.1056.4.3 raeburn 261: return $serverhomeID;
262: }
263: }
264: my $cachetime = 12*3600;
265: my $serverhomeID;
266: if ($caller eq 'loncron') {
267: my @machine_ids = &machine_ids($hostname);
268: foreach my $id (@machine_ids) {
269: my $response = &reply('serverhomeID',$id);
270: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
271: $serverhomeID = $response;
272: last;
273: }
1.993 raeburn 274: }
1.1056.4.3 raeburn 275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 280: }
1.1056.4.3 raeburn 281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 282: }
283:
1.1 albertel 284: # -------------------------------------------------- Non-critical communication
285: sub subreply {
286: my ($cmd,$server)=@_;
1.838 albertel 287: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 288: #
289: # With loncnew process trimming, there's a timing hole between lonc server
290: # process exit and the master server picking up the listen on the AF_UNIX
291: # socket. In that time interval, a lock file will exist:
292:
293: my $lockfile=$peerfile.".lock";
294: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
295: sleep(1);
296: }
297: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 298: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 299: #
1.550 foxr 300: # We'll give the connection a few tries before abandoning it. If
301: # connection is not possible, we'll con_lost back to the client.
302: #
303: my $client;
304: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
305: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
306: Type => SOCK_STREAM,
307: Timeout => 10);
1.869 albertel 308: if ($client) {
1.550 foxr 309: last; # Connected!
1.850 albertel 310: } else {
1.853 albertel 311: &create_connection(&hostname($server),$server);
1.550 foxr 312: }
1.850 albertel 313: sleep(1); # Try again later if failed connection.
1.550 foxr 314: }
315: my $answer;
316: if ($client) {
1.704 albertel 317: print $client "sethost:$server:$cmd\n";
1.550 foxr 318: $answer=<$client>;
319: if (!$answer) { $answer="con_lost"; }
320: chomp($answer);
321: } else {
322: $answer = 'con_lost'; # Failed connection.
323: }
1.1 albertel 324: return $answer;
325: }
326:
327: sub reply {
328: my ($cmd,$server)=@_;
1.838 albertel 329: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 330: my $answer=subreply($cmd,$server);
1.65 www 331: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 332: &logthis("<font color=\"blue\">WARNING:".
1.12 www 333: " $cmd to $server returned $answer</font>");
334: }
1.1 albertel 335: return $answer;
336: }
337:
338: # ----------------------------------------------------------- Send USR1 to lonc
339:
340: sub reconlonc {
1.891 albertel 341: my ($lonid) = @_;
342: my $hostname = &hostname($lonid);
343: if ($lonid) {
344: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
345: if ($hostname && -e $peerfile) {
346: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
347: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
348: Type => SOCK_STREAM,
349: Timeout => 10);
350: if ($client) {
351: print $client ("reset_retries\n");
352: my $answer=<$client>;
353: #reset just this one.
354: }
355: }
356: return;
357: }
358:
1.836 www 359: &logthis("Trying to reconnect lonc");
1.1 albertel 360: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 361: if (open(my $fh,"<$loncfile")) {
1.1 albertel 362: my $loncpid=<$fh>;
363: chomp($loncpid);
364: if (kill 0 => $loncpid) {
365: &logthis("lonc at pid $loncpid responding, sending USR1");
366: kill USR1 => $loncpid;
367: sleep 1;
1.836 www 368: } else {
1.12 www 369: &logthis(
1.672 albertel 370: "<font color=\"blue\">WARNING:".
1.12 www 371: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 372: }
373: } else {
1.836 www 374: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 375: }
376: }
377:
378: # ------------------------------------------------------ Critical communication
1.12 www 379:
1.1 albertel 380: sub critical {
381: my ($cmd,$server)=@_;
1.838 albertel 382: unless (&hostname($server)) {
1.672 albertel 383: &logthis("<font color=\"blue\">WARNING:".
1.89 www 384: " Critical message to unknown server ($server)</font>");
385: return 'no_such_host';
386: }
1.1 albertel 387: my $answer=reply($cmd,$server);
388: if ($answer eq 'con_lost') {
389: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 390: my $answer=reply($cmd,$server);
1.1 albertel 391: if ($answer eq 'con_lost') {
392: my $now=time;
393: my $middlename=$cmd;
1.5 www 394: $middlename=substr($middlename,0,16);
1.1 albertel 395: $middlename=~s/\W//g;
396: my $dfilename=
1.305 www 397: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
398: $dumpcount++;
1.1 albertel 399: {
1.448 albertel 400: my $dfh;
401: if (open($dfh,">$dfilename")) {
402: print $dfh "$cmd\n";
403: close($dfh);
404: }
1.1 albertel 405: }
406: sleep 2;
407: my $wcmd='';
408: {
1.448 albertel 409: my $dfh;
410: if (open($dfh,"<$dfilename")) {
411: $wcmd=<$dfh>;
412: close($dfh);
413: }
1.1 albertel 414: }
415: chomp($wcmd);
1.7 www 416: if ($wcmd eq $cmd) {
1.672 albertel 417: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 418: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 419: &logperm("D:$server:$cmd");
420: return 'con_delayed';
421: } else {
1.672 albertel 422: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 423: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 424: &logperm("F:$server:$cmd");
425: return 'con_failed';
426: }
427: }
428: }
429: return $answer;
1.405 albertel 430: }
431:
1.755 albertel 432: # ------------------------------------------- check if return value is an error
433:
434: sub error {
435: my ($result) = @_;
1.756 albertel 436: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 437: if ($2 == 2) { return undef; }
438: return $1;
439: }
440: return undef;
441: }
442:
1.783 albertel 443: sub convert_and_load_session_env {
444: my ($lonidsdir,$handle)=@_;
445: my @profile;
446: {
1.917 albertel 447: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
448: if (!$opened) {
1.915 albertel 449: return 0;
450: }
1.783 albertel 451: flock($idf,LOCK_SH);
452: @profile=<$idf>;
453: close($idf);
454: }
455: my %temp_env;
456: foreach my $line (@profile) {
1.786 albertel 457: if ($line !~ m/=/) {
458: return 0;
459: }
1.783 albertel 460: chomp($line);
461: my ($envname,$envvalue)=split(/=/,$line,2);
462: $temp_env{&unescape($envname)} = &unescape($envvalue);
463: }
464: unlink("$lonidsdir/$handle.id");
465: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
466: 0640)) {
467: %disk_env = %temp_env;
468: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
469: untie(%disk_env);
470: }
1.786 albertel 471: return 1;
1.783 albertel 472: }
473:
1.374 www 474: # ------------------------------------------- Transfer profile into environment
1.780 albertel 475: my $env_loaded;
476: sub transfer_profile_to_env {
1.788 albertel 477: my ($lonidsdir,$handle,$force_transfer) = @_;
478: if (!$force_transfer && $env_loaded) { return; }
1.374 www 479:
1.720 albertel 480: if (!defined($lonidsdir)) {
481: $lonidsdir = $perlvar{'lonIDsDir'};
482: }
483: if (!defined($handle)) {
484: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
485: }
486:
1.786 albertel 487: my $convert;
488: {
1.917 albertel 489: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
490: if (!$opened) {
1.915 albertel 491: return;
492: }
1.786 albertel 493: flock($idf,LOCK_SH);
494: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
495: &GDBM_READER(),0640)) {
496: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
497: untie(%disk_env);
498: } else {
499: $convert = 1;
500: }
501: }
502: if ($convert) {
503: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
504: &logthis("Failed to load session, or convert session.");
505: }
1.374 www 506: }
1.783 albertel 507:
1.786 albertel 508: my %remove;
1.783 albertel 509: while ( my $envname = each(%env) ) {
1.433 matthew 510: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
511: if ($time < time-300) {
1.783 albertel 512: $remove{$key}++;
1.433 matthew 513: }
514: }
515: }
1.783 albertel 516:
1.619 albertel 517: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 518: $env_loaded=1;
1.783 albertel 519: foreach my $expired_key (keys(%remove)) {
1.433 matthew 520: &delenv($expired_key);
1.374 www 521: }
1.1 albertel 522: }
523:
1.916 albertel 524: # ---------------------------------------------------- Check for valid session
525: sub check_for_valid_session {
526: my ($r) = @_;
527: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
528: my $lonid=$cookies{'lonID'};
529: return undef if (!$lonid);
530:
531: my $handle=&LONCAPA::clean_handle($lonid->value);
532: my $lonidsdir=$r->dir_config('lonIDsDir');
533: return undef if (!-e "$lonidsdir/$handle.id");
534:
1.917 albertel 535: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
536: return undef if (!$opened);
1.916 albertel 537:
538: flock($idf,LOCK_SH);
539: my %disk_env;
540: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
541: &GDBM_READER(),0640)) {
542: return undef;
543: }
544:
545: if (!defined($disk_env{'user.name'})
546: || !defined($disk_env{'user.domain'})) {
547: return undef;
548: }
549: return $handle;
550: }
551:
1.830 albertel 552: sub timed_flock {
553: my ($file,$lock_type) = @_;
554: my $failed=0;
555: eval {
556: local $SIG{__DIE__}='DEFAULT';
557: local $SIG{ALRM}=sub {
558: $failed=1;
559: die("failed lock");
560: };
561: alarm(13);
562: flock($file,$lock_type);
563: alarm(0);
564: };
565: if ($failed) {
566: return undef;
567: } else {
568: return 1;
569: }
570: }
571:
1.5 www 572: # ---------------------------------------------------------- Append Environment
573:
574: sub appenv {
1.949 raeburn 575: my ($newenv,$roles) = @_;
576: if (ref($newenv) eq 'HASH') {
577: foreach my $key (keys(%{$newenv})) {
578: my $refused = 0;
579: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
580: $refused = 1;
581: if (ref($roles) eq 'ARRAY') {
582: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
583: if (grep(/^\Q$role\E$/,@{$roles})) {
584: $refused = 0;
585: }
586: }
587: }
588: if ($refused) {
589: &logthis("<font color=\"blue\">WARNING: ".
590: "Attempt to modify environment ".$key." to ".$newenv->{$key}
591: .'</font>');
592: delete($newenv->{$key});
593: } else {
594: $env{$key}=$newenv->{$key};
595: }
596: }
597: my $opened = open(my $env_file,'+<',$env{'user.environment'});
598: if ($opened
599: && &timed_flock($env_file,LOCK_EX)
600: &&
601: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
602: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
603: while (my ($key,$value) = each(%{$newenv})) {
604: $disk_env{$key} = $value;
605: }
606: untie(%disk_env);
1.35 www 607: }
1.191 harris41 608: }
1.56 www 609: return 'ok';
610: }
611: # ----------------------------------------------------- Delete from Environment
612:
613: sub delenv {
1.987 raeburn 614: my ($delthis,$regexp) = @_;
1.56 www 615: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 616: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 617: "Attempt to delete from environment ".$delthis);
618: return 'error';
619: }
1.917 albertel 620: my $opened = open(my $env_file,'+<',$env{'user.environment'});
621: if ($opened
1.915 albertel 622: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 623: &&
624: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
625: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 626: foreach my $key (keys(%disk_env)) {
1.987 raeburn 627: if ($regexp) {
628: if ($key=~/^$delthis/) {
629: delete($env{$key});
630: delete($disk_env{$key});
631: }
632: } else {
633: if ($key=~/^\Q$delthis\E/) {
634: delete($env{$key});
635: delete($disk_env{$key});
636: }
637: }
1.448 albertel 638: }
1.783 albertel 639: untie(%disk_env);
1.5 www 640: }
641: return 'ok';
1.369 albertel 642: }
643:
1.790 albertel 644: sub get_env_multiple {
645: my ($name) = @_;
646: my @values;
647: if (defined($env{$name})) {
648: # exists is it an array
649: if (ref($env{$name})) {
650: @values=@{ $env{$name} };
651: } else {
652: $values[0]=$env{$name};
653: }
654: }
655: return(@values);
656: }
657:
1.958 www 658: # ------------------------------------------------------------------- Locking
659:
660: sub set_lock {
661: my ($text)=@_;
662: $locknum++;
663: my $id=$$.'-'.$locknum;
664: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
665: 'session.lock.'.$id => $text});
666: return $id;
667: }
668:
669: sub get_locks {
670: my $num=0;
671: my %texts=();
672: foreach my $lock (split(/\,/,$env{'session.locks'})) {
673: if ($lock=~/\w/) {
674: $num++;
675: $texts{$lock}=$env{'session.lock.'.$lock};
676: }
677: }
678: return ($num,%texts);
679: }
680:
681: sub remove_lock {
682: my ($id)=@_;
683: my $newlocks='';
684: foreach my $lock (split(/\,/,$env{'session.locks'})) {
685: if (($lock=~/\w/) && ($lock ne $id)) {
686: $newlocks.=','.$lock;
687: }
688: }
689: &appenv({'session.locks' => $newlocks});
690: &delenv('session.lock.'.$id);
691: }
692:
693: sub remove_all_locks {
694: my $activelocks=$env{'session.locks'};
695: foreach my $lock (split(/\,/,$env{'session.locks'})) {
696: if ($lock=~/\w/) {
697: &remove_lock($lock);
698: }
699: }
700: }
701:
702:
1.369 albertel 703: # ------------------------------------------ Find out current server userload
704: sub userload {
705: my $numusers=0;
706: {
707: opendir(LONIDS,$perlvar{'lonIDsDir'});
708: my $filename;
709: my $curtime=time;
710: while ($filename=readdir(LONIDS)) {
1.925 albertel 711: next if ($filename eq '.' || $filename eq '..');
712: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 713: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 714: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 715: }
716: closedir(LONIDS);
717: }
718: my $userloadpercent=0;
719: my $maxuserload=$perlvar{'lonUserLoadLim'};
720: if ($maxuserload) {
1.371 albertel 721: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 722: }
1.372 albertel 723: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 724: return $userloadpercent;
1.283 www 725: }
726:
727: # ------------------------------------------ Fight off request when overloaded
728:
729: sub overloaderror {
730: my ($r,$checkserver)=@_;
731: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
732: my $loadavg;
733: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 734: open(my $loadfile,'/proc/loadavg');
1.283 www 735: $loadavg=<$loadfile>;
736: $loadavg =~ s/\s.*//g;
1.285 matthew 737: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 738: close($loadfile);
1.283 www 739: } else {
740: $loadavg=&reply('load',$checkserver);
741: }
1.285 matthew 742: my $overload=$loadavg-100;
1.283 www 743: if ($overload>0) {
1.285 matthew 744: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 745: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 746: return 413;
1.283 www 747: }
748: return '';
1.5 www 749: }
1.1 albertel 750:
751: # ------------------------------ Find server with least workload from spare.tab
1.11 www 752:
1.1 albertel 753: sub spareserver {
1.670 albertel 754: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 755: my $spare_server;
1.370 albertel 756: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 757: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
758: : $userloadpercent;
759:
760: foreach my $try_server (@{ $spareid{'primary'} }) {
761: ($spare_server, $lowest_load) =
762: &compare_server_load($try_server, $spare_server, $lowest_load);
763: }
764:
765: my $found_server = ($spare_server ne '' && $lowest_load < 100);
766:
767: if (!$found_server) {
768: foreach my $try_server (@{ $spareid{'default'} }) {
769: ($spare_server, $lowest_load) =
770: &compare_server_load($try_server, $spare_server, $lowest_load);
771: }
772: }
773:
774: if (!$want_server_name) {
1.968 raeburn 775: my $protocol = 'http';
776: if ($protocol{$spare_server} eq 'https') {
777: $protocol = $protocol{$spare_server};
778: }
1.1001 raeburn 779: if (defined($spare_server)) {
780: my $hostname = &hostname($spare_server);
781: if (defined($hostname)) {
782: $spare_server = $protocol.'://'.$hostname;
783: }
784: }
1.784 albertel 785: }
786: return $spare_server;
787: }
788:
789: sub compare_server_load {
790: my ($try_server, $spare_server, $lowest_load) = @_;
791:
792: my $loadans = &reply('load', $try_server);
793: my $userloadans = &reply('userload',$try_server);
794:
795: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3 raeburn 796: return; #didn't get a number from the server
1.784 albertel 797: }
798:
799: my $load;
800: if ($loadans =~ /\d/) {
801: if ($userloadans =~ /\d/) {
802: #both are numbers, pick the bigger one
803: $load = ($loadans > $userloadans) ? $loadans
804: : $userloadans;
1.411 albertel 805: } else {
1.784 albertel 806: $load = $loadans;
1.411 albertel 807: }
1.784 albertel 808: } else {
809: $load = $userloadans;
810: }
811:
812: if (($load =~ /\d/) && ($load < $lowest_load)) {
813: $spare_server = $try_server;
814: $lowest_load = $load;
1.370 albertel 815: }
1.784 albertel 816: return ($spare_server,$lowest_load);
1.202 matthew 817: }
1.914 albertel 818:
819: # --------------------------- ask offload servers if user already has a session
820: sub find_existing_session {
821: my ($udom,$uname) = @_;
822: foreach my $try_server (@{ $spareid{'primary'} },
823: @{ $spareid{'default'} }) {
824: return $try_server if (&has_user_session($try_server, $udom, $uname));
825: }
826: return;
827: }
828:
829: # -------------------------------- ask if server already has a session for user
830: sub has_user_session {
831: my ($lonid,$udom,$uname) = @_;
832: my $result = &reply(join(':','userhassession',
833: map {&escape($_)} ($udom,$uname)),$lonid);
834: return 1 if ($result eq 'ok');
835:
836: return 0;
837: }
838:
1.1056.4.3 raeburn 839: # --------- determine least loaded server in a user's domain which allows login
840:
841: sub choose_server {
842: my ($udom) = @_;
843: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
844: my %servers = &get_servers($udom);
845: my $lowest_load = 30000;
846: my ($login_host,$hostname);
847: foreach my $lonhost (keys(%servers)) {
848: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
849: if ($loginvia eq '') {
850: ($login_host, $lowest_load) =
851: &compare_server_load($lonhost, $login_host, $lowest_load);
852: }
853: }
854: if ($login_host ne '') {
855: $hostname = $servers{$login_host};
856: }
857: return ($login_host,$hostname);
858: }
859:
1.202 matthew 860: # --------------------------------------------- Try to change a user's password
861:
862: sub changepass {
1.799 raeburn 863: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 864: $currentpass = &escape($currentpass);
865: $newpass = &escape($newpass);
1.1030 raeburn 866: my $lonhost = $perlvar{'lonHostID'};
867: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 868: $server);
869: if (! $answer) {
870: &logthis("No reply on password change request to $server ".
871: "by $uname in domain $udom.");
872: } elsif ($answer =~ "^ok") {
873: &logthis("$uname in $udom successfully changed their password ".
874: "on $server.");
875: } elsif ($answer =~ "^pwchange_failure") {
876: &logthis("$uname in $udom was unable to change their password ".
877: "on $server. The action was blocked by either lcpasswd ".
878: "or pwchange");
879: } elsif ($answer =~ "^non_authorized") {
880: &logthis("$uname in $udom did not get their password correct when ".
881: "attempting to change it on $server.");
882: } elsif ($answer =~ "^auth_mode_error") {
883: &logthis("$uname in $udom attempted to change their password despite ".
884: "not being locally or internally authenticated on $server.");
885: } elsif ($answer =~ "^unknown_user") {
886: &logthis("$uname in $udom attempted to change their password ".
887: "on $server but were unable to because $server is not ".
888: "their home server.");
889: } elsif ($answer =~ "^refused") {
890: &logthis("$server refused to change $uname in $udom password because ".
891: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 892: } elsif ($answer =~ "invalid_client") {
893: &logthis("$server refused to change $uname in $udom password because ".
894: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 895: }
896: return $answer;
1.1 albertel 897: }
898:
1.169 harris41 899: # ----------------------- Try to determine user's current authentication scheme
900:
901: sub queryauthenticate {
902: my ($uname,$udom)=@_;
1.456 albertel 903: my $uhome=&homeserver($uname,$udom);
904: if (!$uhome) {
905: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
906: return 'no_host';
907: }
908: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
909: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
910: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 911: }
1.456 albertel 912: return $answer;
1.169 harris41 913: }
914:
1.1 albertel 915: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 916:
1.1 albertel 917: sub authenticate {
1.1056.4.3 raeburn 918: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 919: $upass=&escape($upass);
920: $uname= &LONCAPA::clean_username($uname);
1.836 www 921: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 922: my $newhome;
1.836 www 923: if ((!$uhome) || ($uhome eq 'no_host')) {
924: # Maybe the machine was offline and only re-appeared again recently?
925: &reconlonc();
926: # One more
1.952 raeburn 927: $uhome=&homeserver($uname,$udom,1);
928: if (($uhome eq 'no_host') && $checkdefauth) {
929: if (defined(&domain($udom,'primary'))) {
930: $newhome=&domain($udom,'primary');
931: }
932: if ($newhome ne '') {
933: $uhome = $newhome;
934: }
935: }
1.836 www 936: if ((!$uhome) || ($uhome eq 'no_host')) {
937: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 938: return 'no_host';
939: }
1.1 albertel 940: }
1.1056.4.3 raeburn 941: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 942: if ($answer eq 'authorized') {
1.952 raeburn 943: if ($newhome) {
944: &logthis("User $uname at $udom authorized by $uhome, but needs account");
945: return 'no_account_on_host';
946: } else {
947: &logthis("User $uname at $udom authorized by $uhome");
948: return $uhome;
949: }
1.471 albertel 950: }
951: if ($answer eq 'non_authorized') {
952: &logthis("User $uname at $udom rejected by $uhome");
953: return 'no_host';
1.9 www 954: }
1.471 albertel 955: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 956: return 'no_host';
957: }
958:
1.1056.4.3 raeburn 959: sub can_host_session {
960: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
961: my $canhost = 1;
962: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
963: if (ref($remotesessions) eq 'HASH') {
964: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
965: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
966: $canhost = 0;
967: } else {
968: $canhost = 1;
969: }
970: }
971: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
972: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
973: $canhost = 1;
974: } else {
975: $canhost = 0;
976: }
977: }
978: if ($canhost) {
979: if ($remotesessions->{'version'} ne '') {
980: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
981: if ($reqmajor ne '' && $reqminor ne '') {
982: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
983: my $major = $1;
984: my $minor = $2;
985: if (($major < $reqmajor ) ||
986: (($major == $reqmajor) && ($minor < $reqminor))) {
987: $canhost = 0;
988: }
989: } else {
990: $canhost = 0;
991: }
992: }
993: }
994: }
995: }
996: if ($canhost) {
997: if (ref($hostedsessions) eq 'HASH') {
998: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
999: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1000: $canhost = 0;
1001: } else {
1002: $canhost = 1;
1003: }
1004: }
1005: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1006: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1007: $canhost = 1;
1008: } else {
1009: $canhost = 0;
1010: }
1011: }
1012: }
1013: }
1014: return $canhost;
1015: }
1016:
1.1 albertel 1017: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1018:
1.599 albertel 1019: my %homecache;
1.1 albertel 1020: sub homeserver {
1.230 stredwic 1021: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1022: my $index="$uname:$udom";
1.426 albertel 1023:
1.599 albertel 1024: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1025:
1026: my %servers = &get_servers($udom,'library');
1027: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1028: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1029: exists($badServerCache{$tryserver}));
1.841 albertel 1030:
1031: my $answer=reply("home:$udom:$uname",$tryserver);
1032: if ($answer eq 'found') {
1033: delete($badServerCache{$tryserver});
1034: return $homecache{$index}=$tryserver;
1035: } elsif ($answer eq 'no_host') {
1036: $badServerCache{$tryserver}=1;
1037: }
1.1 albertel 1038: }
1039: return 'no_host';
1.70 www 1040: }
1041:
1042: # ------------------------------------- Find the usernames behind a list of IDs
1043:
1044: sub idget {
1045: my ($udom,@ids)=@_;
1046: my %returnhash=();
1047:
1.841 albertel 1048: my %servers = &get_servers($udom,'library');
1049: foreach my $tryserver (keys(%servers)) {
1050: my $idlist=join('&',@ids);
1051: $idlist=~tr/A-Z/a-z/;
1052: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1053: my @answer=();
1054: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1055: @answer=split(/\&/,$reply);
1056: } ;
1057: my $i;
1058: for ($i=0;$i<=$#ids;$i++) {
1059: if ($answer[$i]) {
1060: $returnhash{$ids[$i]}=$answer[$i];
1061: }
1062: }
1063: }
1.70 www 1064: return %returnhash;
1065: }
1066:
1067: # ------------------------------------- Find the IDs behind a list of usernames
1068:
1069: sub idrget {
1070: my ($udom,@unames)=@_;
1071: my %returnhash=();
1.800 albertel 1072: foreach my $uname (@unames) {
1073: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1074: }
1.70 www 1075: return %returnhash;
1076: }
1077:
1078: # ------------------------------- Store away a list of names and associated IDs
1079:
1080: sub idput {
1081: my ($udom,%ids)=@_;
1082: my %servers=();
1.800 albertel 1083: foreach my $uname (keys(%ids)) {
1084: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1085: my $uhom=&homeserver($uname,$udom);
1.70 www 1086: if ($uhom ne 'no_host') {
1.800 albertel 1087: my $id=&escape($ids{$uname});
1.70 www 1088: $id=~tr/A-Z/a-z/;
1.800 albertel 1089: my $esc_unam=&escape($uname);
1.70 www 1090: if ($servers{$uhom}) {
1.800 albertel 1091: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1092: } else {
1.800 albertel 1093: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1094: }
1095: }
1.191 harris41 1096: }
1.800 albertel 1097: foreach my $server (keys(%servers)) {
1098: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1099: }
1.344 www 1100: }
1101:
1.1023 raeburn 1102: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1103: sub dump_dom {
1.1023 raeburn 1104: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1105: if (!$udom) {
1106: $udom=$env{'user.domain'};
1107: }
1108: my %returnhash;
1.1023 raeburn 1109: if ($udom) {
1110: my $uname = &get_domainconfiguser($udom);
1111: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1112: }
1113: return %returnhash;
1114: }
1115:
1.1023 raeburn 1116: # ------------------------------------------ get items from domain db files
1.806 raeburn 1117:
1118: sub get_dom {
1.860 raeburn 1119: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1120: my $items='';
1121: foreach my $item (@$storearr) {
1122: $items.=&escape($item).'&';
1123: }
1124: $items=~s/\&$//;
1.860 raeburn 1125: if (!$udom) {
1126: $udom=$env{'user.domain'};
1127: if (defined(&domain($udom,'primary'))) {
1128: $uhome=&domain($udom,'primary');
1129: } else {
1.874 albertel 1130: undef($uhome);
1.860 raeburn 1131: }
1132: } else {
1133: if (!$uhome) {
1134: if (defined(&domain($udom,'primary'))) {
1135: $uhome=&domain($udom,'primary');
1136: }
1137: }
1138: }
1139: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1140: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1141: my %returnhash;
1.875 albertel 1142: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1143: return %returnhash;
1144: }
1.806 raeburn 1145: my @pairs=split(/\&/,$rep);
1146: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1147: return @pairs;
1148: }
1149: my $i=0;
1150: foreach my $item (@$storearr) {
1151: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1152: $i++;
1153: }
1154: return %returnhash;
1155: } else {
1.880 banghart 1156: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1157: }
1158: }
1159:
1160: # -------------------------------------------- put items in domain db files
1161:
1162: sub put_dom {
1.860 raeburn 1163: my ($namespace,$storehash,$udom,$uhome)=@_;
1164: if (!$udom) {
1165: $udom=$env{'user.domain'};
1166: if (defined(&domain($udom,'primary'))) {
1167: $uhome=&domain($udom,'primary');
1168: } else {
1.874 albertel 1169: undef($uhome);
1.860 raeburn 1170: }
1171: } else {
1172: if (!$uhome) {
1173: if (defined(&domain($udom,'primary'))) {
1174: $uhome=&domain($udom,'primary');
1175: }
1176: }
1177: }
1178: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1179: my $items='';
1180: foreach my $item (keys(%$storehash)) {
1181: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1182: }
1183: $items=~s/\&$//;
1184: return &reply("putdom:$udom:$namespace:$items",$uhome);
1185: } else {
1.860 raeburn 1186: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1187: }
1188: }
1189:
1.1023 raeburn 1190: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1191: sub newput_dom {
1.1023 raeburn 1192: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1193: my $result;
1194: if (!$udom) {
1195: $udom=$env{'user.domain'};
1196: }
1.1023 raeburn 1197: if ($udom) {
1198: my $uname = &get_domainconfiguser($udom);
1199: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1200: }
1201: return $result;
1202: }
1203:
1.1023 raeburn 1204: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1205: sub del_dom {
1.1023 raeburn 1206: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1207: if (ref($storearr) eq 'ARRAY') {
1208: if (!$udom) {
1209: $udom=$env{'user.domain'};
1210: }
1.1023 raeburn 1211: if ($udom) {
1212: my $uname = &get_domainconfiguser($udom);
1213: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1214: }
1215: }
1216: }
1217:
1.1023 raeburn 1218: # ----------------------------------construct domainconfig user for a domain
1219: sub get_domainconfiguser {
1220: my ($udom) = @_;
1221: return $udom.'-domainconfig';
1222: }
1223:
1.837 raeburn 1224: sub retrieve_inst_usertypes {
1225: my ($udom) = @_;
1226: my (%returnhash,@order);
1.989 raeburn 1227: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1228: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1229: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1230: %returnhash = %{$domdefs{'inststatustypes'}};
1231: @order = @{$domdefs{'inststatusorder'}};
1232: } else {
1233: if (defined(&domain($udom,'primary'))) {
1234: my $uhome=&domain($udom,'primary');
1235: my $rep=&reply("inst_usertypes:$udom",$uhome);
1236: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1237: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1238: return (\%returnhash,\@order);
1239: }
1240: my ($hashitems,$orderitems) = split(/:/,$rep);
1241: my @pairs=split(/\&/,$hashitems);
1242: foreach my $item (@pairs) {
1243: my ($key,$value)=split(/=/,$item,2);
1244: $key = &unescape($key);
1245: next if ($key =~ /^error: 2 /);
1246: $returnhash{$key}=&thaw_unescape($value);
1247: }
1248: my @esc_order = split(/\&/,$orderitems);
1249: foreach my $item (@esc_order) {
1250: push(@order,&unescape($item));
1251: }
1252: } else {
1253: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1254: }
1255: }
1256: return (\%returnhash,\@order);
1257: }
1258:
1.868 raeburn 1259: sub is_domainimage {
1260: my ($url) = @_;
1261: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1262: if (&domain($1) ne '') {
1263: return '1';
1264: }
1265: }
1266: return;
1267: }
1268:
1.899 raeburn 1269: sub inst_directory_query {
1270: my ($srch) = @_;
1271: my $udom = $srch->{'srchdomain'};
1272: my %results;
1273: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1274: my $outcome;
1.899 raeburn 1275: if ($homeserver ne '') {
1.904 albertel 1276: my $queryid=&reply("querysend:instdirsearch:".
1277: &escape($srch->{'srchby'}).':'.
1278: &escape($srch->{'srchterm'}).':'.
1279: &escape($srch->{'srchtype'}),$homeserver);
1280: my $host=&hostname($homeserver);
1281: if ($queryid !~/^\Q$host\E\_/) {
1282: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1283: return;
1284: }
1285: my $response = &get_query_reply($queryid);
1286: my $maxtries = 5;
1287: my $tries = 1;
1288: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1289: $response = &get_query_reply($queryid);
1290: $tries ++;
1291: }
1292:
1293: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1294: if ($response eq 'unavailable') {
1295: $outcome = $response;
1296: } else {
1297: $outcome = 'ok';
1298: my @matches = split(/\n/,$response);
1299: foreach my $match (@matches) {
1300: my ($key,$value) = split(/=/,$match);
1301: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1302: }
1.899 raeburn 1303: }
1304: }
1305: }
1.909 raeburn 1306: return ($outcome,%results);
1.899 raeburn 1307: }
1308:
1309: sub usersearch {
1310: my ($srch) = @_;
1311: my $dom = $srch->{'srchdomain'};
1312: my %results;
1313: my %libserv = &all_library();
1314: my $query = 'usersearch';
1315: foreach my $tryserver (keys(%libserv)) {
1316: if (&host_domain($tryserver) eq $dom) {
1317: my $host=&hostname($tryserver);
1318: my $queryid=
1.911 raeburn 1319: &reply("querysend:".&escape($query).':'.
1320: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1321: &escape($srch->{'srchtype'}).':'.
1322: &escape($srch->{'srchterm'}),$tryserver);
1323: if ($queryid !~/^\Q$host\E\_/) {
1324: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1325: next;
1.899 raeburn 1326: }
1327: my $reply = &get_query_reply($queryid);
1328: my $maxtries = 1;
1329: my $tries = 1;
1330: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1331: $reply = &get_query_reply($queryid);
1332: $tries ++;
1333: }
1334: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1335: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1336: } else {
1.911 raeburn 1337: my @matches;
1338: if ($reply =~ /\n/) {
1339: @matches = split(/\n/,$reply);
1340: } else {
1341: @matches = split(/\&/,$reply);
1342: }
1.899 raeburn 1343: foreach my $match (@matches) {
1344: my ($uname,$udom,%userhash);
1.911 raeburn 1345: foreach my $entry (split(/:/,$match)) {
1346: my ($key,$value) =
1347: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1348: $userhash{$key} = $value;
1349: if ($key eq 'username') {
1350: $uname = $value;
1351: } elsif ($key eq 'domain') {
1352: $udom = $value;
1.911 raeburn 1353: }
1.899 raeburn 1354: }
1355: $results{$uname.':'.$udom} = \%userhash;
1356: }
1357: }
1358: }
1359: }
1360: return %results;
1361: }
1362:
1.912 raeburn 1363: sub get_instuser {
1364: my ($udom,$uname,$id) = @_;
1365: my $homeserver = &domain($udom,'primary');
1366: my ($outcome,%results);
1367: if ($homeserver ne '') {
1368: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1369: &escape($id).':'.&escape($udom),$homeserver);
1370: my $host=&hostname($homeserver);
1371: if ($queryid !~/^\Q$host\E\_/) {
1372: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1373: return;
1374: }
1375: my $response = &get_query_reply($queryid);
1376: my $maxtries = 5;
1377: my $tries = 1;
1378: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1379: $response = &get_query_reply($queryid);
1380: $tries ++;
1381: }
1382: if (!&error($response) && $response ne 'refused') {
1383: if ($response eq 'unavailable') {
1384: $outcome = $response;
1385: } else {
1386: $outcome = 'ok';
1387: my @matches = split(/\n/,$response);
1388: foreach my $match (@matches) {
1389: my ($key,$value) = split(/=/,$match);
1390: $results{&unescape($key)} = &thaw_unescape($value);
1391: }
1392: }
1393: }
1394: }
1395: my %userinfo;
1396: if (ref($results{$uname}) eq 'HASH') {
1397: %userinfo = %{$results{$uname}};
1398: }
1399: return ($outcome,%userinfo);
1400: }
1401:
1402: sub inst_rulecheck {
1.923 raeburn 1403: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1404: my %returnhash;
1405: if ($udom ne '') {
1406: if (ref($rules) eq 'ARRAY') {
1407: @{$rules} = map {&escape($_);} (@{$rules});
1408: my $rulestr = join(':',@{$rules});
1409: my $homeserver=&domain($udom,'primary');
1410: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1411: my $response;
1412: if ($item eq 'username') {
1413: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1414: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1415: $homeserver));
1.923 raeburn 1416: } elsif ($item eq 'id') {
1417: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1418: ':'.&escape($id).':'.$rulestr,
1419: $homeserver));
1.945 raeburn 1420: } elsif ($item eq 'selfcreate') {
1421: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1422: &escape($udom).':'.&escape($uname).
1423: ':'.$rulestr,$homeserver));
1.923 raeburn 1424: }
1.912 raeburn 1425: if ($response ne 'refused') {
1426: my @pairs=split(/\&/,$response);
1427: foreach my $item (@pairs) {
1428: my ($key,$value)=split(/=/,$item,2);
1429: $key = &unescape($key);
1430: next if ($key =~ /^error: 2 /);
1431: $returnhash{$key}=&thaw_unescape($value);
1432: }
1433: }
1434: }
1435: }
1436: }
1437: return %returnhash;
1438: }
1439:
1440: sub inst_userrules {
1.923 raeburn 1441: my ($udom,$check) = @_;
1.912 raeburn 1442: my (%ruleshash,@ruleorder);
1443: if ($udom ne '') {
1444: my $homeserver=&domain($udom,'primary');
1445: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1446: my $response;
1447: if ($check eq 'id') {
1448: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1449: $homeserver);
1.943 raeburn 1450: } elsif ($check eq 'email') {
1451: $response=&reply('instemailrules:'.&escape($udom),
1452: $homeserver);
1.923 raeburn 1453: } else {
1454: $response=&reply('instuserrules:'.&escape($udom),
1455: $homeserver);
1456: }
1.912 raeburn 1457: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1458: ($response ne 'unknown_cmd') &&
1.912 raeburn 1459: ($response ne 'no_such_host')) {
1460: my ($hashitems,$orderitems) = split(/:/,$response);
1461: my @pairs=split(/\&/,$hashitems);
1462: foreach my $item (@pairs) {
1463: my ($key,$value)=split(/=/,$item,2);
1464: $key = &unescape($key);
1465: next if ($key =~ /^error: 2 /);
1466: $ruleshash{$key}=&thaw_unescape($value);
1467: }
1468: my @esc_order = split(/\&/,$orderitems);
1469: foreach my $item (@esc_order) {
1470: push(@ruleorder,&unescape($item));
1471: }
1472: }
1473: }
1474: }
1475: return (\%ruleshash,\@ruleorder);
1476: }
1477:
1.976 raeburn 1478: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1479:
1480: sub get_domain_defaults {
1481: my ($domain) = @_;
1482: my $cachetime = 60*60*24;
1483: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1484: if (defined($cached)) {
1485: if (ref($result) eq 'HASH') {
1486: return %{$result};
1487: }
1488: }
1489: my %domdefaults;
1490: my %domconfig =
1.989 raeburn 1491: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1492: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1493: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1494: if (ref($domconfig{'defaults'}) eq 'HASH') {
1495: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1496: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1497: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1498: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1499: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1500: } else {
1501: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1502: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1503: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1504: }
1.976 raeburn 1505: if (ref($domconfig{'quotas'}) eq 'HASH') {
1506: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1507: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1508: } else {
1509: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1510: }
1511: my @usertools = ('aboutme','blog','portfolio');
1512: foreach my $item (@usertools) {
1513: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1514: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1515: }
1516: }
1517: }
1.985 raeburn 1518: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1519: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1520: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1521: }
1522: }
1.989 raeburn 1523: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1524: foreach my $item ('inststatustypes','inststatusorder') {
1525: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1526: }
1527: }
1.1047 raeburn 1528: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1529: foreach my $item ('canuse_pdfforms') {
1530: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1531: }
1532: }
1.1056.4.3 raeburn 1533: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1534: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1535: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1536: }
1537: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1538: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1539: }
1540: }
1.943 raeburn 1541: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1542: $cachetime);
1543: return %domdefaults;
1544: }
1545:
1.344 www 1546: # --------------------------------------------------- Assign a key to a student
1547:
1548: sub assign_access_key {
1.364 www 1549: #
1550: # a valid key looks like uname:udom#comments
1551: # comments are being appended
1552: #
1.498 www 1553: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1554: $kdom=
1.620 albertel 1555: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1556: $knum=
1.620 albertel 1557: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1558: $cdom=
1.620 albertel 1559: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1560: $cnum=
1.620 albertel 1561: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1562: $udom=$env{'user.name'} unless (defined($udom));
1563: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1564: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1565: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1566: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1567: # assigned to this person
1568: # - this should not happen,
1.345 www 1569: # unless something went wrong
1570: # the first time around
1571: # ready to assign
1.364 www 1572: $logentry=$1.'; '.$logentry;
1.496 www 1573: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1574: $kdom,$knum) eq 'ok') {
1.345 www 1575: # key now belongs to user
1.346 www 1576: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1577: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1578: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1579: return 'ok';
1580: } else {
1581: return
1582: 'error: Count not permanently assign key, will need to be re-entered later.';
1583: }
1584: } else {
1585: return 'error: Could not assign key, try again later.';
1586: }
1.364 www 1587: } elsif (!$existing{$ckey}) {
1.345 www 1588: # the key does not exist
1589: return 'error: The key does not exist';
1590: } else {
1591: # the key is somebody else's
1592: return 'error: The key is already in use';
1593: }
1.344 www 1594: }
1595:
1.364 www 1596: # ------------------------------------------ put an additional comment on a key
1597:
1598: sub comment_access_key {
1599: #
1600: # a valid key looks like uname:udom#comments
1601: # comments are being appended
1602: #
1603: my ($ckey,$cdom,$cnum,$logentry)=@_;
1604: $cdom=
1.620 albertel 1605: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1606: $cnum=
1.620 albertel 1607: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1608: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1609: if ($existing{$ckey}) {
1610: $existing{$ckey}.='; '.$logentry;
1611: # ready to assign
1.367 www 1612: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1613: $cdom,$cnum) eq 'ok') {
1614: return 'ok';
1615: } else {
1616: return 'error: Count not store comment.';
1617: }
1618: } else {
1619: # the key does not exist
1620: return 'error: The key does not exist';
1621: }
1622: }
1623:
1.344 www 1624: # ------------------------------------------------------ Generate a set of keys
1625:
1626: sub generate_access_keys {
1.364 www 1627: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1628: $cdom=
1.620 albertel 1629: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1630: $cnum=
1.620 albertel 1631: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1632: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1633: unless (($cdom) && ($cnum)) { return 0; }
1634: if ($number>10000) { return 0; }
1635: sleep(2); # make sure don't get same seed twice
1636: srand(time()^($$+($$<<15))); # from "Programming Perl"
1637: my $total=0;
1638: for (my $i=1;$i<=$number;$i++) {
1639: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1640: sprintf("%lx",int(100000*rand)).'-'.
1641: sprintf("%lx",int(100000*rand));
1642: $newkey=~s/1/g/g; # folks mix up 1 and l
1643: $newkey=~s/0/h/g; # and also 0 and O
1644: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1645: if ($existing{$newkey}) {
1646: $i--;
1647: } else {
1.364 www 1648: if (&put('accesskeys',
1649: { $newkey => '# generated '.localtime().
1.620 albertel 1650: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1651: '; '.$logentry },
1652: $cdom,$cnum) eq 'ok') {
1.344 www 1653: $total++;
1654: }
1655: }
1656: }
1.620 albertel 1657: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1658: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1659: return $total;
1660: }
1661:
1662: # ------------------------------------------------------- Validate an accesskey
1663:
1664: sub validate_access_key {
1665: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1666: $cdom=
1.620 albertel 1667: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1668: $cnum=
1.620 albertel 1669: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1670: $udom=$env{'user.domain'} unless (defined($udom));
1671: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1672: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1673: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1674: }
1675:
1676: # ------------------------------------- Find the section of student in a course
1.652 albertel 1677: sub devalidate_getsection_cache {
1678: my ($udom,$unam,$courseid)=@_;
1679: my $hashid="$udom:$unam:$courseid";
1680: &devalidate_cache_new('getsection',$hashid);
1681: }
1.298 matthew 1682:
1.815 albertel 1683: sub courseid_to_courseurl {
1684: my ($courseid) = @_;
1685: #already url style courseid
1686: return $courseid if ($courseid =~ m{^/});
1687:
1688: if (exists($env{'course.'.$courseid.'.num'})) {
1689: my $cnum = $env{'course.'.$courseid.'.num'};
1690: my $cdom = $env{'course.'.$courseid.'.domain'};
1691: return "/$cdom/$cnum";
1692: }
1693:
1694: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1695: if (exists($courseinfo{'num'})) {
1696: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1697: }
1698:
1699: return undef;
1700: }
1701:
1.298 matthew 1702: sub getsection {
1703: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1704: my $cachetime=1800;
1.551 albertel 1705:
1706: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1707: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1708: if (defined($cached)) { return $result; }
1709:
1.298 matthew 1710: my %Pending;
1711: my %Expired;
1712: #
1713: # Each role can either have not started yet (pending), be active,
1714: # or have expired.
1715: #
1716: # If there is an active role, we are done.
1717: #
1718: # If there is more than one role which has not started yet,
1719: # choose the one which will start sooner
1720: # If there is one role which has not started yet, return it.
1721: #
1722: # If there is more than one expired role, choose the one which ended last.
1723: # If there is a role which has expired, return it.
1724: #
1.815 albertel 1725: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1726: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1727: foreach my $key (keys(%roleshash)) {
1.479 albertel 1728: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1729: my $section=$1;
1730: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1731: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1732: my $now=time;
1.548 albertel 1733: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1734: $Expired{$end}=$section;
1735: next;
1736: }
1.548 albertel 1737: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1738: $Pending{$start}=$section;
1739: next;
1740: }
1.599 albertel 1741: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1742: }
1743: #
1744: # Presumedly there will be few matching roles from the above
1745: # loop and the sorting time will be negligible.
1746: if (scalar(keys(%Pending))) {
1747: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1748: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1749: }
1750: if (scalar(keys(%Expired))) {
1751: my @sorted = sort {$a <=> $b} keys(%Expired);
1752: my $time = pop(@sorted);
1.599 albertel 1753: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1754: }
1.599 albertel 1755: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1756: }
1.70 www 1757:
1.599 albertel 1758: sub save_cache {
1759: &purge_remembered();
1.722 albertel 1760: #&Apache::loncommon::validate_page();
1.620 albertel 1761: undef(%env);
1.780 albertel 1762: undef($env_loaded);
1.599 albertel 1763: }
1.452 albertel 1764:
1.599 albertel 1765: my $to_remember=-1;
1766: my %remembered;
1767: my %accessed;
1768: my $kicks=0;
1769: my $hits=0;
1.849 albertel 1770: sub make_key {
1771: my ($name,$id) = @_;
1.872 albertel 1772: if (length($id) > 65
1773: && length(&escape($id)) > 200) {
1774: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1775: }
1.849 albertel 1776: return &escape($name.':'.$id);
1777: }
1778:
1.599 albertel 1779: sub devalidate_cache_new {
1780: my ($name,$id,$debug) = @_;
1781: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1782: $id=&make_key($name,$id);
1.599 albertel 1783: $memcache->delete($id);
1784: delete($remembered{$id});
1785: delete($accessed{$id});
1786: }
1787:
1788: sub is_cached_new {
1789: my ($name,$id,$debug) = @_;
1.849 albertel 1790: $id=&make_key($name,$id);
1.599 albertel 1791: if (exists($remembered{$id})) {
1792: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1793: $accessed{$id}=[&gettimeofday()];
1794: $hits++;
1795: return ($remembered{$id},1);
1796: }
1797: my $value = $memcache->get($id);
1798: if (!(defined($value))) {
1799: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1800: return (undef,undef);
1.416 albertel 1801: }
1.599 albertel 1802: if ($value eq '__undef__') {
1803: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1804: $value=undef;
1805: }
1806: &make_room($id,$value,$debug);
1807: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1808: return ($value,1);
1809: }
1810:
1811: sub do_cache_new {
1812: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1813: $id=&make_key($name,$id);
1.599 albertel 1814: my $setvalue=$value;
1815: if (!defined($setvalue)) {
1816: $setvalue='__undef__';
1817: }
1.623 albertel 1818: if (!defined($time) ) {
1819: $time=600;
1820: }
1.599 albertel 1821: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1822: my $result = $memcache->set($id,$setvalue,$time);
1823: if (! $result) {
1.872 albertel 1824: &logthis("caching of id -> $id failed");
1.910 albertel 1825: $memcache->disconnect_all();
1.872 albertel 1826: }
1.600 albertel 1827: # need to make a copy of $value
1.919 albertel 1828: &make_room($id,$value,$debug);
1.599 albertel 1829: return $value;
1830: }
1831:
1832: sub make_room {
1833: my ($id,$value,$debug)=@_;
1.919 albertel 1834:
1835: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1836: : $value;
1.599 albertel 1837: if ($to_remember<0) { return; }
1838: $accessed{$id}=[&gettimeofday()];
1839: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1840: my $to_kick;
1841: my $max_time=0;
1842: foreach my $other (keys(%accessed)) {
1843: if (&tv_interval($accessed{$other}) > $max_time) {
1844: $to_kick=$other;
1845: $max_time=&tv_interval($accessed{$other});
1846: }
1847: }
1848: delete($remembered{$to_kick});
1849: delete($accessed{$to_kick});
1850: $kicks++;
1851: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1852: return;
1853: }
1854:
1.599 albertel 1855: sub purge_remembered {
1.604 albertel 1856: #&logthis("Tossing ".scalar(keys(%remembered)));
1857: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1858: undef(%remembered);
1859: undef(%accessed);
1.428 albertel 1860: }
1.70 www 1861: # ------------------------------------- Read an entry from a user's environment
1862:
1863: sub userenvironment {
1864: my ($udom,$unam,@what)=@_;
1.976 raeburn 1865: my $items;
1866: foreach my $item (@what) {
1867: $items.=&escape($item).'&';
1868: }
1869: $items=~s/\&$//;
1.70 www 1870: my %returnhash=();
1.1009 raeburn 1871: my $uhome = &homeserver($unam,$udom);
1872: unless ($uhome eq 'no_host') {
1873: my @answer=split(/\&/,
1874: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1875: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1876: return %returnhash;
1877: }
1.1009 raeburn 1878: my $i;
1879: for ($i=0;$i<=$#what;$i++) {
1880: $returnhash{$what[$i]}=&unescape($answer[$i]);
1881: }
1.70 www 1882: }
1883: return %returnhash;
1.1 albertel 1884: }
1885:
1.617 albertel 1886: # ---------------------------------------------------------- Get a studentphoto
1887: sub studentphoto {
1888: my ($udom,$unam,$ext) = @_;
1889: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1890: if (defined($env{'request.course.id'})) {
1.708 raeburn 1891: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1892: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1893: return(&retrievestudentphoto($udom,$unam,$ext));
1894: } else {
1895: my ($result,$perm_reqd)=
1.707 albertel 1896: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1897: if ($result eq 'ok') {
1898: if (!($perm_reqd eq 'yes')) {
1899: return(&retrievestudentphoto($udom,$unam,$ext));
1900: }
1901: }
1902: }
1903: }
1904: } else {
1905: my ($result,$perm_reqd) =
1.707 albertel 1906: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1907: if ($result eq 'ok') {
1908: if (!($perm_reqd eq 'yes')) {
1909: return(&retrievestudentphoto($udom,$unam,$ext));
1910: }
1911: }
1912: }
1913: return '/adm/lonKaputt/lonlogo_broken.gif';
1914: }
1915:
1916: sub retrievestudentphoto {
1917: my ($udom,$unam,$ext,$type) = @_;
1918: my $home=&Apache::lonnet::homeserver($unam,$udom);
1919: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1920: if ($ret eq 'ok') {
1921: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1922: if ($type eq 'thumbnail') {
1923: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1924: }
1925: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1926: return $tokenurl;
1927: } else {
1928: if ($type eq 'thumbnail') {
1929: return '/adm/lonKaputt/genericstudent_tn.gif';
1930: } else {
1931: return '/adm/lonKaputt/lonlogo_broken.gif';
1932: }
1.617 albertel 1933: }
1934: }
1935:
1.263 www 1936: # -------------------------------------------------------------------- New chat
1937:
1938: sub chatsend {
1.724 raeburn 1939: my ($newentry,$anon,$group)=@_;
1.620 albertel 1940: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1941: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1942: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1943: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1944: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1945: &escape($newentry)).':'.$group,$chome);
1.292 www 1946: }
1947:
1948: # ------------------------------------------ Find current version of a resource
1949:
1950: sub getversion {
1951: my $fname=&clutter(shift);
1952: unless ($fname=~/^\/res\//) { return -1; }
1953: return ¤tversion(&filelocation('',$fname));
1954: }
1955:
1956: sub currentversion {
1957: my $fname=shift;
1.599 albertel 1958: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1959: if (defined($cached)) { return $result; }
1.292 www 1960: my $author=$fname;
1961: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1962: my ($udom,$uname)=split(/\//,$author);
1963: my $home=homeserver($uname,$udom);
1964: if ($home eq 'no_host') {
1965: return -1;
1966: }
1967: my $answer=reply("currentversion:$fname",$home);
1968: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1969: return -1;
1970: }
1.599 albertel 1971: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1972: }
1973:
1.1 albertel 1974: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1975:
1.1 albertel 1976: sub subscribe {
1977: my $fname=shift;
1.761 raeburn 1978: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1979: $fname=~s/[\n\r]//g;
1.1 albertel 1980: my $author=$fname;
1981: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1982: my ($udom,$uname)=split(/\//,$author);
1983: my $home=homeserver($uname,$udom);
1.335 albertel 1984: if ($home eq 'no_host') {
1985: return 'not_found';
1.1 albertel 1986: }
1987: my $answer=reply("sub:$fname",$home);
1.64 www 1988: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1989: $answer.=' by '.$home;
1990: }
1.1 albertel 1991: return $answer;
1992: }
1993:
1.8 www 1994: # -------------------------------------------------------------- Replicate file
1995:
1996: sub repcopy {
1997: my $filename=shift;
1.23 www 1998: $filename=~s/\/+/\//g;
1.607 raeburn 1999: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2000: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2001: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2002: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2003: return &repcopy_userfile($filename);
2004: }
1.532 albertel 2005: $filename=~s/[\n\r]//g;
1.8 www 2006: my $transname="$filename.in.transfer";
1.828 www 2007: # FIXME: this should flock
1.607 raeburn 2008: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2009: my $remoteurl=subscribe($filename);
1.64 www 2010: if ($remoteurl =~ /^con_lost by/) {
2011: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2012: return 'unavailable';
1.8 www 2013: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2014: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2015: return 'not_found';
1.64 www 2016: } elsif ($remoteurl =~ /^rejected by/) {
2017: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2018: return 'forbidden';
1.20 www 2019: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2020: return 'ok';
1.8 www 2021: } else {
1.290 www 2022: my $author=$filename;
2023: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2024: my ($udom,$uname)=split(/\//,$author);
2025: my $home=homeserver($uname,$udom);
2026: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2027: my @parts=split(/\//,$filename);
2028: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2029: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2030: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2031: return 'bad_request';
1.8 www 2032: }
2033: my $count;
2034: for ($count=5;$count<$#parts;$count++) {
2035: $path.="/$parts[$count]";
2036: if ((-e $path)!=1) {
2037: mkdir($path,0777);
2038: }
2039: }
2040: my $ua=new LWP::UserAgent;
2041: my $request=new HTTP::Request('GET',"$remoteurl");
2042: my $response=$ua->request($request,$transname);
2043: if ($response->is_error()) {
2044: unlink($transname);
2045: my $message=$response->status_line;
1.672 albertel 2046: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2047: ." LWP get: $message: $filename</font>");
1.607 raeburn 2048: return 'unavailable';
1.8 www 2049: } else {
1.16 www 2050: if ($remoteurl!~/\.meta$/) {
2051: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2052: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2053: if ($mresponse->is_error()) {
2054: unlink($filename.'.meta');
2055: &logthis(
1.672 albertel 2056: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2057: }
2058: }
1.8 www 2059: rename($transname,$filename);
1.607 raeburn 2060: return 'ok';
1.8 www 2061: }
1.290 www 2062: }
1.8 www 2063: }
1.330 www 2064: }
2065:
2066: # ------------------------------------------------ Get server side include body
2067: sub ssi_body {
1.381 albertel 2068: my ($filelink,%form)=@_;
1.606 matthew 2069: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2070: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2071: }
1.953 www 2072: my $output='';
2073: my $response;
1.980 raeburn 2074: if ($filelink=~/^https?\:/) {
1.954 raeburn 2075: ($output,$response)=&externalssi($filelink);
1.953 www 2076: } else {
1.1004 droeschl 2077: $filelink .= $filelink=~/\?/ ? '&' : '?';
2078: $filelink .= 'inhibitmenu=yes';
1.953 www 2079: ($output,$response)=&ssi($filelink,%form);
2080: }
1.778 albertel 2081: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2082: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2083: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2084: if (wantarray) {
2085: return ($output, $response);
2086: } else {
2087: return $output;
2088: }
1.8 www 2089: }
2090:
1.15 www 2091: # --------------------------------------------------------- Server Side Include
2092:
1.782 albertel 2093: sub absolute_url {
2094: my ($host_name) = @_;
2095: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2096: if ($host_name eq '') {
2097: $host_name = $ENV{'SERVER_NAME'};
2098: }
2099: return $protocol.$host_name;
2100: }
2101:
1.942 foxr 2102: #
2103: # Server side include.
2104: # Parameters:
2105: # fn Possibly encrypted resource name/id.
2106: # form Hash that describes how the rendering should be done
2107: # and other things.
1.944 foxr 2108: # Returns:
1.950 raeburn 2109: # Scalar context: The content of the response.
2110: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2111: #
1.15 www 2112: sub ssi {
2113:
1.944 foxr 2114: my ($fn,%form)=@_;
1.15 www 2115: my $ua=new LWP::UserAgent;
1.23 www 2116: my $request;
1.711 albertel 2117:
2118: $form{'no_update_last_known'}=1;
1.895 albertel 2119: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2120: if (%form) {
1.782 albertel 2121: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2122: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2123: } else {
1.782 albertel 2124: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2125: }
2126:
1.15 www 2127: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2128: my $response=$ua->request($request);
2129:
1.944 foxr 2130: if (wantarray) {
2131: return ($response->content, $response);
2132: } else {
2133: return $response->content;
1.942 foxr 2134: }
1.324 www 2135: }
2136:
2137: sub externalssi {
2138: my ($url)=@_;
2139: my $ua=new LWP::UserAgent;
2140: my $request=new HTTP::Request('GET',$url);
2141: my $response=$ua->request($request);
1.954 raeburn 2142: if (wantarray) {
2143: return ($response->content, $response);
2144: } else {
2145: return $response->content;
2146: }
1.15 www 2147: }
1.254 www 2148:
1.492 albertel 2149: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2150:
2151: sub allowuploaded {
2152: my ($srcurl,$url)=@_;
2153: $url=&clutter(&declutter($url));
2154: my $dir=$url;
2155: $dir=~s/\/[^\/]+$//;
2156: my %httpref=();
2157: my $httpurl=&hreflocation('',$url);
2158: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2159: &Apache::lonnet::appenv(\%httpref);
1.254 www 2160: }
1.477 raeburn 2161:
1.478 albertel 2162: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2163: # input: action, courseID, current domain, intended
1.637 raeburn 2164: # path to file, source of file, instruction to parse file for objects,
2165: # ref to hash for embedded objects,
2166: # ref to hash for codebase of java objects.
2167: #
1.485 raeburn 2168: # output: url to file (if action was uploaddoc),
2169: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2170: #
1.478 albertel 2171: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2172: # course.
1.477 raeburn 2173: #
1.478 albertel 2174: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2175: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2176: # course's home server.
1.477 raeburn 2177: #
1.478 albertel 2178: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2179: # be copied from $source (current location) to
2180: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2181: # and will then be copied to
2182: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2183: # course's home server.
1.485 raeburn 2184: #
1.481 raeburn 2185: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2186: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2187: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2188: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2189: # in course's home server.
1.637 raeburn 2190: #
1.477 raeburn 2191:
2192: sub process_coursefile {
1.638 albertel 2193: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2194: my $fetchresult;
1.638 albertel 2195: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2196: if ($action eq 'propagate') {
1.638 albertel 2197: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2198: $home);
1.481 raeburn 2199: } else {
1.477 raeburn 2200: my $fpath = '';
2201: my $fname = $file;
1.478 albertel 2202: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2203: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2204: my $filepath = &build_filepath($fpath);
1.481 raeburn 2205: if ($action eq 'copy') {
2206: if ($source eq '') {
2207: $fetchresult = 'no source file';
2208: return $fetchresult;
2209: } else {
2210: my $destination = $filepath.'/'.$fname;
2211: rename($source,$destination);
2212: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2213: $home);
1.481 raeburn 2214: }
2215: } elsif ($action eq 'uploaddoc') {
2216: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2217: print $fh $env{'form.'.$source};
1.481 raeburn 2218: close($fh);
1.637 raeburn 2219: if ($parser eq 'parse') {
1.1024 raeburn 2220: my $mm = new File::MMagic;
2221: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2222: if ($mime_type eq 'text/html') {
2223: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2224: unless ($parse_result eq 'ok') {
2225: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2226: }
1.637 raeburn 2227: }
2228: }
1.477 raeburn 2229: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2230: $home);
1.481 raeburn 2231: if ($fetchresult eq 'ok') {
2232: return '/uploaded/'.$fpath.'/'.$fname;
2233: } else {
2234: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2235: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2236: return '/adm/notfound.html';
2237: }
1.477 raeburn 2238: }
2239: }
1.485 raeburn 2240: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2241: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2242: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2243: }
2244: return $fetchresult;
2245: }
2246:
1.637 raeburn 2247: sub build_filepath {
2248: my ($fpath) = @_;
2249: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2250: unless ($fpath eq '') {
2251: my @parts=split('/',$fpath);
2252: foreach my $part (@parts) {
2253: $filepath.= '/'.$part;
2254: if ((-e $filepath)!=1) {
2255: mkdir($filepath,0777);
2256: }
2257: }
2258: }
2259: return $filepath;
2260: }
2261:
2262: sub store_edited_file {
1.638 albertel 2263: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2264: my $file = $primary_url;
2265: $file =~ s#^/uploaded/$docudom/$docuname/##;
2266: my $fpath = '';
2267: my $fname = $file;
2268: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2269: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2270: my $filepath = &build_filepath($fpath);
2271: open(my $fh,'>'.$filepath.'/'.$fname);
2272: print $fh $content;
2273: close($fh);
1.638 albertel 2274: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2275: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2276: $home);
1.637 raeburn 2277: if ($$fetchresult eq 'ok') {
2278: return '/uploaded/'.$fpath.'/'.$fname;
2279: } else {
1.638 albertel 2280: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2281: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2282: return '/adm/notfound.html';
2283: }
2284: }
2285:
1.531 albertel 2286: sub clean_filename {
1.831 albertel 2287: my ($fname,$args)=@_;
1.315 www 2288: # Replace Windows backslashes by forward slashes
1.257 www 2289: $fname=~s/\\/\//g;
1.831 albertel 2290: if (!$args->{'keep_path'}) {
2291: # Get rid of everything but the actual filename
2292: $fname=~s/^.*\/([^\/]+)$/$1/;
2293: }
1.315 www 2294: # Replace spaces by underscores
2295: $fname=~s/\s+/\_/g;
2296: # Replace all other weird characters by nothing
1.831 albertel 2297: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2298: # Replace all .\d. sequences with _\d. so they no longer look like version
2299: # numbers
2300: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2301: return $fname;
2302: }
1.1051 raeburn 2303: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2304: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2305: # image with the same aspect ratio as the original, but with dimensions which do
2306: # not exceed $resizewidth and $resizeheight.
2307:
1.984 neumanie 2308: sub resizeImage {
1.1051 raeburn 2309: my ($img_path,$resizewidth,$resizeheight) = @_;
2310: my $ima = Image::Magick->new;
2311: my $resized;
2312: if (-e $img_path) {
2313: $ima->Read($img_path);
2314: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2315: my $width = $ima->Get('width');
2316: my $height = $ima->Get('height');
2317: if ($width > $resizewidth) {
2318: my $factor = $width/$resizewidth;
2319: my $newheight = $height/$factor;
2320: $ima->Scale(width=>$resizewidth,height=>$newheight);
2321: $resized = 1;
2322: }
2323: }
2324: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2325: my $width = $ima->Get('width');
2326: my $height = $ima->Get('height');
2327: if ($height > $resizeheight) {
2328: my $factor = $height/$resizeheight;
2329: my $newwidth = $width/$factor;
2330: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2331: $resized = 1;
2332: }
2333: }
2334: if ($resized) {
2335: $ima->Write($img_path);
2336: }
2337: }
2338: return;
1.977 amueller 2339: }
2340:
1.608 albertel 2341: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2342: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2343: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2344: # $coursedoc - if true up to the current course
2345: # if false
2346: # $subdir - directory in userfile to store the file into
1.858 raeburn 2347: # $parser - instruction to parse file for objects ($parser = parse)
2348: # $allfiles - reference to hash for embedded objects
2349: # $codebase - reference to hash for codebase of java objects
2350: # $desuname - username for permanent storage of uploaded file
2351: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2352: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2353: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2354: # $resizewidth - width (pixels) to which to resize uploaded image
2355: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2356: #
1.686 albertel 2357: # output: url of file in userspace, or error: <message>
2358: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2359:
1.531 albertel 2360: sub userfileupload {
1.860 raeburn 2361: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2362: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2363: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2364: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2365: $fname=&clean_filename($fname);
1.315 www 2366: # See if there is anything left
1.257 www 2367: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2368: chop($env{'form.'.$formname});
1.523 raeburn 2369: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2370: my $now = time;
2371: my $filepath = 'tmp/helprequests/'.$now;
2372: my @parts=split(/\//,$filepath);
2373: my $fullpath = $perlvar{'lonDaemons'};
2374: for (my $i=0;$i<@parts;$i++) {
2375: $fullpath .= '/'.$parts[$i];
2376: if ((-e $fullpath)!=1) {
2377: mkdir($fullpath,0777);
2378: }
2379: }
2380: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2381: print $fh $env{'form.'.$formname};
1.523 raeburn 2382: close($fh);
1.741 raeburn 2383: return $fullpath.'/'.$fname;
2384: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2385: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2386: '_'.$env{'user.domain'}.'/pending';
2387: my @parts=split(/\//,$filepath);
2388: my $fullpath = $perlvar{'lonDaemons'};
2389: for (my $i=0;$i<@parts;$i++) {
2390: $fullpath .= '/'.$parts[$i];
2391: if ((-e $fullpath)!=1) {
2392: mkdir($fullpath,0777);
2393: }
2394: }
2395: open(my $fh,'>'.$fullpath.'/'.$fname);
2396: print $fh $env{'form.'.$formname};
2397: close($fh);
2398: return $fullpath.'/'.$fname;
1.523 raeburn 2399: }
1.995 raeburn 2400: if ($subdir eq 'scantron') {
2401: $fname = 'scantron_orig_'.$fname;
2402: } else {
1.258 www 2403: # Create the directory if not present
1.995 raeburn 2404: $fname="$subdir/$fname";
2405: }
1.259 www 2406: if ($coursedoc) {
1.638 albertel 2407: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2408: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2409: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2410: return &finishuserfileupload($docuname,$docudom,
2411: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2412: $codebase,$thumbwidth,$thumbheight,
2413: $resizewidth,$resizeheight);
1.481 raeburn 2414: } else {
1.620 albertel 2415: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2416: return &process_coursefile('uploaddoc',$docuname,$docudom,
2417: $fname,$formname,$parser,
2418: $allfiles,$codebase);
1.481 raeburn 2419: }
1.719 banghart 2420: } elsif (defined($destuname)) {
2421: my $docuname=$destuname;
2422: my $docudom=$destudom;
1.860 raeburn 2423: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2424: $parser,$allfiles,$codebase,
1.1051 raeburn 2425: $thumbwidth,$thumbheight,
2426: $resizewidth,$resizeheight);
1.719 banghart 2427:
1.259 www 2428: } else {
1.638 albertel 2429: my $docuname=$env{'user.name'};
2430: my $docudom=$env{'user.domain'};
1.714 raeburn 2431: if (exists($env{'form.group'})) {
2432: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2433: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2434: }
1.860 raeburn 2435: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2436: $parser,$allfiles,$codebase,
1.1051 raeburn 2437: $thumbwidth,$thumbheight,
2438: $resizewidth,$resizeheight);
1.259 www 2439: }
1.271 www 2440: }
2441:
2442: sub finishuserfileupload {
1.860 raeburn 2443: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2444: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2445: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2446: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2447:
1.860 raeburn 2448: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2449: $file=$fname;
2450: if ($fname=~m|/|) {
2451: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2452: $path.=$fnamepath.'/';
2453: }
1.259 www 2454: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2455: my $count;
2456: for ($count=4;$count<=$#parts;$count++) {
2457: $filepath.="/$parts[$count]";
2458: if ((-e $filepath)!=1) {
2459: mkdir($filepath,0777);
2460: }
2461: }
1.984 neumanie 2462:
1.258 www 2463: # Save the file
2464: {
1.701 albertel 2465: if (!open(FH,'>'.$filepath.'/'.$file)) {
2466: &logthis('Failed to create '.$filepath.'/'.$file);
2467: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2468: return '/adm/notfound.html';
2469: }
2470: if (!print FH ($env{'form.'.$formname})) {
2471: &logthis('Failed to write to '.$filepath.'/'.$file);
2472: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2473: return '/adm/notfound.html';
2474: }
1.570 albertel 2475: close(FH);
1.1051 raeburn 2476: if ($resizewidth && $resizeheight) {
2477: my $mm = new File::MMagic;
2478: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2479: if ($mime_type =~ m{^image/}) {
2480: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2481: }
1.977 amueller 2482: }
1.258 www 2483: }
1.637 raeburn 2484: if ($parser eq 'parse') {
1.1024 raeburn 2485: my $mm = new File::MMagic;
2486: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2487: if ($mime_type eq 'text/html') {
2488: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2489: $allfiles,$codebase);
2490: unless ($parse_result eq 'ok') {
2491: &logthis('Failed to parse '.$filepath.$file.
2492: ' for embedded media: '.$parse_result);
2493: }
1.637 raeburn 2494: }
2495: }
1.860 raeburn 2496: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2497: my $input = $filepath.'/'.$file;
2498: my $output = $filepath.'/'.'tn-'.$file;
2499: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2500: system("convert -sample $thumbsize $input $output");
2501: if (-e $filepath.'/'.'tn-'.$file) {
2502: $fetchthumb = 1;
2503: }
2504: }
1.858 raeburn 2505:
1.259 www 2506: # Notify homeserver to grep it
2507: #
1.984 neumanie 2508: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2509: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2510: if ($fetchresult eq 'ok') {
1.860 raeburn 2511: if ($fetchthumb) {
2512: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2513: if ($thumbresult ne 'ok') {
2514: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2515: $docuhome.': '.$thumbresult);
2516: }
2517: }
1.259 www 2518: #
1.258 www 2519: # Return the URL to it
1.494 albertel 2520: return '/uploaded/'.$path.$file;
1.263 www 2521: } else {
1.494 albertel 2522: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2523: ': '.$fetchresult);
1.263 www 2524: return '/adm/notfound.html';
1.858 raeburn 2525: }
1.493 albertel 2526: }
2527:
1.637 raeburn 2528: sub extract_embedded_items {
1.961 raeburn 2529: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2530: my @state = ();
2531: my %javafiles = (
2532: codebase => '',
2533: code => '',
2534: archive => ''
2535: );
2536: my %mediafiles = (
2537: src => '',
2538: movie => '',
2539: );
1.648 raeburn 2540: my $p;
2541: if ($content) {
2542: $p = HTML::LCParser->new($content);
2543: } else {
1.961 raeburn 2544: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2545: }
1.641 albertel 2546: while (my $t=$p->get_token()) {
1.640 albertel 2547: if ($t->[0] eq 'S') {
2548: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2549: push(@state, $tagname);
1.648 raeburn 2550: if (lc($tagname) eq 'allow') {
2551: &add_filetype($allfiles,$attr->{'src'},'src');
2552: }
1.640 albertel 2553: if (lc($tagname) eq 'img') {
2554: &add_filetype($allfiles,$attr->{'src'},'src');
2555: }
1.886 albertel 2556: if (lc($tagname) eq 'a') {
2557: &add_filetype($allfiles,$attr->{'href'},'href');
2558: }
1.645 raeburn 2559: if (lc($tagname) eq 'script') {
2560: if ($attr->{'archive'} =~ /\.jar$/i) {
2561: &add_filetype($allfiles,$attr->{'archive'},'archive');
2562: } else {
2563: &add_filetype($allfiles,$attr->{'src'},'src');
2564: }
2565: }
2566: if (lc($tagname) eq 'link') {
2567: if (lc($attr->{'rel'}) eq 'stylesheet') {
2568: &add_filetype($allfiles,$attr->{'href'},'href');
2569: }
2570: }
1.640 albertel 2571: if (lc($tagname) eq 'object' ||
2572: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2573: foreach my $item (keys(%javafiles)) {
2574: $javafiles{$item} = '';
2575: }
2576: }
2577: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2578: my $name = lc($attr->{'name'});
2579: foreach my $item (keys(%javafiles)) {
2580: if ($name eq $item) {
2581: $javafiles{$item} = $attr->{'value'};
2582: last;
2583: }
2584: }
2585: foreach my $item (keys(%mediafiles)) {
2586: if ($name eq $item) {
2587: &add_filetype($allfiles, $attr->{'value'}, 'value');
2588: last;
2589: }
2590: }
2591: }
2592: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2593: foreach my $item (keys(%javafiles)) {
2594: if ($attr->{$item}) {
2595: $javafiles{$item} = $attr->{$item};
2596: last;
2597: }
2598: }
2599: foreach my $item (keys(%mediafiles)) {
2600: if ($attr->{$item}) {
2601: &add_filetype($allfiles,$attr->{$item},$item);
2602: last;
2603: }
2604: }
2605: }
2606: } elsif ($t->[0] eq 'E') {
2607: my ($tagname) = ($t->[1]);
2608: if ($javafiles{'codebase'} ne '') {
2609: $javafiles{'codebase'} .= '/';
2610: }
2611: if (lc($tagname) eq 'applet' ||
2612: lc($tagname) eq 'object' ||
2613: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2614: ) {
2615: foreach my $item (keys(%javafiles)) {
2616: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2617: my $file=$javafiles{'codebase'}.$javafiles{$item};
2618: &add_filetype($allfiles,$file,$item);
2619: }
2620: }
2621: }
2622: pop @state;
2623: }
2624: }
1.637 raeburn 2625: return 'ok';
2626: }
2627:
1.639 albertel 2628: sub add_filetype {
2629: my ($allfiles,$file,$type)=@_;
2630: if (exists($allfiles->{$file})) {
2631: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2632: push(@{$allfiles->{$file}}, &escape($type));
2633: }
2634: } else {
2635: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2636: }
2637: }
2638:
1.493 albertel 2639: sub removeuploadedurl {
1.984 neumanie 2640: my ($url)=@_;
2641: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2642: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2643: }
2644:
2645: sub removeuserfile {
2646: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2647: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2648: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2649: if ($result eq 'ok') {
1.798 raeburn 2650: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2651: my $metafile = $fname.'.meta';
2652: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2653: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2654: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2655: my $sqlresult =
1.823 albertel 2656: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2657: 'portfolio_metadata',$group,
2658: 'delete');
1.798 raeburn 2659: }
2660: }
2661: return $result;
1.257 www 2662: }
1.15 www 2663:
1.530 albertel 2664: sub mkdiruserfile {
2665: my ($docuname,$docudom,$dir)=@_;
2666: my $home=&homeserver($docuname,$docudom);
2667: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2668: }
2669:
1.531 albertel 2670: sub renameuserfile {
2671: my ($docuname,$docudom,$old,$new)=@_;
2672: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2673: my $result = &reply("renameuserfile:$docudom:$docuname:".
2674: &escape("$old").':'.&escape("$new"),$home);
2675: if ($result eq 'ok') {
2676: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2677: my $oldmeta = $old.'.meta';
2678: my $newmeta = $new.'.meta';
2679: my $metaresult =
2680: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2681: my $url = "/uploaded/$docudom/$docuname/$old";
2682: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2683: my $sqlresult =
1.823 albertel 2684: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2685: 'portfolio_metadata',$group,
2686: 'delete');
1.798 raeburn 2687: }
2688: }
2689: return $result;
1.531 albertel 2690: }
2691:
1.14 www 2692: # ------------------------------------------------------------------------- Log
2693:
2694: sub log {
2695: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2696: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2697: }
2698:
2699: # ------------------------------------------------------------------ Course Log
1.352 www 2700: #
2701: # This routine flushes several buffers of non-mission-critical nature
2702: #
1.157 www 2703:
2704: sub flushcourselogs {
1.352 www 2705: &logthis('Flushing log buffers');
2706: #
2707: # course logs
2708: # This is a log of all transactions in a course, which can be used
2709: # for data mining purposes
2710: #
2711: # It also collects the courseid database, which lists last transaction
2712: # times and course titles for all courseids
2713: #
2714: my %courseidbuffer=();
1.921 raeburn 2715: foreach my $crsid (keys(%courselogs)) {
1.352 www 2716: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2717: &escape($courselogs{$crsid}),
2718: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2719: delete $courselogs{$crsid};
2720: } else {
2721: &logthis('Failed to flush log buffer for '.$crsid);
2722: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2723: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2724: " exceeded maximum size, deleting.</font>");
2725: delete $courselogs{$crsid};
2726: }
1.352 www 2727: }
1.920 raeburn 2728: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2729: 'description' => $coursedescrbuf{$crsid},
2730: 'inst_code' => $courseinstcodebuf{$crsid},
2731: 'type' => $coursetypebuf{$crsid},
2732: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2733: };
1.191 harris41 2734: }
1.352 www 2735: #
2736: # Write course id database (reverse lookup) to homeserver of courses
2737: # Is used in pickcourse
2738: #
1.840 albertel 2739: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2740: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2741: $courseidbuffer{$crs_home},
2742: $crs_home,'timeonly');
1.352 www 2743: }
2744: #
2745: # File accesses
2746: # Writes to the dynamic metadata of resources to get hit counts, etc.
2747: #
1.449 matthew 2748: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2749: if ($entry =~ /___count$/) {
2750: my ($dom,$name);
1.807 albertel 2751: ($dom,$name,undef)=
1.811 albertel 2752: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2753: if (! defined($dom) || $dom eq '' ||
2754: ! defined($name) || $name eq '') {
1.620 albertel 2755: my $cid = $env{'request.course.id'};
2756: $dom = $env{'request.'.$cid.'.domain'};
2757: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2758: }
1.450 matthew 2759: my $value = $accesshash{$entry};
2760: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2761: my %temphash=($url => $value);
1.449 matthew 2762: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2763: if ($result eq 'ok') {
2764: delete $accesshash{$entry};
2765: } elsif ($result eq 'unknown_cmd') {
2766: # Target server has old code running on it.
1.450 matthew 2767: my %temphash=($entry => $value);
1.449 matthew 2768: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2769: delete $accesshash{$entry};
2770: }
2771: }
2772: } else {
1.811 albertel 2773: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2774: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2775: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2776: delete $accesshash{$entry};
2777: }
1.185 www 2778: }
1.191 harris41 2779: }
1.352 www 2780: #
2781: # Roles
2782: # Reverse lookup of user roles for course faculty/staff and co-authorship
2783: #
1.800 albertel 2784: foreach my $entry (keys(%userrolehash)) {
1.351 www 2785: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2786: split(/\:/,$entry);
2787: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2788: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2789: $rudom,$runame) eq 'ok') {
2790: delete $userrolehash{$entry};
2791: }
2792: }
1.662 raeburn 2793: #
2794: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2795: #
2796: my %domrolebuffer = ();
1.1000 raeburn 2797: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2798: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2799: if ($domrolebuffer{$rudom}) {
2800: $domrolebuffer{$rudom}.='&'.&escape($entry).
2801: '='.&escape($domainrolehash{$entry});
2802: } else {
2803: $domrolebuffer{$rudom}.=&escape($entry).
2804: '='.&escape($domainrolehash{$entry});
2805: }
2806: delete $domainrolehash{$entry};
2807: }
2808: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2809: my %servers = &get_servers($dom,'library');
2810: foreach my $tryserver (keys(%servers)) {
2811: unless (&reply('domroleput:'.$dom.':'.
2812: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2813: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2814: }
1.662 raeburn 2815: }
2816: }
1.186 www 2817: $dumpcount++;
1.157 www 2818: }
2819:
2820: sub courselog {
2821: my $what=shift;
1.158 www 2822: $what=time.':'.$what;
1.620 albertel 2823: unless ($env{'request.course.id'}) { return ''; }
2824: $coursedombuf{$env{'request.course.id'}}=
2825: $env{'course.'.$env{'request.course.id'}.'.domain'};
2826: $coursenumbuf{$env{'request.course.id'}}=
2827: $env{'course.'.$env{'request.course.id'}.'.num'};
2828: $coursehombuf{$env{'request.course.id'}}=
2829: $env{'course.'.$env{'request.course.id'}.'.home'};
2830: $coursedescrbuf{$env{'request.course.id'}}=
2831: $env{'course.'.$env{'request.course.id'}.'.description'};
2832: $courseinstcodebuf{$env{'request.course.id'}}=
2833: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2834: $courseownerbuf{$env{'request.course.id'}}=
2835: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2836: $coursetypebuf{$env{'request.course.id'}}=
2837: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2838: if (defined $courselogs{$env{'request.course.id'}}) {
2839: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2840: } else {
1.620 albertel 2841: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2842: }
1.620 albertel 2843: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2844: &flushcourselogs();
2845: }
1.158 www 2846: }
2847:
2848: sub courseacclog {
2849: my $fnsymb=shift;
1.620 albertel 2850: unless ($env{'request.course.id'}) { return ''; }
2851: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2852: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2853: $what.=':POST';
1.583 matthew 2854: # FIXME: Probably ought to escape things....
1.800 albertel 2855: foreach my $key (keys(%env)) {
2856: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2857: my $formitem = $1;
2858: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2859: $what.=':'.$formitem.'='.$env{$key};
2860: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2861: $what.=':'.$formitem.'='.$env{$key};
2862: }
1.158 www 2863: }
1.191 harris41 2864: }
1.583 matthew 2865: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2866: # FIXME: We should not be depending on a form parameter that someone
2867: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2868: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2869: $what.= ':POST';
2870: # FIXME: Probably ought to escape things....
2871: foreach my $element ('courseexp','crsfulltext','crsrelated',
2872: 'crsdiscuss') {
1.620 albertel 2873: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2874: }
2875: }
1.158 www 2876: }
2877: &courselog($what);
1.149 www 2878: }
2879:
1.185 www 2880: sub countacc {
2881: my $url=&declutter(shift);
1.458 matthew 2882: return if (! defined($url) || $url eq '');
1.620 albertel 2883: unless ($env{'request.course.id'}) { return ''; }
2884: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2885: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2886: $accesshash{$key}++;
1.185 www 2887: }
1.349 www 2888:
1.361 www 2889: sub linklog {
2890: my ($from,$to)=@_;
2891: $from=&declutter($from);
2892: $to=&declutter($to);
2893: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2894: $accesshash{$to.'___'.$from.'___goto'}=1;
2895: }
2896:
1.349 www 2897: sub userrolelog {
2898: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2899: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2900: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2901: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2902: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2903: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2904: $userrolehash
2905: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2906: =$tend.':'.$tstart;
1.662 raeburn 2907: }
1.898 albertel 2908: if (($env{'request.role'} =~ /dc\./) &&
2909: (($trole=~/^au/) || ($trole=~/^in/) ||
2910: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2911: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2912: ($trole=~/^co/))) {
1.898 albertel 2913: $userrolehash
2914: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2915: =$tend.':'.$tstart;
2916: }
1.662 raeburn 2917: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2918: ($trole=~/^li/) || ($trole=~/^li/) ||
2919: ($trole=~/^au/) || ($trole=~/^dg/) ||
2920: ($trole=~/^sc/)) {
2921: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2922: $domainrolehash
2923: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2924: = $tend.':'.$tstart;
2925: }
1.351 www 2926: }
2927:
1.957 raeburn 2928: sub courserolelog {
2929: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2930: if (($trole eq 'cc') || ($trole eq 'in') ||
2931: ($trole eq 'ep') || ($trole eq 'ad') ||
2932: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2933: ($trole=~/^cr/) || ($trole eq 'gr') ||
2934: ($trole eq 'co')) {
1.957 raeburn 2935: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2936: my $cdom = $1;
2937: my $cnum = $2;
2938: my $sec = $3;
2939: my $namespace = 'rolelog';
2940: my %storehash = (
2941: role => $trole,
2942: start => $tstart,
2943: end => $tend,
2944: selfenroll => $selfenroll,
2945: context => $context,
2946: );
2947: if ($trole eq 'gr') {
2948: $namespace = 'groupslog';
2949: $storehash{'group'} = $sec;
2950: } else {
2951: $storehash{'section'} = $sec;
2952: }
2953: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2954: if (($trole ne 'st') || ($sec ne '')) {
2955: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2956: }
1.957 raeburn 2957: }
2958: }
2959: return;
2960: }
2961:
1.351 www 2962: sub get_course_adv_roles {
1.948 raeburn 2963: my ($cid,$codes) = @_;
1.620 albertel 2964: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2965: my %coursehash=&coursedescription($cid);
1.988 raeburn 2966: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2967: my %nothide=();
1.800 albertel 2968: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2969: if ($user !~ /:/) {
2970: $nothide{join(':',split(/[\@]/,$user))}=1;
2971: } else {
2972: $nothide{$user}=1;
2973: }
1.470 www 2974: }
1.351 www 2975: my %returnhash=();
2976: my %dumphash=
2977: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2978: my $now=time;
1.997 raeburn 2979: my %privileged;
1.1000 raeburn 2980: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2981: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2982: if (($tstart) && ($tstart<0)) { next; }
2983: if (($tend) && ($tend<$now)) { next; }
2984: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2985: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2986: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2987: unless (ref($privileged{$domain}) eq 'HASH') {
2988: my %dompersonnel =
1.998 raeburn 2989: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2990: $privileged{$domain} = {};
2991: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2992: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2993: foreach my $user (keys(%{$dompersonnel{$server}})) {
2994: my ($trole,$uname,$udom) = split(/:/,$user);
2995: $privileged{$udom}{$uname} = 1;
2996: }
2997: }
2998: }
2999: }
3000: if ((exists($privileged{$domain}{$username})) &&
3001: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3002: if ($role eq 'cr') { next; }
1.948 raeburn 3003: if ($codes) {
3004: if ($section) { $role .= ':'.$section; }
3005: if ($returnhash{$role}) {
3006: $returnhash{$role}.=','.$username.':'.$domain;
3007: } else {
3008: $returnhash{$role}=$username.':'.$domain;
3009: }
1.351 www 3010: } else {
1.988 raeburn 3011: my $key=&plaintext($role,$crstype);
1.973 bisitz 3012: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3013: if ($returnhash{$key}) {
3014: $returnhash{$key}.=','.$username.':'.$domain;
3015: } else {
3016: $returnhash{$key}=$username.':'.$domain;
3017: }
1.351 www 3018: }
1.948 raeburn 3019: }
1.400 www 3020: return %returnhash;
3021: }
3022:
3023: sub get_my_roles {
1.937 raeburn 3024: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3025: unless (defined($uname)) { $uname=$env{'user.name'}; }
3026: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3027: my (%dumphash,%nothide);
1.858 raeburn 3028: if ($context eq 'userroles') {
3029: %dumphash = &dump('roles',$udom,$uname);
3030: } else {
3031: %dumphash=
1.400 www 3032: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3033: if ($hidepriv) {
3034: my %coursehash=&coursedescription($udom.'_'.$uname);
3035: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3036: if ($user !~ /:/) {
3037: $nothide{join(':',split(/[\@]/,$user))} = 1;
3038: } else {
3039: $nothide{$user} = 1;
3040: }
3041: }
3042: }
1.858 raeburn 3043: }
1.400 www 3044: my %returnhash=();
3045: my $now=time;
1.999 raeburn 3046: my %privileged;
1.800 albertel 3047: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3048: my ($role,$tend,$tstart);
3049: if ($context eq 'userroles') {
3050: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3051: } else {
3052: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3053: }
1.400 www 3054: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3055: my $status = 'active';
1.939 raeburn 3056: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3057: $status = 'previous';
3058: }
3059: if (($tstart) && ($now<$tstart)) {
3060: $status = 'future';
3061: }
3062: if (ref($types) eq 'ARRAY') {
3063: if (!grep(/^\Q$status\E$/,@{$types})) {
3064: next;
3065: }
3066: } else {
3067: if ($status ne 'active') {
3068: next;
3069: }
3070: }
1.867 raeburn 3071: my ($rolecode,$username,$domain,$section,$area);
3072: if ($context eq 'userroles') {
3073: ($area,$rolecode) = split(/_/,$entry);
3074: (undef,$domain,$username,$section) = split(/\//,$area);
3075: } else {
3076: ($role,$username,$domain,$section) = split(/\:/,$entry);
3077: }
1.832 raeburn 3078: if (ref($roledoms) eq 'ARRAY') {
3079: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3080: next;
3081: }
3082: }
3083: if (ref($roles) eq 'ARRAY') {
3084: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3085: if ($role =~ /^cr\//) {
3086: if (!grep(/^cr$/,@{$roles})) {
3087: next;
3088: }
3089: } else {
3090: next;
3091: }
1.832 raeburn 3092: }
1.867 raeburn 3093: }
1.937 raeburn 3094: if ($hidepriv) {
1.999 raeburn 3095: if ($context eq 'userroles') {
3096: if ((&privileged($username,$domain)) &&
3097: (!$nothide{$username.':'.$domain})) {
3098: next;
3099: }
3100: } else {
3101: unless (ref($privileged{$domain}) eq 'HASH') {
3102: my %dompersonnel =
3103: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3104: $privileged{$domain} = {};
3105: if (keys(%dompersonnel)) {
3106: foreach my $server (keys(%dompersonnel)) {
3107: if (ref($dompersonnel{$server}) eq 'HASH') {
3108: foreach my $user (keys(%{$dompersonnel{$server}})) {
3109: my ($trole,$uname,$udom) = split(/:/,$user);
3110: $privileged{$udom}{$uname} = $trole;
3111: }
3112: }
3113: }
3114: }
3115: }
3116: if (exists($privileged{$domain}{$username})) {
3117: if (!$nothide{$username.':'.$domain}) {
3118: next;
3119: }
3120: }
1.937 raeburn 3121: }
3122: }
1.933 raeburn 3123: if ($withsec) {
3124: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3125: $tstart.':'.$tend;
3126: } else {
3127: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3128: }
1.832 raeburn 3129: }
1.373 www 3130: return %returnhash;
1.399 www 3131: }
3132:
3133: # ----------------------------------------------------- Frontpage Announcements
3134: #
3135: #
3136:
3137: sub postannounce {
3138: my ($server,$text)=@_;
1.844 albertel 3139: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3140: unless ($text=~/\w/) { $text=''; }
3141: return &reply('setannounce:'.&escape($text),$server);
3142: }
3143:
3144: sub getannounce {
1.448 albertel 3145:
3146: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3147: my $announcement='';
1.800 albertel 3148: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3149: close($fh);
1.399 www 3150: if ($announcement=~/\w/) {
3151: return
3152: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3153: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3154: } else {
3155: return '';
3156: }
3157: } else {
3158: return '';
3159: }
1.351 www 3160: }
1.353 www 3161:
3162: # ---------------------------------------------------------- Course ID routines
3163: # Deal with domain's nohist_courseid.db files
3164: #
3165:
3166: sub courseidput {
1.921 raeburn 3167: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3168: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3169: my $outcome;
3170: if ($caller eq 'timeonly') {
3171: my $cids = '';
3172: foreach my $item (keys(%$storehash)) {
3173: $cids.=&escape($item).'&';
3174: }
3175: $cids=~s/\&$//;
3176: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3177: $coursehome);
3178: } else {
3179: my $items = '';
3180: foreach my $item (keys(%$storehash)) {
3181: $items.= &escape($item).'='.
3182: &freeze_escape($$storehash{$item}).'&';
3183: }
3184: $items=~s/\&$//;
3185: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3186: $coursehome);
1.918 raeburn 3187: }
3188: if ($outcome eq 'unknown_cmd') {
3189: my $what;
3190: foreach my $cid (keys(%$storehash)) {
3191: $what .= &escape($cid).'=';
1.921 raeburn 3192: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3193: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3194: }
3195: $what =~ s/\:$/&/;
3196: }
3197: $what =~ s/\&$//;
3198: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3199: } else {
3200: return $outcome;
3201: }
1.353 www 3202: }
3203:
3204: sub courseiddump {
1.921 raeburn 3205: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3206: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3207: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3208: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3209: my $as_hash = 1;
3210: my %returnhash;
3211: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3212: my %libserv = &all_library();
3213: foreach my $tryserver (keys(%libserv)) {
3214: if ( ( $hostidflag == 1
3215: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3216: || (!defined($hostidflag)) ) {
3217:
1.918 raeburn 3218: if (($domfilter eq '') ||
3219: (&host_domain($tryserver) eq $domfilter)) {
3220: my $rep =
3221: &reply('courseiddump:'.&host_domain($tryserver).':'.
3222: $sincefilter.':'.&escape($descfilter).':'.
3223: &escape($instcodefilter).':'.&escape($ownerfilter).
3224: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3225: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3226: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3227: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3228: &escape($cc_clone).':'.$cloneonly.':'.
3229: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3230: &escape($creationcontext).':'.$domcloner,
3231: $tryserver);
1.918 raeburn 3232: my @pairs=split(/\&/,$rep);
3233: foreach my $item (@pairs) {
3234: my ($key,$value)=split(/\=/,$item,2);
3235: $key = &unescape($key);
3236: next if ($key =~ /^error: 2 /);
3237: my $result = &thaw_unescape($value);
3238: if (ref($result) eq 'HASH') {
3239: $returnhash{$key}=$result;
3240: } else {
1.921 raeburn 3241: my @responses = split(/:/,$value);
3242: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3243: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3244: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3245: }
1.1008 raeburn 3246: }
1.353 www 3247: }
3248: }
3249: }
3250: }
3251: return %returnhash;
3252: }
3253:
1.1055 raeburn 3254: sub courselastaccess {
3255: my ($cdom,$cnum,$hostidref) = @_;
3256: my %returnhash;
3257: if ($cdom && $cnum) {
3258: my $chome = &homeserver($cnum,$cdom);
3259: if ($chome ne 'no_host') {
3260: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3261: &extract_lastaccess(\%returnhash,$rep);
3262: }
3263: } else {
3264: if (!$cdom) { $cdom=''; }
3265: my %libserv = &all_library();
3266: foreach my $tryserver (keys(%libserv)) {
3267: if (ref($hostidref) eq 'ARRAY') {
3268: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3269: }
3270: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3271: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3272: &extract_lastaccess(\%returnhash,$rep);
3273: }
3274: }
3275: }
3276: return %returnhash;
3277: }
3278:
3279: sub extract_lastaccess {
3280: my ($returnhash,$rep) = @_;
3281: if (ref($returnhash) eq 'HASH') {
3282: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3283: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3284: $rep eq '') {
3285: my @pairs=split(/\&/,$rep);
3286: foreach my $item (@pairs) {
3287: my ($key,$value)=split(/\=/,$item,2);
3288: $key = &unescape($key);
3289: next if ($key =~ /^error: 2 /);
3290: $returnhash->{$key} = &thaw_unescape($value);
3291: }
3292: }
3293: }
3294: return;
3295: }
3296:
1.658 raeburn 3297: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3298:
3299: sub dcmailput {
1.685 raeburn 3300: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3301: my $status = &Apache::lonnet::critical(
1.740 www 3302: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3303: &escape($message),$server);
1.662 raeburn 3304: return $status;
3305: }
3306:
1.658 raeburn 3307: sub dcmaildump {
3308: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3309: my %returnhash=();
1.846 albertel 3310:
3311: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3312: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3313: &escape($enddate).':';
3314: my @esc_senders=map { &escape($_)} @$senders;
3315: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3316: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3317: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3318: if (($key) && ($value)) {
3319: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3320: }
3321: }
3322: }
3323: return %returnhash;
3324: }
1.662 raeburn 3325: # ---------------------------------------------------------- Domain roles
3326:
3327: sub get_domain_roles {
3328: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3329: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3330: $startdate = '.';
3331: }
1.1018 raeburn 3332: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3333: $enddate = '.';
3334: }
1.922 raeburn 3335: my $rolelist;
3336: if (ref($roles) eq 'ARRAY') {
3337: $rolelist = join(':',@{$roles});
3338: }
1.662 raeburn 3339: my %personnel = ();
1.841 albertel 3340:
3341: my %servers = &get_servers($dom,'library');
3342: foreach my $tryserver (keys(%servers)) {
3343: %{$personnel{$tryserver}}=();
3344: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3345: &escape($startdate).':'.
3346: &escape($enddate).':'.
3347: &escape($rolelist), $tryserver))) {
3348: my ($key,$value) = split(/\=/,$line,2);
3349: if (($key) && ($value)) {
3350: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3351: }
3352: }
1.662 raeburn 3353: }
3354: return %personnel;
3355: }
1.658 raeburn 3356:
1.149 www 3357: # ----------------------------------------------------------- Check out an item
3358:
1.504 albertel 3359: sub get_first_access {
3360: my ($type,$argsymb)=@_;
1.790 albertel 3361: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3362: if ($argsymb) { $symb=$argsymb; }
3363: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3364: if ($type eq 'course') {
3365: $res='course';
3366: } elsif ($type eq 'map') {
1.588 albertel 3367: $res=&symbread($map);
3368: } else {
3369: $res=$symb;
3370: }
3371: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3372: return $times{"$courseid\0$res"};
1.504 albertel 3373: }
3374:
3375: sub set_first_access {
3376: my ($type)=@_;
1.790 albertel 3377: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3378: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3379: if ($type eq 'course') {
3380: $res='course';
3381: } elsif ($type eq 'map') {
1.588 albertel 3382: $res=&symbread($map);
3383: } else {
3384: $res=$symb;
3385: }
3386: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3387: if (!$firstaccess) {
1.588 albertel 3388: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3389: }
3390: return 'already_set';
1.504 albertel 3391: }
3392:
1.149 www 3393: sub checkout {
3394: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3395: my $now=time;
3396: my $lonhost=$perlvar{'lonHostID'};
3397: my $infostr=&escape(
1.234 www 3398: 'CHECKOUTTOKEN&'.
1.149 www 3399: $tuname.'&'.
3400: $tudom.'&'.
3401: $tcrsid.'&'.
3402: $symb.'&'.
3403: $now.'&'.$ENV{'REMOTE_ADDR'});
3404: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3405: if ($token=~/^error\:/) {
1.672 albertel 3406: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3407: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3408: "</font>");
3409: return '';
3410: }
3411:
1.149 www 3412: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3413: $token=~tr/a-z/A-Z/;
3414:
1.153 www 3415: my %infohash=('resource.0.outtoken' => $token,
3416: 'resource.0.checkouttime' => $now,
3417: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3418:
3419: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3420: return '';
1.151 www 3421: } else {
1.672 albertel 3422: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3423: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3424: "</font>");
1.149 www 3425: }
3426:
3427: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3428: &escape('Checkout '.$infostr.' - '.
3429: $token)) ne 'ok') {
3430: return '';
1.151 www 3431: } else {
1.672 albertel 3432: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3433: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3434: "</font>");
1.149 www 3435: }
1.151 www 3436: return $token;
1.149 www 3437: }
3438:
3439: # ------------------------------------------------------------ Check in an item
3440:
3441: sub checkin {
3442: my $token=shift;
1.150 www 3443: my $now=time;
3444: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3445: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3446: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3447: $dtoken=~s/\W/\_/g;
1.234 www 3448: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3449: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3450:
1.154 www 3451: unless (($tuname) && ($tudom)) {
3452: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3453: return '';
3454: }
3455:
3456: unless (&allowed('mgr',$tcrsid)) {
3457: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3458: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3459: return '';
3460: }
3461:
1.153 www 3462: my %infohash=('resource.0.intoken' => $token,
3463: 'resource.0.checkintime' => $now,
3464: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3465:
3466: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3467: return '';
3468: }
3469:
3470: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3471: &escape('Checkin - '.$token)) ne 'ok') {
3472: return '';
3473: }
3474:
3475: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3476: }
3477:
3478: # --------------------------------------------- Set Expire Date for Spreadsheet
3479:
3480: sub expirespread {
3481: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3482: my $cid=$env{'request.course.id'};
1.110 www 3483: if ($cid) {
3484: my $now=time;
3485: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3486: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3487: $env{'course.'.$cid.'.num'}.
1.110 www 3488: ':nohist_expirationdates:'.
3489: &escape($key).'='.$now,
1.620 albertel 3490: $env{'course.'.$cid.'.home'})
1.110 www 3491: }
3492: return 'ok';
1.14 www 3493: }
3494:
1.109 www 3495: # ----------------------------------------------------- Devalidate Spreadsheets
3496:
3497: sub devalidate {
1.325 www 3498: my ($symb,$uname,$udom)=@_;
1.620 albertel 3499: my $cid=$env{'request.course.id'};
1.109 www 3500: if ($cid) {
1.391 matthew 3501: # delete the stored spreadsheets for
3502: # - the student level sheet of this user in course's homespace
3503: # - the assessment level sheet for this resource
3504: # for this user in user's homespace
1.553 albertel 3505: # - current conditional state info
1.325 www 3506: my $key=$uname.':'.$udom.':';
1.109 www 3507: my $status=
1.299 matthew 3508: &del('nohist_calculatedsheets',
1.391 matthew 3509: [$key.'studentcalc:'],
1.620 albertel 3510: $env{'course.'.$cid.'.domain'},
3511: $env{'course.'.$cid.'.num'})
1.133 albertel 3512: .' '.
3513: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3514: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3515: unless ($status eq 'ok ok') {
3516: &logthis('Could not devalidate spreadsheet '.
1.325 www 3517: $uname.' at '.$udom.' for '.
1.109 www 3518: $symb.': '.$status);
1.133 albertel 3519: }
1.553 albertel 3520: &delenv('user.state.'.$cid);
1.109 www 3521: }
3522: }
3523:
1.265 albertel 3524: sub get_scalar {
3525: my ($string,$end) = @_;
3526: my $value;
3527: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3528: $value = $1;
3529: } elsif ($$string =~ s/^([^&]*?)&//) {
3530: $value = $1;
3531: }
3532: return &unescape($value);
3533: }
3534:
3535: sub array2str {
3536: my (@array) = @_;
3537: my $result=&arrayref2str(\@array);
3538: $result=~s/^__ARRAY_REF__//;
3539: $result=~s/__END_ARRAY_REF__$//;
3540: return $result;
3541: }
3542:
1.204 albertel 3543: sub arrayref2str {
3544: my ($arrayref) = @_;
1.265 albertel 3545: my $result='__ARRAY_REF__';
1.204 albertel 3546: foreach my $elem (@$arrayref) {
1.265 albertel 3547: if(ref($elem) eq 'ARRAY') {
3548: $result.=&arrayref2str($elem).'&';
3549: } elsif(ref($elem) eq 'HASH') {
3550: $result.=&hashref2str($elem).'&';
3551: } elsif(ref($elem)) {
3552: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3553: } else {
3554: $result.=&escape($elem).'&';
3555: }
3556: }
3557: $result=~s/\&$//;
1.265 albertel 3558: $result .= '__END_ARRAY_REF__';
1.204 albertel 3559: return $result;
3560: }
3561:
1.168 albertel 3562: sub hash2str {
1.204 albertel 3563: my (%hash) = @_;
3564: my $result=&hashref2str(\%hash);
1.265 albertel 3565: $result=~s/^__HASH_REF__//;
3566: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3567: return $result;
3568: }
3569:
3570: sub hashref2str {
3571: my ($hashref)=@_;
1.265 albertel 3572: my $result='__HASH_REF__';
1.800 albertel 3573: foreach my $key (sort(keys(%$hashref))) {
3574: if (ref($key) eq 'ARRAY') {
3575: $result.=&arrayref2str($key).'=';
3576: } elsif (ref($key) eq 'HASH') {
3577: $result.=&hashref2str($key).'=';
3578: } elsif (ref($key)) {
1.265 albertel 3579: $result.='=';
1.800 albertel 3580: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3581: } else {
1.800 albertel 3582: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3583: }
3584:
1.800 albertel 3585: if(ref($hashref->{$key}) eq 'ARRAY') {
3586: $result.=&arrayref2str($hashref->{$key}).'&';
3587: } elsif(ref($hashref->{$key}) eq 'HASH') {
3588: $result.=&hashref2str($hashref->{$key}).'&';
3589: } elsif(ref($hashref->{$key})) {
1.265 albertel 3590: $result.='&';
1.800 albertel 3591: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3592: } else {
1.800 albertel 3593: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3594: }
3595: }
1.168 albertel 3596: $result=~s/\&$//;
1.265 albertel 3597: $result .= '__END_HASH_REF__';
1.168 albertel 3598: return $result;
3599: }
3600:
3601: sub str2hash {
1.265 albertel 3602: my ($string)=@_;
3603: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3604: return %$hash;
3605: }
3606:
3607: sub str2hashref {
1.168 albertel 3608: my ($string) = @_;
1.265 albertel 3609:
3610: my %hash;
3611:
3612: if($string !~ /^__HASH_REF__/) {
3613: if (! ($string eq '' || !defined($string))) {
3614: $hash{'error'}='Not hash reference';
3615: }
3616: return (\%hash, $string);
3617: }
3618:
3619: $string =~ s/^__HASH_REF__//;
3620:
3621: while($string !~ /^__END_HASH_REF__/) {
3622: #key
3623: my $key='';
3624: if($string =~ /^__HASH_REF__/) {
3625: ($key, $string)=&str2hashref($string);
3626: if(defined($key->{'error'})) {
3627: $hash{'error'}='Bad data';
3628: return (\%hash, $string);
3629: }
3630: } elsif($string =~ /^__ARRAY_REF__/) {
3631: ($key, $string)=&str2arrayref($string);
3632: if($key->[0] eq 'Array reference error') {
3633: $hash{'error'}='Bad data';
3634: return (\%hash, $string);
3635: }
3636: } else {
3637: $string =~ s/^(.*?)=//;
1.267 albertel 3638: $key=&unescape($1);
1.265 albertel 3639: }
3640: $string =~ s/^=//;
3641:
3642: #value
3643: my $value='';
3644: if($string =~ /^__HASH_REF__/) {
3645: ($value, $string)=&str2hashref($string);
3646: if(defined($value->{'error'})) {
3647: $hash{'error'}='Bad data';
3648: return (\%hash, $string);
3649: }
3650: } elsif($string =~ /^__ARRAY_REF__/) {
3651: ($value, $string)=&str2arrayref($string);
3652: if($value->[0] eq 'Array reference error') {
3653: $hash{'error'}='Bad data';
3654: return (\%hash, $string);
3655: }
3656: } else {
3657: $value=&get_scalar(\$string,'__END_HASH_REF__');
3658: }
3659: $string =~ s/^&//;
3660:
3661: $hash{$key}=$value;
1.204 albertel 3662: }
1.265 albertel 3663:
3664: $string =~ s/^__END_HASH_REF__//;
3665:
3666: return (\%hash, $string);
1.204 albertel 3667: }
3668:
3669: sub str2array {
1.265 albertel 3670: my ($string)=@_;
3671: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3672: return @$array;
3673: }
3674:
3675: sub str2arrayref {
1.204 albertel 3676: my ($string) = @_;
1.265 albertel 3677: my @array;
3678:
3679: if($string !~ /^__ARRAY_REF__/) {
3680: if (! ($string eq '' || !defined($string))) {
3681: $array[0]='Array reference error';
3682: }
3683: return (\@array, $string);
3684: }
3685:
3686: $string =~ s/^__ARRAY_REF__//;
3687:
3688: while($string !~ /^__END_ARRAY_REF__/) {
3689: my $value='';
3690: if($string =~ /^__HASH_REF__/) {
3691: ($value, $string)=&str2hashref($string);
3692: if(defined($value->{'error'})) {
3693: $array[0] ='Array reference error';
3694: return (\@array, $string);
3695: }
3696: } elsif($string =~ /^__ARRAY_REF__/) {
3697: ($value, $string)=&str2arrayref($string);
3698: if($value->[0] eq 'Array reference error') {
3699: $array[0] ='Array reference error';
3700: return (\@array, $string);
3701: }
3702: } else {
3703: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3704: }
3705: $string =~ s/^&//;
3706:
3707: push(@array, $value);
1.191 harris41 3708: }
1.265 albertel 3709:
3710: $string =~ s/^__END_ARRAY_REF__//;
3711:
3712: return (\@array, $string);
1.168 albertel 3713: }
3714:
1.167 albertel 3715: # -------------------------------------------------------------------Temp Store
3716:
1.168 albertel 3717: sub tmpreset {
3718: my ($symb,$namespace,$domain,$stuname) = @_;
3719: if (!$symb) {
3720: $symb=&symbread();
1.620 albertel 3721: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3722: }
3723: $symb=escape($symb);
3724:
1.620 albertel 3725: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3726: $namespace=~s/\//\_/g;
3727: $namespace=~s/\W//g;
3728:
1.620 albertel 3729: if (!$domain) { $domain=$env{'user.domain'}; }
3730: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3731: if ($domain eq 'public' && $stuname eq 'public') {
3732: $stuname=$ENV{'REMOTE_ADDR'};
3733: }
1.168 albertel 3734: my $path=$perlvar{'lonDaemons'}.'/tmp';
3735: my %hash;
3736: if (tie(%hash,'GDBM_File',
3737: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3738: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3739: foreach my $key (keys(%hash)) {
1.180 albertel 3740: if ($key=~ /:$symb/) {
1.168 albertel 3741: delete($hash{$key});
3742: }
3743: }
3744: }
3745: }
3746:
1.167 albertel 3747: sub tmpstore {
1.168 albertel 3748: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3749:
3750: if (!$symb) {
3751: $symb=&symbread();
1.620 albertel 3752: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3753: }
3754: $symb=escape($symb);
3755:
3756: if (!$namespace) {
3757: # I don't think we would ever want to store this for a course.
3758: # it seems this will only be used if we don't have a course.
1.620 albertel 3759: #$namespace=$env{'request.course.id'};
1.168 albertel 3760: #if (!$namespace) {
1.620 albertel 3761: $namespace=$env{'request.state'};
1.168 albertel 3762: #}
3763: }
3764: $namespace=~s/\//\_/g;
3765: $namespace=~s/\W//g;
1.620 albertel 3766: if (!$domain) { $domain=$env{'user.domain'}; }
3767: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3768: if ($domain eq 'public' && $stuname eq 'public') {
3769: $stuname=$ENV{'REMOTE_ADDR'};
3770: }
1.168 albertel 3771: my $now=time;
3772: my %hash;
3773: my $path=$perlvar{'lonDaemons'}.'/tmp';
3774: if (tie(%hash,'GDBM_File',
3775: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3776: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3777: $hash{"version:$symb"}++;
3778: my $version=$hash{"version:$symb"};
3779: my $allkeys='';
3780: foreach my $key (keys(%$storehash)) {
3781: $allkeys.=$key.':';
1.591 albertel 3782: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3783: }
3784: $hash{"$version:$symb:timestamp"}=$now;
3785: $allkeys.='timestamp';
3786: $hash{"$version:keys:$symb"}=$allkeys;
3787: if (untie(%hash)) {
3788: return 'ok';
3789: } else {
3790: return "error:$!";
3791: }
3792: } else {
3793: return "error:$!";
3794: }
3795: }
1.167 albertel 3796:
1.168 albertel 3797: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3798:
1.168 albertel 3799: sub tmprestore {
3800: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3801:
1.168 albertel 3802: if (!$symb) {
3803: $symb=&symbread();
1.620 albertel 3804: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3805: }
3806: $symb=escape($symb);
3807:
1.620 albertel 3808: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3809:
1.620 albertel 3810: if (!$domain) { $domain=$env{'user.domain'}; }
3811: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3812: if ($domain eq 'public' && $stuname eq 'public') {
3813: $stuname=$ENV{'REMOTE_ADDR'};
3814: }
1.168 albertel 3815: my %returnhash;
3816: $namespace=~s/\//\_/g;
3817: $namespace=~s/\W//g;
3818: my %hash;
3819: my $path=$perlvar{'lonDaemons'}.'/tmp';
3820: if (tie(%hash,'GDBM_File',
3821: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3822: &GDBM_READER(),0640)) {
1.168 albertel 3823: my $version=$hash{"version:$symb"};
3824: $returnhash{'version'}=$version;
3825: my $scope;
3826: for ($scope=1;$scope<=$version;$scope++) {
3827: my $vkeys=$hash{"$scope:keys:$symb"};
3828: my @keys=split(/:/,$vkeys);
3829: my $key;
3830: $returnhash{"$scope:keys"}=$vkeys;
3831: foreach $key (@keys) {
1.591 albertel 3832: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3833: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3834: }
3835: }
1.168 albertel 3836: if (!(untie(%hash))) {
3837: return "error:$!";
3838: }
3839: } else {
3840: return "error:$!";
3841: }
3842: return %returnhash;
1.167 albertel 3843: }
3844:
1.9 www 3845: # ----------------------------------------------------------------------- Store
3846:
3847: sub store {
1.124 www 3848: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3849: my $home='';
3850:
1.168 albertel 3851: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3852:
1.213 www 3853: $symb=&symbclean($symb);
1.122 albertel 3854: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3855:
1.620 albertel 3856: if (!$domain) { $domain=$env{'user.domain'}; }
3857: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3858:
3859: &devalidate($symb,$stuname,$domain);
1.109 www 3860:
3861: $symb=escape($symb);
1.187 www 3862: if (!$namespace) {
1.620 albertel 3863: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3864: return '';
3865: }
3866: }
1.620 albertel 3867: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3868:
3869: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3870: $$storehash{'host'}=$perlvar{'lonHostID'};
3871:
1.12 www 3872: my $namevalue='';
1.800 albertel 3873: foreach my $key (keys(%$storehash)) {
3874: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3875: }
1.12 www 3876: $namevalue=~s/\&$//;
1.187 www 3877: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3878: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3879: }
3880:
1.47 www 3881: # -------------------------------------------------------------- Critical Store
3882:
3883: sub cstore {
1.124 www 3884: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3885: my $home='';
3886:
1.168 albertel 3887: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3888:
1.213 www 3889: $symb=&symbclean($symb);
1.122 albertel 3890: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3891:
1.620 albertel 3892: if (!$domain) { $domain=$env{'user.domain'}; }
3893: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3894:
3895: &devalidate($symb,$stuname,$domain);
1.109 www 3896:
3897: $symb=escape($symb);
1.187 www 3898: if (!$namespace) {
1.620 albertel 3899: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3900: return '';
3901: }
3902: }
1.620 albertel 3903: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3904:
3905: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3906: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3907:
1.47 www 3908: my $namevalue='';
1.800 albertel 3909: foreach my $key (keys(%$storehash)) {
3910: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3911: }
1.47 www 3912: $namevalue=~s/\&$//;
1.187 www 3913: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3914: return critical
3915: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3916: }
3917:
1.9 www 3918: # --------------------------------------------------------------------- Restore
3919:
3920: sub restore {
1.124 www 3921: my ($symb,$namespace,$domain,$stuname) = @_;
3922: my $home='';
3923:
1.168 albertel 3924: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3925:
1.122 albertel 3926: if (!$symb) {
3927: unless ($symb=escape(&symbread())) { return ''; }
3928: } else {
1.213 www 3929: $symb=&escape(&symbclean($symb));
1.122 albertel 3930: }
1.188 www 3931: if (!$namespace) {
1.620 albertel 3932: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3933: return '';
3934: }
3935: }
1.620 albertel 3936: if (!$domain) { $domain=$env{'user.domain'}; }
3937: if (!$stuname) { $stuname=$env{'user.name'}; }
3938: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3939: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3940:
1.12 www 3941: my %returnhash=();
1.800 albertel 3942: foreach my $line (split(/\&/,$answer)) {
3943: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3944: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3945: }
1.75 www 3946: my $version;
3947: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3948: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3949: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3950: }
1.75 www 3951: }
1.13 www 3952: return %returnhash;
1.34 www 3953: }
3954:
3955: # ---------------------------------------------------------- Course Description
3956:
3957: sub coursedescription {
1.731 albertel 3958: my ($courseid,$args)=@_;
1.34 www 3959: $courseid=~s/^\///;
1.49 www 3960: $courseid=~s/\_/\//g;
1.34 www 3961: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3962: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3963: my $normalid=$cdomain.'_'.$cnum;
3964: # need to always cache even if we get errors otherwise we keep
3965: # trying and trying and trying to get the course description.
3966: my %envhash=();
3967: my %returnhash=();
1.731 albertel 3968:
3969: my $expiretime=600;
3970: if ($env{'request.course.id'} eq $normalid) {
3971: $expiretime=120;
3972: }
3973:
3974: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3975: if (!$args->{'freshen_cache'}
3976: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3977: foreach my $key (keys(%env)) {
3978: next if ($key !~ /^\Q$prefix\E(.*)/);
3979: my ($setting) = $1;
3980: $returnhash{$setting} = $env{$key};
3981: }
3982: return %returnhash;
3983: }
3984:
3985: # get the data agin
3986: if (!$args->{'one_time'}) {
3987: $envhash{'course.'.$normalid.'.last_cache'}=time;
3988: }
1.811 albertel 3989:
1.34 www 3990: if ($chome ne 'no_host') {
1.302 albertel 3991: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3992: if (!exists($returnhash{'con_lost'})) {
3993: $returnhash{'home'}= $chome;
3994: $returnhash{'domain'} = $cdomain;
3995: $returnhash{'num'} = $cnum;
1.741 raeburn 3996: if (!defined($returnhash{'type'})) {
3997: $returnhash{'type'} = 'Course';
3998: }
1.130 albertel 3999: while (my ($name,$value) = each %returnhash) {
1.53 www 4000: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4001: }
1.270 www 4002: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4003: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4004: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4005: $envhash{'course.'.$normalid.'.home'}=$chome;
4006: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4007: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4008: }
4009: }
1.731 albertel 4010: if (!$args->{'one_time'}) {
1.949 raeburn 4011: &appenv(\%envhash);
1.731 albertel 4012: }
1.302 albertel 4013: return %returnhash;
1.461 www 4014: }
4015:
4016: # -------------------------------------------------See if a user is privileged
4017:
4018: sub privileged {
4019: my ($username,$domain)=@_;
4020: my $rolesdump=&reply("dump:$domain:$username:roles",
4021: &homeserver($username,$domain));
1.1033 raeburn 4022: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4023: ($rolesdump =~ /^error:/)) {
4024: return 0;
4025: }
1.461 www 4026: my $now=time;
4027: if ($rolesdump ne '') {
1.800 albertel 4028: foreach my $entry (split(/&/,$rolesdump)) {
4029: if ($entry!~/^rolesdef_/) {
4030: my ($area,$role)=split(/=/,$entry);
1.461 www 4031: $area=~s/\_\w\w$//;
4032: my ($trole,$tend,$tstart)=split(/_/,$role);
4033: if (($trole eq 'dc') || ($trole eq 'su')) {
4034: my $active=1;
4035: if ($tend) {
4036: if ($tend<$now) { $active=0; }
4037: }
4038: if ($tstart) {
4039: if ($tstart>$now) { $active=0; }
4040: }
4041: if ($active) { return 1; }
4042: }
4043: }
4044: }
4045: }
4046: return 0;
1.9 www 4047: }
1.1 albertel 4048:
1.103 harris41 4049: # -------------------------------------------------------- Get user privileges
1.11 www 4050:
4051: sub rolesinit {
4052: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4053: my $now=time;
4054: my %userroles = ('user.login.time' => $now);
1.1056.4.3 raeburn 4055: my $extra = &freeze_escape({'clientcheckrole' => 1});
4056: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4057: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4058: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4059: return \%userroles;
4060: }
1.11 www 4061: my %allroles=();
1.678 raeburn 4062: my %allgroups=();
4063: my $group_privs;
1.11 www 4064:
4065: if ($rolesdump ne '') {
1.800 albertel 4066: foreach my $entry (split(/&/,$rolesdump)) {
4067: if ($entry!~/^rolesdef_/) {
4068: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4069: $area=~s/\_\w\w$//;
1.678 raeburn 4070: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4071: if ($role=~/^cr/) {
1.807 albertel 4072: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4073: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4074: ($tend,$tstart)=split('_',$trest);
4075: } else {
4076: $trole=$role;
4077: }
1.678 raeburn 4078: } elsif ($role =~ m|^gr/|) {
4079: ($trole,$tend,$tstart) = split(/_/,$role);
4080: ($trole,$group_privs) = split(/\//,$trole);
4081: $group_privs = &unescape($group_privs);
1.587 albertel 4082: } else {
4083: ($trole,$tend,$tstart)=split(/_/,$role);
4084: }
1.743 albertel 4085: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4086: $username);
4087: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4088: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4089: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4090: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4091: my $spec=$trole.'.'.$area;
4092: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4093: if ($trole =~ /^cr\//) {
1.567 raeburn 4094: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4095: } elsif ($trole eq 'gr') {
4096: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4097: } else {
1.567 raeburn 4098: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4099: }
1.12 www 4100: }
1.662 raeburn 4101: }
1.191 harris41 4102: }
1.743 albertel 4103: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4104: $userroles{'user.adv'} = $adv;
4105: $userroles{'user.author'} = $author;
1.620 albertel 4106: $env{'user.adv'}=$adv;
1.11 www 4107: }
1.743 albertel 4108: return \%userroles;
1.11 www 4109: }
4110:
1.567 raeburn 4111: sub set_arearole {
4112: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4113: # log the associated role with the area
4114: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4115: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4116: }
4117:
4118: sub custom_roleprivs {
4119: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4120: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4121: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4122: if (&hostname($homsvr) ne '') {
1.567 raeburn 4123: my ($rdummy,$roledef)=
4124: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4125: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4126: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4127: if (defined($syspriv)) {
1.1043 raeburn 4128: if ($trest =~ /^$match_community$/) {
4129: $syspriv =~ s/bre\&S//;
4130: }
1.567 raeburn 4131: $$allroles{'cm./'}.=':'.$syspriv;
4132: $$allroles{$spec.'./'}.=':'.$syspriv;
4133: }
4134: if ($tdomain ne '') {
4135: if (defined($dompriv)) {
4136: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4137: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4138: }
4139: if (($trest ne '') && (defined($coursepriv))) {
4140: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4141: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4142: }
4143: }
4144: }
4145: }
4146: }
4147:
1.678 raeburn 4148: sub group_roleprivs {
4149: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4150: my $access = 1;
4151: my $now = time;
4152: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4153: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4154: if ($access) {
1.811 albertel 4155: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4156: $$allgroups{$course}{$group} .=':'.$group_privs;
4157: }
4158: }
1.567 raeburn 4159:
4160: sub standard_roleprivs {
4161: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4162: if (defined($pr{$trole.':s'})) {
4163: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4164: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4165: }
4166: if ($tdomain ne '') {
4167: if (defined($pr{$trole.':d'})) {
4168: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4169: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4170: }
4171: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4172: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4173: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4174: }
4175: }
4176: }
4177:
4178: sub set_userprivs {
1.1056.4.2 raeburn 4179: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4180: my $author=0;
4181: my $adv=0;
1.678 raeburn 4182: my %grouproles = ();
4183: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4184: my @groupkeys;
1.1000 raeburn 4185: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4186: push(@groupkeys,$role);
4187: }
4188: if (ref($groups_roles) eq 'HASH') {
4189: foreach my $key (keys(%{$groups_roles})) {
4190: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4191: push(@groupkeys,$key);
4192: }
4193: }
4194: }
4195: if (@groupkeys > 0) {
4196: foreach my $role (@groupkeys) {
4197: my ($trole,$area,$sec,$extendedarea);
4198: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4199: $trole = $1;
4200: $area = $2;
4201: $sec = $3;
4202: $extendedarea = $area.$sec;
4203: if (exists($$allgroups{$area})) {
4204: foreach my $group (keys(%{$$allgroups{$area}})) {
4205: my $spec = $trole.'.'.$extendedarea;
4206: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4207: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4208: }
1.678 raeburn 4209: }
4210: }
4211: }
4212: }
4213: }
1.800 albertel 4214: foreach my $group (keys(%grouproles)) {
4215: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4216: }
1.800 albertel 4217: foreach my $role (keys(%{$allroles})) {
4218: my %thesepriv;
1.941 raeburn 4219: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4220: foreach my $item (split(/:/,$$allroles{$role})) {
4221: if ($item ne '') {
4222: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4223: if ($restrictions eq '') {
4224: $thesepriv{$privilege}='F';
4225: } elsif ($thesepriv{$privilege} ne 'F') {
4226: $thesepriv{$privilege}.=$restrictions;
4227: }
4228: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4229: }
4230: }
4231: my $thesestr='';
1.800 albertel 4232: foreach my $priv (keys(%thesepriv)) {
4233: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4234: }
4235: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4236: }
4237: return ($author,$adv);
4238: }
4239:
1.994 raeburn 4240: sub role_status {
1.1002 raeburn 4241: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4242: my @pwhere = ();
4243: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4244: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4245: unless (!defined($$role) || $$role eq '') {
4246: $$where=join('.',@pwhere);
4247: $$trolecode=$$role.'.'.$$where;
4248: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4249: $$tstatus='is';
4250: if ($$tstart && $$tstart>$then) {
4251: $$tstatus='future';
1.1034 raeburn 4252: if ($$tstart<$now) {
4253: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4254: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4255: my (%allroles,%allgroups,$group_privs,
4256: %groups_roles,@rolecodes);
1.1002 raeburn 4257: my %userroles = (
4258: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4259: );
1.1056.4.2 raeburn 4260: @rolecodes = ('cm');
1.1002 raeburn 4261: my $spec=$$role.'.'.$$where;
4262: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4263: if ($$role =~ /^cr\//) {
4264: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4265: push(@rolecodes,'cr');
1.1002 raeburn 4266: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4267: push(@rolecodes,$$role);
1.1002 raeburn 4268: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4269: $env{'user.name'});
1.1056.4.2 raeburn 4270: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4271:
1.1002 raeburn 4272: (undef,my $group_privs) = split(/\//,$trole);
4273: $group_privs = &unescape($group_privs);
4274: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4275: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4276: if (keys(%course_roles) > 0) {
4277: my ($tnum) = ($trest =~ /^($match_courseid)/);
4278: if ($tdomain ne '' && $tnum ne '') {
4279: foreach my $key (keys(%course_roles)) {
4280: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4281: my $crsrole = $1;
4282: my $crssec = $2;
4283: if ($crsrole =~ /^cr/) {
4284: unless (grep(/^cr$/,@rolecodes)) {
4285: push(@rolecodes,'cr');
4286: }
4287: } else {
4288: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4289: push(@rolecodes,$crsrole);
4290: }
4291: }
4292: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4293: if ($crssec ne '') {
4294: $rolekey .= '/'.$crssec;
4295: }
4296: $rolekey .= './';
4297: $groups_roles{$rolekey} = \@rolecodes;
4298: }
4299: }
4300: }
4301: }
1.1002 raeburn 4302: } else {
1.1056.4.2 raeburn 4303: push(@rolecodes,$$role);
1.1002 raeburn 4304: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4305: }
1.1056.4.2 raeburn 4306: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4307: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4308: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4309: }
4310: }
1.1034 raeburn 4311: $$tstatus = 'is';
1.1002 raeburn 4312: }
1.994 raeburn 4313: }
4314: if ($$tend) {
4315: if ($$tend<$then) {
4316: $$tstatus='expired';
4317: } elsif ($$tend<$now) {
4318: $$tstatus='will_not';
4319: }
4320: }
4321: }
4322: }
4323: }
4324:
4325: sub check_adhoc_privs {
1.1002 raeburn 4326: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4327: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4328: if ($env{$cckey}) {
4329: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4330: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4331: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4332: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4333: }
4334: } else {
4335: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4336: }
4337: }
4338:
4339: sub set_adhoc_privileges {
4340: # role can be cc or ca
4341: my ($dcdom,$pickedcourse,$role) = @_;
4342: my $area = '/'.$dcdom.'/'.$pickedcourse;
4343: my $spec = $role.'.'.$area;
4344: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4345: $env{'user.name'});
4346: my %ccrole = ();
4347: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4348: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4349: &appenv(\%userroles,[$role,'cm']);
4350: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4351: &appenv( {'request.role' => $spec,
4352: 'request.role.domain' => $dcdom,
4353: 'request.course.sec' => ''
4354: }
4355: );
4356: my $tadv=0;
4357: if (&allowed('adv') eq 'F') { $tadv=1; }
4358: &appenv({'request.role.adv' => $tadv});
4359: }
4360:
1.12 www 4361: # --------------------------------------------------------------- get interface
4362:
4363: sub get {
1.131 albertel 4364: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4365: my $items='';
1.800 albertel 4366: foreach my $item (@$storearr) {
4367: $items.=&escape($item).'&';
1.191 harris41 4368: }
1.12 www 4369: $items=~s/\&$//;
1.620 albertel 4370: if (!$udomain) { $udomain=$env{'user.domain'}; }
4371: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4372: my $uhome=&homeserver($uname,$udomain);
4373:
1.133 albertel 4374: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4375: my @pairs=split(/\&/,$rep);
1.273 albertel 4376: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4377: return @pairs;
4378: }
1.15 www 4379: my %returnhash=();
1.42 www 4380: my $i=0;
1.800 albertel 4381: foreach my $item (@$storearr) {
4382: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4383: $i++;
1.191 harris41 4384: }
1.15 www 4385: return %returnhash;
1.27 www 4386: }
4387:
4388: # --------------------------------------------------------------- del interface
4389:
4390: sub del {
1.133 albertel 4391: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4392: my $items='';
1.800 albertel 4393: foreach my $item (@$storearr) {
4394: $items.=&escape($item).'&';
1.191 harris41 4395: }
1.984 neumanie 4396:
1.27 www 4397: $items=~s/\&$//;
1.620 albertel 4398: if (!$udomain) { $udomain=$env{'user.domain'}; }
4399: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4400: my $uhome=&homeserver($uname,$udomain);
4401: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4402: }
4403:
4404: # -------------------------------------------------------------- dump interface
4405:
4406: sub dump {
1.755 albertel 4407: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4408: if (!$udomain) { $udomain=$env{'user.domain'}; }
4409: if (!$uname) { $uname=$env{'user.name'}; }
4410: my $uhome=&homeserver($uname,$udomain);
4411: if ($regexp) {
4412: $regexp=&escape($regexp);
4413: } else {
4414: $regexp='.';
4415: }
4416: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4417: my @pairs=split(/\&/,$rep);
4418: my %returnhash=();
4419: foreach my $item (@pairs) {
4420: my ($key,$value)=split(/=/,$item,2);
4421: $key = &unescape($key);
4422: next if ($key =~ /^error: 2 /);
4423: $returnhash{$key}=&thaw_unescape($value);
4424: }
4425: return %returnhash;
1.407 www 4426: }
4427:
1.717 albertel 4428: # --------------------------------------------------------- dumpstore interface
4429:
4430: sub dumpstore {
4431: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4432: if (!$udomain) { $udomain=$env{'user.domain'}; }
4433: if (!$uname) { $uname=$env{'user.name'}; }
4434: my $uhome=&homeserver($uname,$udomain);
4435: if ($regexp) {
4436: $regexp=&escape($regexp);
4437: } else {
4438: $regexp='.';
4439: }
4440: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4441: my @pairs=split(/\&/,$rep);
4442: my %returnhash=();
4443: foreach my $item (@pairs) {
4444: my ($key,$value)=split(/=/,$item,2);
4445: next if ($key =~ /^error: 2 /);
4446: $returnhash{$key}=&thaw_unescape($value);
4447: }
4448: return %returnhash;
1.717 albertel 4449: }
4450:
1.407 www 4451: # -------------------------------------------------------------- keys interface
4452:
4453: sub getkeys {
4454: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4455: if (!$udomain) { $udomain=$env{'user.domain'}; }
4456: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4457: my $uhome=&homeserver($uname,$udomain);
4458: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4459: my @keyarray=();
1.800 albertel 4460: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4461: next if ($key =~ /^error: 2 /);
1.800 albertel 4462: push(@keyarray,&unescape($key));
1.407 www 4463: }
4464: return @keyarray;
1.318 matthew 4465: }
4466:
1.319 matthew 4467: # --------------------------------------------------------------- currentdump
4468: sub currentdump {
1.328 matthew 4469: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4470: $courseid = $env{'request.course.id'} if (! defined($courseid));
4471: $sdom = $env{'user.domain'} if (! defined($sdom));
4472: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4473: my $uhome = &homeserver($sname,$sdom);
4474: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4475: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4476: #
1.318 matthew 4477: my %returnhash=();
1.319 matthew 4478: #
4479: if ($rep eq "unknown_cmd") {
4480: # an old lond will not know currentdump
4481: # Do a dump and make it look like a currentdump
1.822 albertel 4482: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4483: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4484: my %hash = @tmp;
4485: @tmp=();
1.424 matthew 4486: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4487: } else {
4488: my @pairs=split(/\&/,$rep);
1.800 albertel 4489: foreach my $pair (@pairs) {
4490: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4491: my ($symb,$param) = split(/:/,$key);
4492: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4493: &thaw_unescape($value);
1.319 matthew 4494: }
1.191 harris41 4495: }
1.12 www 4496: return %returnhash;
1.424 matthew 4497: }
4498:
4499: sub convert_dump_to_currentdump{
4500: my %hash = %{shift()};
4501: my %returnhash;
4502: # Code ripped from lond, essentially. The only difference
4503: # here is the unescaping done by lonnet::dump(). Conceivably
4504: # we might run in to problems with parameter names =~ /^v\./
4505: while (my ($key,$value) = each(%hash)) {
4506: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4507: $symb = &unescape($symb);
4508: $param = &unescape($param);
1.424 matthew 4509: next if ($v eq 'version' || $symb eq 'keys');
4510: next if (exists($returnhash{$symb}) &&
4511: exists($returnhash{$symb}->{$param}) &&
4512: $returnhash{$symb}->{'v.'.$param} > $v);
4513: $returnhash{$symb}->{$param}=$value;
4514: $returnhash{$symb}->{'v.'.$param}=$v;
4515: }
4516: #
4517: # Remove all of the keys in the hashes which keep track of
4518: # the version of the parameter.
4519: while (my ($symb,$param_hash) = each(%returnhash)) {
4520: # use a foreach because we are going to delete from the hash.
4521: foreach my $key (keys(%$param_hash)) {
4522: delete($param_hash->{$key}) if ($key =~ /^v\./);
4523: }
4524: }
4525: return \%returnhash;
1.12 www 4526: }
4527:
1.627 albertel 4528: # ------------------------------------------------------ critical inc interface
4529:
4530: sub cinc {
4531: return &inc(@_,'critical');
4532: }
4533:
1.449 matthew 4534: # --------------------------------------------------------------- inc interface
4535:
4536: sub inc {
1.627 albertel 4537: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4538: if (!$udomain) { $udomain=$env{'user.domain'}; }
4539: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4540: my $uhome=&homeserver($uname,$udomain);
4541: my $items='';
4542: if (! ref($store)) {
4543: # got a single value, so use that instead
4544: $items = &escape($store).'=&';
4545: } elsif (ref($store) eq 'SCALAR') {
4546: $items = &escape($$store).'=&';
4547: } elsif (ref($store) eq 'ARRAY') {
4548: $items = join('=&',map {&escape($_);} @{$store});
4549: } elsif (ref($store) eq 'HASH') {
4550: while (my($key,$value) = each(%{$store})) {
4551: $items.= &escape($key).'='.&escape($value).'&';
4552: }
4553: }
4554: $items=~s/\&$//;
1.627 albertel 4555: if ($critical) {
4556: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4557: } else {
4558: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4559: }
1.449 matthew 4560: }
4561:
1.12 www 4562: # --------------------------------------------------------------- put interface
4563:
4564: sub put {
1.134 albertel 4565: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4566: if (!$udomain) { $udomain=$env{'user.domain'}; }
4567: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4568: my $uhome=&homeserver($uname,$udomain);
1.12 www 4569: my $items='';
1.800 albertel 4570: foreach my $item (keys(%$storehash)) {
4571: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4572: }
1.12 www 4573: $items=~s/\&$//;
1.134 albertel 4574: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4575: }
4576:
1.631 albertel 4577: # ------------------------------------------------------------ newput interface
4578:
4579: sub newput {
4580: my ($namespace,$storehash,$udomain,$uname)=@_;
4581: if (!$udomain) { $udomain=$env{'user.domain'}; }
4582: if (!$uname) { $uname=$env{'user.name'}; }
4583: my $uhome=&homeserver($uname,$udomain);
4584: my $items='';
4585: foreach my $key (keys(%$storehash)) {
4586: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4587: }
4588: $items=~s/\&$//;
4589: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4590: }
4591:
4592: # --------------------------------------------------------- putstore interface
4593:
1.524 raeburn 4594: sub putstore {
1.715 albertel 4595: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4596: if (!$udomain) { $udomain=$env{'user.domain'}; }
4597: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4598: my $uhome=&homeserver($uname,$udomain);
4599: my $items='';
1.715 albertel 4600: foreach my $key (keys(%$storehash)) {
4601: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4602: }
1.715 albertel 4603: $items=~s/\&$//;
1.716 albertel 4604: my $esc_symb=&escape($symb);
4605: my $esc_v=&escape($version);
1.715 albertel 4606: my $reply =
1.716 albertel 4607: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4608: $uhome);
4609: if ($reply eq 'unknown_cmd') {
1.716 albertel 4610: # gfall back to way things use to be done
1.715 albertel 4611: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4612: $uname);
1.524 raeburn 4613: }
1.715 albertel 4614: return $reply;
4615: }
4616:
4617: sub old_putstore {
1.716 albertel 4618: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4619: if (!$udomain) { $udomain=$env{'user.domain'}; }
4620: if (!$uname) { $uname=$env{'user.name'}; }
4621: my $uhome=&homeserver($uname,$udomain);
4622: my %newstorehash;
1.800 albertel 4623: foreach my $item (keys(%$storehash)) {
4624: my $key = $version.':'.&escape($symb).':'.$item;
4625: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4626: }
4627: my $items='';
4628: my %allitems = ();
1.800 albertel 4629: foreach my $item (keys(%newstorehash)) {
4630: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4631: my $key = $1.':keys:'.$2;
4632: $allitems{$key} .= $3.':';
4633: }
1.800 albertel 4634: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4635: }
1.800 albertel 4636: foreach my $item (keys(%allitems)) {
4637: $allitems{$item} =~ s/\:$//;
4638: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4639: }
4640: $items=~s/\&$//;
4641: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4642: }
4643:
1.47 www 4644: # ------------------------------------------------------ critical put interface
4645:
4646: sub cput {
1.134 albertel 4647: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4648: if (!$udomain) { $udomain=$env{'user.domain'}; }
4649: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4650: my $uhome=&homeserver($uname,$udomain);
1.47 www 4651: my $items='';
1.800 albertel 4652: foreach my $item (keys(%$storehash)) {
4653: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4654: }
1.47 www 4655: $items=~s/\&$//;
1.134 albertel 4656: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4657: }
4658:
4659: # -------------------------------------------------------------- eget interface
4660:
4661: sub eget {
1.133 albertel 4662: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4663: my $items='';
1.800 albertel 4664: foreach my $item (@$storearr) {
4665: $items.=&escape($item).'&';
1.191 harris41 4666: }
1.12 www 4667: $items=~s/\&$//;
1.620 albertel 4668: if (!$udomain) { $udomain=$env{'user.domain'}; }
4669: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4670: my $uhome=&homeserver($uname,$udomain);
4671: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4672: my @pairs=split(/\&/,$rep);
4673: my %returnhash=();
1.42 www 4674: my $i=0;
1.800 albertel 4675: foreach my $item (@$storearr) {
4676: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4677: $i++;
1.191 harris41 4678: }
1.12 www 4679: return %returnhash;
4680: }
4681:
1.667 albertel 4682: # ------------------------------------------------------------ tmpput interface
4683: sub tmpput {
1.802 raeburn 4684: my ($storehash,$server,$context)=@_;
1.667 albertel 4685: my $items='';
1.800 albertel 4686: foreach my $item (keys(%$storehash)) {
4687: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4688: }
4689: $items=~s/\&$//;
1.802 raeburn 4690: if (defined($context)) {
4691: $items .= ':'.&escape($context);
4692: }
1.667 albertel 4693: return &reply("tmpput:$items",$server);
4694: }
4695:
4696: # ------------------------------------------------------------ tmpget interface
4697: sub tmpget {
1.688 albertel 4698: my ($token,$server)=@_;
4699: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4700: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4701: my %returnhash;
4702: foreach my $item (split(/\&/,$rep)) {
4703: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4704: next if ($key =~ /^error: 2 /);
1.667 albertel 4705: $returnhash{&unescape($key)}=&thaw_unescape($value);
4706: }
4707: return %returnhash;
4708: }
4709:
1.688 albertel 4710: # ------------------------------------------------------------ tmpget interface
4711: sub tmpdel {
4712: my ($token,$server)=@_;
4713: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4714: return &reply("tmpdel:$token",$server);
4715: }
4716:
1.765 albertel 4717: # -------------------------------------------------- portfolio access checking
4718:
4719: sub portfolio_access {
1.766 albertel 4720: my ($requrl) = @_;
1.765 albertel 4721: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4722: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4723: if ($result) {
4724: my %setters;
4725: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4726: my ($startblock,$endblock) =
4727: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4728: if ($startblock && $endblock) {
4729: return 'B';
4730: }
4731: } else {
4732: my ($startblock,$endblock) =
4733: &Apache::loncommon::blockcheck(\%setters,'port');
4734: if ($startblock && $endblock) {
4735: return 'B';
4736: }
4737: }
4738: }
1.765 albertel 4739: if ($result eq 'ok') {
1.766 albertel 4740: return 'F';
1.765 albertel 4741: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4742: return 'A';
1.765 albertel 4743: }
1.766 albertel 4744: return '';
1.765 albertel 4745: }
4746:
4747: sub get_portfolio_access {
1.767 albertel 4748: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4749:
4750: if (!ref($access_hash)) {
4751: my $current_perms = &get_portfile_permissions($udom,$unum);
4752: my %access_controls = &get_access_controls($current_perms,$group,
4753: $file_name);
4754: $access_hash = $access_controls{$file_name};
4755: }
4756:
1.765 albertel 4757: my ($public,$guest,@domains,@users,@courses,@groups);
4758: my $now = time;
4759: if (ref($access_hash) eq 'HASH') {
4760: foreach my $key (keys(%{$access_hash})) {
4761: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4762: if ($start > $now) {
4763: next;
4764: }
4765: if ($end && $end<$now) {
4766: next;
4767: }
4768: if ($scope eq 'public') {
4769: $public = $key;
4770: last;
4771: } elsif ($scope eq 'guest') {
4772: $guest = $key;
4773: } elsif ($scope eq 'domains') {
4774: push(@domains,$key);
4775: } elsif ($scope eq 'users') {
4776: push(@users,$key);
4777: } elsif ($scope eq 'course') {
4778: push(@courses,$key);
4779: } elsif ($scope eq 'group') {
4780: push(@groups,$key);
4781: }
4782: }
4783: if ($public) {
4784: return 'ok';
4785: }
4786: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4787: if ($guest) {
4788: return $guest;
4789: }
4790: } else {
4791: if (@domains > 0) {
4792: foreach my $domkey (@domains) {
4793: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4794: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4795: return 'ok';
4796: }
4797: }
4798: }
4799: }
4800: if (@users > 0) {
4801: foreach my $userkey (@users) {
1.865 raeburn 4802: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4803: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4804: if (ref($item) eq 'HASH') {
4805: if (($item->{'uname'} eq $env{'user.name'}) &&
4806: ($item->{'udom'} eq $env{'user.domain'})) {
4807: return 'ok';
4808: }
4809: }
4810: }
4811: }
1.765 albertel 4812: }
4813: }
4814: my %roleshash;
4815: my @courses_and_groups = @courses;
4816: push(@courses_and_groups,@groups);
4817: if (@courses_and_groups > 0) {
4818: my (%allgroups,%allroles);
4819: my ($start,$end,$role,$sec,$group);
4820: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4821: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4822: my $cid = $2.'_'.$3;
4823: if ($1 eq 'gr') {
4824: $group = $4;
4825: $allgroups{$cid}{$group} = $env{$envkey};
4826: } else {
4827: if ($4 eq '') {
4828: $sec = 'none';
4829: } else {
4830: $sec = $4;
4831: }
4832: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4833: }
1.811 albertel 4834: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4835: my $cid = $2.'_'.$3;
4836: if ($4 eq '') {
4837: $sec = 'none';
4838: } else {
4839: $sec = $4;
4840: }
4841: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4842: }
4843: }
4844: if (keys(%allroles) == 0) {
4845: return;
4846: }
4847: foreach my $key (@courses_and_groups) {
4848: my %content = %{$$access_hash{$key}};
4849: my $cnum = $content{'number'};
4850: my $cdom = $content{'domain'};
4851: my $cid = $cdom.'_'.$cnum;
4852: if (!exists($allroles{$cid})) {
4853: next;
4854: }
4855: foreach my $role_id (keys(%{$content{'roles'}})) {
4856: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4857: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4858: my @status = @{$content{'roles'}{$role_id}{'access'}};
4859: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4860: foreach my $role (keys(%{$allroles{$cid}})) {
4861: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4862: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4863: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4864: if (grep/^all$/,@sections) {
4865: return 'ok';
4866: } else {
4867: if (grep/^$sec$/,@sections) {
4868: return 'ok';
4869: }
4870: }
4871: }
4872: }
4873: if (keys(%{$allgroups{$cid}}) == 0) {
4874: if (grep/^none$/,@groups) {
4875: return 'ok';
4876: }
4877: } else {
4878: if (grep/^all$/,@groups) {
4879: return 'ok';
4880: }
4881: foreach my $group (keys(%{$allgroups{$cid}})) {
4882: if (grep/^$group$/,@groups) {
4883: return 'ok';
4884: }
4885: }
4886: }
4887: }
4888: }
4889: }
4890: }
4891: }
4892: if ($guest) {
4893: return $guest;
4894: }
4895: }
4896: }
4897: return;
4898: }
4899:
4900: sub course_group_datechecker {
4901: my ($dates,$now,$status) = @_;
4902: my ($start,$end) = split(/\./,$dates);
4903: if (!$start && !$end) {
4904: return 'ok';
4905: }
4906: if (grep/^active$/,@{$status}) {
4907: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4908: return 'ok';
4909: }
4910: }
4911: if (grep/^previous$/,@{$status}) {
4912: if ($end > $now ) {
4913: return 'ok';
4914: }
4915: }
4916: if (grep/^future$/,@{$status}) {
4917: if ($start > $now) {
4918: return 'ok';
4919: }
4920: }
4921: return;
4922: }
4923:
4924: sub parse_portfolio_url {
4925: my ($url) = @_;
4926:
4927: my ($type,$udom,$unum,$group,$file_name);
4928:
1.823 albertel 4929: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4930: $type = 1;
4931: $udom = $1;
4932: $unum = $2;
4933: $file_name = $3;
1.823 albertel 4934: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4935: $type = 2;
4936: $udom = $1;
4937: $unum = $2;
4938: $group = $3;
4939: $file_name = $3.'/'.$4;
4940: }
4941: if (wantarray) {
4942: return ($type,$udom,$unum,$file_name,$group);
4943: }
4944: return $type;
4945: }
4946:
4947: sub is_portfolio_url {
4948: my ($url) = @_;
4949: return scalar(&parse_portfolio_url($url));
4950: }
4951:
1.798 raeburn 4952: sub is_portfolio_file {
4953: my ($file) = @_;
1.820 raeburn 4954: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4955: return 1;
4956: }
4957: return;
4958: }
4959:
1.976 raeburn 4960: sub usertools_access {
1.985 raeburn 4961: my ($uname,$udom,$tool,$action,$context) = @_;
4962: my ($access,%tools);
4963: if ($context eq '') {
4964: $context = 'tools';
4965: }
4966: if ($context eq 'requestcourses') {
4967: %tools = (
4968: official => 1,
4969: unofficial => 1,
1.1006 raeburn 4970: community => 1,
1.985 raeburn 4971: );
4972: } else {
4973: %tools = (
4974: aboutme => 1,
4975: blog => 1,
4976: portfolio => 1,
4977: );
4978: }
1.976 raeburn 4979: return if (!defined($tools{$tool}));
4980:
4981: if ((!defined($udom)) || (!defined($uname))) {
4982: $udom = $env{'user.domain'};
4983: $uname = $env{'user.name'};
4984: }
4985:
1.978 raeburn 4986: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4987: if ($action ne 'reload') {
1.985 raeburn 4988: if ($context eq 'requestcourses') {
4989: return $env{'environment.canrequest.'.$tool};
4990: } else {
4991: return $env{'environment.availabletools.'.$tool};
4992: }
4993: }
1.976 raeburn 4994: }
4995:
4996: my ($toolstatus,$inststatus);
4997:
1.985 raeburn 4998: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4999: ($action ne 'reload')) {
5000: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5001: $inststatus = $env{'environment.inststatus'};
5002: } else {
1.1025 raeburn 5003: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 5004: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 5005: $inststatus = $userenv{'inststatus'};
5006: }
5007:
5008: if ($toolstatus ne '') {
5009: if ($toolstatus) {
5010: $access = 1;
5011: } else {
5012: $access = 0;
5013: }
5014: return $access;
5015: }
5016:
5017: my $is_adv = &is_advanced_user($udom,$uname);
5018: my %domdef = &get_domain_defaults($udom);
5019: if (ref($domdef{$tool}) eq 'HASH') {
5020: if ($is_adv) {
5021: if ($domdef{$tool}{'_LC_adv'} ne '') {
5022: if ($domdef{$tool}{'_LC_adv'}) {
5023: $access = 1;
5024: } else {
5025: $access = 0;
5026: }
5027: return $access;
5028: }
5029: }
5030: if ($inststatus ne '') {
5031: my ($hasaccess,$hasnoaccess);
5032: foreach my $affiliation (split(/:/,$inststatus)) {
5033: if ($domdef{$tool}{$affiliation} ne '') {
5034: if ($domdef{$tool}{$affiliation}) {
5035: $hasaccess = 1;
5036: } else {
5037: $hasnoaccess = 1;
5038: }
5039: }
5040: }
5041: if ($hasaccess || $hasnoaccess) {
5042: if ($hasaccess) {
5043: $access = 1;
5044: } elsif ($hasnoaccess) {
5045: $access = 0;
5046: }
5047: return $access;
5048: }
5049: } else {
5050: if ($domdef{$tool}{'default'} ne '') {
5051: if ($domdef{$tool}{'default'}) {
5052: $access = 1;
5053: } elsif ($domdef{$tool}{'default'} == 0) {
5054: $access = 0;
5055: }
5056: return $access;
5057: }
5058: }
5059: } else {
1.985 raeburn 5060: if ($context eq 'tools') {
5061: $access = 1;
5062: } else {
5063: $access = 0;
5064: }
1.976 raeburn 5065: return $access;
5066: }
5067: }
5068:
1.1050 raeburn 5069: sub is_course_owner {
5070: my ($cdom,$cnum,$udom,$uname) = @_;
5071: if (($udom eq '') || ($uname eq '')) {
5072: $udom = $env{'user.domain'};
5073: $uname = $env{'user.name'};
5074: }
5075: unless (($udom eq '') || ($uname eq '')) {
5076: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5077: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5078: return 1;
5079: } else {
5080: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5081: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5082: return 1;
5083: }
5084: }
5085: }
5086: }
5087: return;
5088: }
5089:
1.976 raeburn 5090: sub is_advanced_user {
5091: my ($udom,$uname) = @_;
5092: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5093: my %allroles;
5094: my $is_adv;
5095: foreach my $role (keys(%roleshash)) {
5096: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5097: my $area = '/'.$tdomain.'/'.$trest;
5098: if ($sec ne '') {
5099: $area .= '/'.$sec;
5100: }
5101: if (($area ne '') && ($trole ne '')) {
5102: my $spec=$trole.'.'.$area;
5103: if ($trole =~ /^cr\//) {
5104: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5105: } elsif ($trole ne 'gr') {
5106: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5107: }
5108: }
5109: }
5110: foreach my $role (keys(%allroles)) {
5111: last if ($is_adv);
5112: foreach my $item (split(/:/,$allroles{$role})) {
5113: if ($item ne '') {
5114: my ($privilege,$restrictions)=split(/&/,$item);
5115: if ($privilege eq 'adv') {
5116: $is_adv = 1;
5117: last;
5118: }
5119: }
5120: }
5121: }
5122: return $is_adv;
5123: }
1.798 raeburn 5124:
1.1035 raeburn 5125: sub check_can_request {
1.1036 raeburn 5126: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5127: my $canreq = 0;
5128: my ($types,$typename) = &Apache::loncommon::course_types();
5129: my @options = ('approval','validate','autolimit');
5130: my $optregex = join('|',@options);
5131: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5132: foreach my $type (@{$types}) {
5133: if (&usertools_access($env{'user.name'},
5134: $env{'user.domain'},
5135: $type,undef,'requestcourses')) {
5136: $canreq ++;
1.1036 raeburn 5137: if (ref($request_domains) eq 'HASH') {
5138: push(@{$request_domains->{$type}},$env{'user.domain'});
5139: }
1.1035 raeburn 5140: if ($dom eq $env{'user.domain'}) {
5141: $can_request->{$type} = 1;
5142: }
5143: }
5144: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5145: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5146: if (@curr > 0) {
1.1036 raeburn 5147: foreach my $item (@curr) {
5148: if (ref($request_domains) eq 'HASH') {
5149: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5150: if ($otherdom ne '') {
5151: if (ref($request_domains->{$type}) eq 'ARRAY') {
5152: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5153: push(@{$request_domains->{$type}},$otherdom);
5154: }
5155: } else {
5156: push(@{$request_domains->{$type}},$otherdom);
5157: }
5158: }
5159: }
5160: }
5161: unless($dom eq $env{'user.domain'}) {
5162: $canreq ++;
1.1035 raeburn 5163: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5164: $can_request->{$type} = 1;
5165: }
5166: }
5167: }
5168: }
5169: }
5170: }
5171: return $canreq;
5172: }
5173:
1.341 www 5174: # ---------------------------------------------- Custom access rule evaluation
5175:
5176: sub customaccess {
5177: my ($priv,$uri)=@_;
1.807 albertel 5178: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5179: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5180: $udom = &LONCAPA::clean_domain($udom);
5181: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5182: my $access=0;
1.800 albertel 5183: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5184: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5185: if ($type eq 'user') {
5186: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5187: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5188: if ($tdom) {
5189: if ($tdom ne $env{'user.domain'}) { next; }
5190: }
1.896 albertel 5191: if ($tuname) {
5192: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5193: }
5194: $access=($effect eq 'allow');
5195: last;
5196: }
5197: } else {
5198: if ($role) {
5199: if ($role ne $urole) { next; }
5200: }
5201: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5202: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5203: if ($tdom) {
5204: if ($tdom ne $udom) { next; }
5205: }
5206: if ($tcrs) {
5207: if ($tcrs ne $ucrs) { next; }
5208: }
5209: if ($tsec) {
5210: if ($tsec ne $usec) { next; }
5211: }
5212: $access=($effect eq 'allow');
5213: last;
5214: }
5215: if ($realm eq '' && $role eq '') {
5216: $access=($effect eq 'allow');
5217: }
1.402 bowersj2 5218: }
1.341 www 5219: }
5220: return $access;
5221: }
5222:
1.103 harris41 5223: # ------------------------------------------------- Check for a user privilege
1.12 www 5224:
5225: sub allowed {
1.810 raeburn 5226: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5227: my $ver_orguri=$uri;
1.439 www 5228: $uri=&deversion($uri);
1.152 www 5229: my $orguri=$uri;
1.52 www 5230: $uri=&declutter($uri);
1.809 raeburn 5231:
1.810 raeburn 5232: if ($priv eq 'evb') {
5233: # Evade communication block restrictions for specified role in a course
5234: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5235: return $1;
5236: } else {
5237: return;
5238: }
5239: }
5240:
1.620 albertel 5241: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5242: # Free bre access to adm and meta resources
1.775 albertel 5243: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5244: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5245: && ($priv eq 'bre')) {
1.14 www 5246: return 'F';
1.159 www 5247: }
5248:
1.545 banghart 5249: # Free bre access to user's own portfolio contents
1.714 raeburn 5250: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5251: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5252: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5253: my %setters;
5254: my ($startblock,$endblock) =
5255: &Apache::loncommon::blockcheck(\%setters,'port');
5256: if ($startblock && $endblock) {
5257: return 'B';
5258: } else {
5259: return 'F';
5260: }
1.545 banghart 5261: }
5262:
1.762 raeburn 5263: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5264: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5265: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5266: if (exists($env{'request.course.id'})) {
5267: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5268: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5269: if (($domain eq $cdom) && ($name eq $cnum)) {
5270: my $courseprivid=$env{'request.course.id'};
5271: $courseprivid=~s/\_/\//;
5272: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5273: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5274: return $1;
1.762 raeburn 5275: } else {
5276: if ($env{'request.course.sec'}) {
5277: $courseprivid.='/'.$env{'request.course.sec'};
5278: }
5279: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5280: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5281: return $2;
5282: }
1.714 raeburn 5283: }
5284: }
5285: }
5286: }
5287:
1.159 www 5288: # Free bre to public access
5289:
5290: if ($priv eq 'bre') {
1.238 www 5291: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5292: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5293: return 'F';
5294: }
1.238 www 5295: if ($copyright eq 'priv') {
5296: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5297: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5298: return '';
5299: }
5300: }
5301: if ($copyright eq 'domain') {
5302: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5303: unless (($env{'user.domain'} eq $1) ||
5304: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5305: return '';
5306: }
1.262 matthew 5307: }
1.620 albertel 5308: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5309: # Library role, so allow browsing of resources in this domain.
5310: return 'F';
1.238 www 5311: }
1.341 www 5312: if ($copyright eq 'custom') {
5313: unless (&customaccess($priv,$uri)) { return ''; }
5314: }
1.14 www 5315: }
1.264 matthew 5316: # Domain coordinator is trying to create a course
1.620 albertel 5317: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5318: # uri is the requested domain in this case.
5319: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5320: # a role of dc for the domain in question.
1.620 albertel 5321: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5322: }
1.29 www 5323:
1.52 www 5324: my $thisallowed='';
5325: my $statecond=0;
5326: my $courseprivid='';
5327:
1.1039 raeburn 5328: my $ownaccess;
1.1043 raeburn 5329: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5330: if (($priv eq 'bro') && ($env{'user.author'})) {
5331: if ($uri eq '') {
5332: $ownaccess = 1;
5333: } else {
5334: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5335: my $udom = $env{'user.domain'};
5336: my $uname = $env{'user.name'};
5337: if ($uri =~ m{^\Q$udom\E/?$}) {
5338: $ownaccess = 1;
1.1040 raeburn 5339: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5340: unless ($uri =~ m{\.\./}) {
5341: $ownaccess = 1;
5342: }
5343: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5344: my $now = time;
5345: if ($uri =~ m{^([^/]+)/?$}) {
5346: my $adom = $1;
5347: foreach my $key (keys(%env)) {
1.1042 raeburn 5348: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5349: my ($start,$end) = split('.',$env{$key});
5350: if (($now >= $start) && (!$end || $end < $now)) {
5351: $ownaccess = 1;
5352: last;
5353: }
5354: }
5355: }
5356: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5357: my $adom = $1;
5358: my $aname = $2;
1.1042 raeburn 5359: foreach my $role ('ca','aa') {
5360: if ($env{"user.role.$role./$adom/$aname"}) {
5361: my ($start,$end) =
5362: split('.',$env{"user.role.$role./$adom/$aname"});
5363: if (($now >= $start) && (!$end || $end < $now)) {
5364: $ownaccess = 1;
5365: last;
5366: }
1.1039 raeburn 5367: }
5368: }
5369: }
5370: }
5371: }
5372: }
5373: }
5374:
1.52 www 5375: # Course
5376:
1.620 albertel 5377: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5378: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5379: $thisallowed.=$1;
5380: }
1.52 www 5381: }
1.29 www 5382:
1.52 www 5383: # Domain
5384:
1.620 albertel 5385: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5386: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5387: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5388: $thisallowed.=$1;
5389: }
1.12 www 5390: }
1.52 www 5391:
5392: # Course: uri itself is a course
1.66 www 5393: my $courseuri=$uri;
5394: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5395: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5396:
1.620 albertel 5397: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5398: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5399: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5400: $thisallowed.=$1;
5401: }
1.12 www 5402: }
1.29 www 5403:
1.665 albertel 5404: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5405: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5406: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5407: $thisallowed='';
1.671 raeburn 5408: my ($match)=&is_on_map($uri);
5409: if ($match) {
5410: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5411: =~/\Q$priv\E\&([^\:]*)/) {
5412: $thisallowed.=$1;
5413: }
5414: } else {
1.705 albertel 5415: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5416: if ($refuri) {
5417: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5418: $thisallowed='F';
1.671 raeburn 5419: } else {
5420: $refuri=&declutter($refuri);
5421: my ($match) = &is_on_map($refuri);
5422: if ($match) {
5423: $thisallowed='F';
5424: }
1.669 raeburn 5425: }
1.671 raeburn 5426: }
5427: }
1.314 www 5428: }
1.492 albertel 5429:
1.766 albertel 5430: if ($priv eq 'bre'
5431: && $thisallowed ne 'F'
5432: && $thisallowed ne '2'
5433: && &is_portfolio_url($uri)) {
5434: $thisallowed = &portfolio_access($uri);
5435: }
5436:
1.52 www 5437: # Full access at system, domain or course-wide level? Exit.
1.29 www 5438: if ($thisallowed=~/F/) {
5439: return 'F';
5440: }
5441:
1.52 www 5442: # If this is generating or modifying users, exit with special codes
1.29 www 5443:
1.643 www 5444: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5445: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5446: my ($audom,$auname)=split('/',$uri);
1.643 www 5447: # no author name given, so this just checks on the general right to make a co-author in this domain
5448: unless ($auname) { return $thisallowed; }
5449: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5450: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5451: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5452: ($audom ne $env{'request.role.domain'}))) { return ''; }
5453: }
1.52 www 5454: return $thisallowed;
5455: }
5456: #
1.103 harris41 5457: # Gathered so far: system, domain and course wide privileges
1.52 www 5458: #
5459: # Course: See if uri or referer is an individual resource that is part of
5460: # the course
5461:
1.620 albertel 5462: if ($env{'request.course.id'}) {
1.232 www 5463:
1.620 albertel 5464: $courseprivid=$env{'request.course.id'};
5465: if ($env{'request.course.sec'}) {
5466: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5467: }
5468: $courseprivid=~s/\_/\//;
5469: my $checkreferer=1;
1.232 www 5470: my ($match,$cond)=&is_on_map($uri);
5471: if ($match) {
5472: $statecond=$cond;
1.620 albertel 5473: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5474: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5475: $thisallowed.=$1;
5476: $checkreferer=0;
5477: }
1.29 www 5478: }
1.83 www 5479:
1.148 www 5480: if ($checkreferer) {
1.620 albertel 5481: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5482: unless ($refuri) {
1.800 albertel 5483: foreach my $key (keys(%env)) {
5484: if ($key=~/^httpref\..*\*/) {
5485: my $pattern=$key;
1.156 www 5486: $pattern=~s/^httpref\.\/res\///;
1.148 www 5487: $pattern=~s/\*/\[\^\/\]\+/g;
5488: $pattern=~s/\//\\\//g;
1.152 www 5489: if ($orguri=~/$pattern/) {
1.800 albertel 5490: $refuri=$env{$key};
1.148 www 5491: }
5492: }
1.191 harris41 5493: }
1.148 www 5494: }
1.232 www 5495:
1.148 www 5496: if ($refuri) {
1.152 www 5497: $refuri=&declutter($refuri);
1.232 www 5498: my ($match,$cond)=&is_on_map($refuri);
5499: if ($match) {
5500: my $refstatecond=$cond;
1.620 albertel 5501: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5502: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5503: $thisallowed.=$1;
1.53 www 5504: $uri=$refuri;
5505: $statecond=$refstatecond;
1.52 www 5506: }
5507: }
1.148 www 5508: }
1.29 www 5509: }
1.52 www 5510: }
1.29 www 5511:
1.52 www 5512: #
1.103 harris41 5513: # Gathered now: all privileges that could apply, and condition number
1.52 www 5514: #
5515: #
5516: # Full or no access?
5517: #
1.29 www 5518:
1.52 www 5519: if ($thisallowed=~/F/) {
5520: return 'F';
5521: }
1.29 www 5522:
1.52 www 5523: unless ($thisallowed) {
5524: return '';
5525: }
1.29 www 5526:
1.52 www 5527: # Restrictions exist, deal with them
5528: #
5529: # C:according to course preferences
5530: # R:according to resource settings
5531: # L:unless locked
5532: # X:according to user session state
5533: #
5534:
5535: # Possibly locked functionality, check all courses
1.54 www 5536: # Locks might take effect only after 10 minutes cache expiration for other
5537: # courses, and 2 minutes for current course
1.52 www 5538:
5539: my $envkey;
5540: if ($thisallowed=~/L/) {
1.1000 raeburn 5541: foreach $envkey (keys(%env)) {
1.54 www 5542: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5543: my $courseid=$2;
5544: my $roleid=$1.'.'.$2;
1.92 www 5545: $courseid=~s/^\///;
1.54 www 5546: my $expiretime=600;
1.620 albertel 5547: if ($env{'request.role'} eq $roleid) {
1.54 www 5548: $expiretime=120;
5549: }
5550: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5551: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5552: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5553: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5554: }
1.620 albertel 5555: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5556: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5557: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5558: &log($env{'user.domain'},$env{'user.name'},
5559: $env{'user.home'},
1.57 www 5560: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5561: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5562: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5563: return '';
5564: }
5565: }
1.620 albertel 5566: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5567: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5568: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5569: &log($env{'user.domain'},$env{'user.name'},
5570: $env{'user.home'},
1.57 www 5571: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5572: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5573: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5574: return '';
5575: }
5576: }
5577: }
1.29 www 5578: }
1.52 www 5579: }
5580:
5581: #
5582: # Rest of the restrictions depend on selected course
5583: #
5584:
1.620 albertel 5585: unless ($env{'request.course.id'}) {
1.766 albertel 5586: if ($thisallowed eq 'A') {
5587: return 'A';
1.814 raeburn 5588: } elsif ($thisallowed eq 'B') {
5589: return 'B';
1.766 albertel 5590: } else {
5591: return '1';
5592: }
1.52 www 5593: }
1.29 www 5594:
1.52 www 5595: #
5596: # Now user is definitely in a course
5597: #
1.53 www 5598:
5599:
5600: # Course preferences
5601:
5602: if ($thisallowed=~/C/) {
1.620 albertel 5603: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5604: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5605: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5606: =~/\Q$rolecode\E/) {
1.689 albertel 5607: if ($priv ne 'pch') {
5608: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5609: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5610: $env{'request.course.id'});
5611: }
1.237 www 5612: return '';
5613: }
5614:
1.620 albertel 5615: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5616: =~/\Q$unamedom\E/) {
1.689 albertel 5617: if ($priv ne 'pch') {
5618: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5619: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5620: $env{'request.course.id'});
5621: }
1.54 www 5622: return '';
5623: }
1.53 www 5624: }
5625:
5626: # Resource preferences
5627:
5628: if ($thisallowed=~/R/) {
1.620 albertel 5629: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5630: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5631: if ($priv ne 'pch') {
5632: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5633: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5634: }
5635: return '';
1.54 www 5636: }
1.53 www 5637: }
1.30 www 5638:
1.246 www 5639: # Restricted by state or randomout?
1.30 www 5640:
1.52 www 5641: if ($thisallowed=~/X/) {
1.620 albertel 5642: if ($env{'acc.randomout'}) {
1.579 albertel 5643: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5644: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5645: return '';
5646: }
1.247 www 5647: }
5648: if (&condval($statecond)) {
1.52 www 5649: return '2';
5650: } else {
5651: return '';
5652: }
5653: }
1.30 www 5654:
1.766 albertel 5655: if ($thisallowed eq 'A') {
5656: return 'A';
1.814 raeburn 5657: } elsif ($thisallowed eq 'B') {
5658: return 'B';
1.766 albertel 5659: }
1.52 www 5660: return 'F';
1.232 www 5661: }
5662:
1.710 albertel 5663: sub split_uri_for_cond {
5664: my $uri=&deversion(&declutter(shift));
5665: my @uriparts=split(/\//,$uri);
5666: my $filename=pop(@uriparts);
5667: my $pathname=join('/',@uriparts);
5668: return ($pathname,$filename);
5669: }
1.232 www 5670: # --------------------------------------------------- Is a resource on the map?
5671:
5672: sub is_on_map {
1.710 albertel 5673: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5674: #Trying to find the conditional for the file
1.620 albertel 5675: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5676: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5677: if ($match) {
1.289 bowersj2 5678: return (1,$1);
5679: } else {
1.434 www 5680: return (0,0);
1.289 bowersj2 5681: }
1.12 www 5682: }
5683:
1.427 www 5684: # --------------------------------------------------------- Get symb from alias
5685:
5686: sub get_symb_from_alias {
5687: my $symb=shift;
5688: my ($map,$resid,$url)=&decode_symb($symb);
5689: # Already is a symb
5690: if ($url) { return $symb; }
5691: # Must be an alias
5692: my $aliassymb='';
5693: my %bighash;
1.620 albertel 5694: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5695: &GDBM_READER(),0640)) {
5696: my $rid=$bighash{'mapalias_'.$symb};
5697: if ($rid) {
5698: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5699: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5700: $resid,$bighash{'src_'.$rid});
1.427 www 5701: }
5702: untie %bighash;
5703: }
5704: return $aliassymb;
5705: }
5706:
1.12 www 5707: # ----------------------------------------------------------------- Define Role
5708:
5709: sub definerole {
5710: if (allowed('mcr','/')) {
5711: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5712: foreach my $role (split(':',$sysrole)) {
5713: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5714: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5715: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5716: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5717: return "refused:s:$crole&$cqual";
5718: }
5719: }
1.191 harris41 5720: }
1.800 albertel 5721: foreach my $role (split(':',$domrole)) {
5722: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5723: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5724: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5725: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5726: return "refused:d:$crole&$cqual";
5727: }
5728: }
1.191 harris41 5729: }
1.800 albertel 5730: foreach my $role (split(':',$courole)) {
5731: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5732: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5733: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5734: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5735: return "refused:c:$crole&$cqual";
5736: }
5737: }
1.191 harris41 5738: }
1.620 albertel 5739: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5740: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5741: "rolesdef_$rolename=".
5742: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5743: return reply($command,$env{'user.home'});
1.12 www 5744: } else {
5745: return 'refused';
5746: }
1.105 harris41 5747: }
5748:
5749: # ---------------- Make a metadata query against the network of library servers
5750:
5751: sub metadata_query {
1.244 matthew 5752: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5753: my %rhash;
1.845 albertel 5754: my %libserv = &all_library();
1.244 matthew 5755: my @server_list = (defined($server_array) ? @$server_array
5756: : keys(%libserv) );
5757: for my $server (@server_list) {
1.118 harris41 5758: unless ($custom or $customshow) {
5759: my $reply=&reply("querysend:".&escape($query),$server);
5760: $rhash{$server}=$reply;
5761: }
5762: else {
5763: my $reply=&reply("querysend:".&escape($query).':'.
5764: &escape($custom).':'.&escape($customshow),
5765: $server);
5766: $rhash{$server}=$reply;
5767: }
1.112 harris41 5768: }
1.118 harris41 5769: return \%rhash;
1.240 www 5770: }
5771:
5772: # ----------------------------------------- Send log queries and wait for reply
5773:
5774: sub log_query {
5775: my ($uname,$udom,$query,%filters)=@_;
5776: my $uhome=&homeserver($uname,$udom);
5777: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5778: my $uhost=&hostname($uhome);
1.800 albertel 5779: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5780: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5781: $uhome);
1.479 albertel 5782: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5783: return get_query_reply($queryid);
5784: }
5785:
1.818 raeburn 5786: # -------------------------- Update MySQL table for portfolio file
5787:
5788: sub update_portfolio_table {
1.821 raeburn 5789: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5790: if ($group ne '') {
5791: $file_name =~s /^\Q$group\E//;
5792: }
1.818 raeburn 5793: my $homeserver = &homeserver($uname,$udom);
5794: my $queryid=
1.821 raeburn 5795: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5796: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5797: my $reply = &get_query_reply($queryid);
5798: return $reply;
5799: }
5800:
1.899 raeburn 5801: # -------------------------- Update MySQL allusers table
5802:
5803: sub update_allusers_table {
5804: my ($uname,$udom,$names) = @_;
5805: my $homeserver = &homeserver($uname,$udom);
5806: my $queryid=
5807: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5808: 'lastname='.&escape($names->{'lastname'}).'%%'.
5809: 'firstname='.&escape($names->{'firstname'}).'%%'.
5810: 'middlename='.&escape($names->{'middlename'}).'%%'.
5811: 'generation='.&escape($names->{'generation'}).'%%'.
5812: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5813: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4! raeburn 5814: return;
1.899 raeburn 5815: }
5816:
1.508 raeburn 5817: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5818:
5819: sub fetch_enrollment_query {
1.511 raeburn 5820: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5821: my $homeserver;
1.547 raeburn 5822: my $maxtries = 1;
1.508 raeburn 5823: if ($context eq 'automated') {
5824: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5825: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5826: } else {
5827: $homeserver = &homeserver($cnum,$dom);
5828: }
1.838 albertel 5829: my $host=&hostname($homeserver);
1.506 raeburn 5830: my $cmd = '';
1.1000 raeburn 5831: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5832: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5833: }
5834: $cmd =~ s/%%$//;
5835: $cmd = &escape($cmd);
5836: my $query = 'fetchenrollment';
1.620 albertel 5837: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5838: unless ($queryid=~/^\Q$host\E\_/) {
5839: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5840: return 'error: '.$queryid;
5841: }
1.506 raeburn 5842: my $reply = &get_query_reply($queryid);
1.547 raeburn 5843: my $tries = 1;
5844: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5845: $reply = &get_query_reply($queryid);
5846: $tries ++;
5847: }
1.526 raeburn 5848: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5849: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5850: } else {
1.901 albertel 5851: my @responses = split(/:/,$reply);
1.515 raeburn 5852: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5853: foreach my $line (@responses) {
5854: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5855: $$replyref{$key} = $value;
5856: }
5857: } else {
1.506 raeburn 5858: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5859: foreach my $line (@responses) {
5860: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5861: $$replyref{$key} = $value;
5862: if ($value > 0) {
1.800 albertel 5863: foreach my $item (@{$$affiliatesref{$key}}) {
5864: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5865: my $destname = $pathname.'/'.$filename;
5866: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5867: if ($xml_classlist =~ /^error/) {
5868: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5869: } else {
1.506 raeburn 5870: if ( open(FILE,">$destname") ) {
5871: print FILE &unescape($xml_classlist);
5872: close(FILE);
1.526 raeburn 5873: } else {
5874: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5875: }
5876: }
5877: }
5878: }
5879: }
5880: }
5881: return 'ok';
5882: }
5883: return 'error';
5884: }
5885:
1.242 www 5886: sub get_query_reply {
5887: my $queryid=shift;
1.240 www 5888: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5889: my $reply='';
5890: for (1..100) {
5891: sleep 2;
5892: if (-e $replyfile.'.end') {
1.448 albertel 5893: if (open(my $fh,$replyfile)) {
1.904 albertel 5894: $reply = join('',<$fh>);
5895: close($fh);
1.240 www 5896: } else { return 'error: reply_file_error'; }
1.242 www 5897: return &unescape($reply);
5898: }
1.240 www 5899: }
1.242 www 5900: return 'timeout:'.$queryid;
1.240 www 5901: }
5902:
5903: sub courselog_query {
1.241 www 5904: #
5905: # possible filters:
5906: # url: url or symb
5907: # username
5908: # domain
5909: # action: view, submit, grade
5910: # start: timestamp
5911: # end: timestamp
5912: #
1.240 www 5913: my (%filters)=@_;
1.620 albertel 5914: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5915: if ($filters{'url'}) {
5916: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5917: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5918: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5919: }
1.620 albertel 5920: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5921: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5922: return &log_query($cname,$cdom,'courselog',%filters);
5923: }
5924:
5925: sub userlog_query {
1.858 raeburn 5926: #
5927: # possible filters:
5928: # action: log check role
5929: # start: timestamp
5930: # end: timestamp
5931: #
1.240 www 5932: my ($uname,$udom,%filters)=@_;
5933: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5934: }
5935:
1.506 raeburn 5936: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5937:
5938: sub auto_run {
1.508 raeburn 5939: my ($cnum,$cdom) = @_;
1.876 raeburn 5940: my $response = 0;
5941: my $settings;
5942: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5943: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5944: $settings = $domconfig{'autoenroll'};
5945: if ($settings->{'run'} eq '1') {
5946: $response = 1;
5947: }
5948: } else {
1.934 raeburn 5949: my $homeserver;
5950: if (&is_course($cdom,$cnum)) {
5951: $homeserver = &homeserver($cnum,$cdom);
5952: } else {
5953: $homeserver = &domain($cdom,'primary');
5954: }
5955: if ($homeserver ne 'no_host') {
5956: $response = &reply('autorun:'.$cdom,$homeserver);
5957: }
1.876 raeburn 5958: }
1.506 raeburn 5959: return $response;
5960: }
1.776 albertel 5961:
1.506 raeburn 5962: sub auto_get_sections {
1.508 raeburn 5963: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5964: my $homeserver;
5965: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5966: $homeserver = &homeserver($cnum,$cdom);
5967: }
5968: if (!defined($homeserver)) {
5969: if ($cdom =~ /^$match_domain$/) {
5970: $homeserver = &domain($cdom,'primary');
5971: }
5972: }
5973: my @secs;
5974: if (defined($homeserver)) {
5975: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5976: unless ($response eq 'refused') {
5977: @secs = split(/:/,$response);
5978: }
1.506 raeburn 5979: }
5980: return @secs;
5981: }
1.776 albertel 5982:
1.506 raeburn 5983: sub auto_new_course {
1.508 raeburn 5984: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5985: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5986: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5987: return $response;
5988: }
1.776 albertel 5989:
1.506 raeburn 5990: sub auto_validate_courseID {
1.508 raeburn 5991: my ($cnum,$cdom,$inst_course_id) = @_;
5992: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5993: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5994: return $response;
5995: }
1.776 albertel 5996:
1.1007 raeburn 5997: sub auto_validate_instcode {
1.1020 raeburn 5998: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5999: my ($homeserver,$response);
6000: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6001: $homeserver = &homeserver($cnum,$cdom);
6002: }
6003: if (!defined($homeserver)) {
6004: if ($cdom =~ /^$match_domain$/) {
6005: $homeserver = &domain($cdom,'primary');
6006: }
6007: }
1.1056.4.2 raeburn 6008: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6009: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6010: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6011: return ($outcome,$description);
1.1007 raeburn 6012: }
6013:
1.506 raeburn 6014: sub auto_create_password {
1.873 raeburn 6015: my ($cnum,$cdom,$authparam,$udom) = @_;
6016: my ($homeserver,$response);
1.506 raeburn 6017: my $create_passwd = 0;
6018: my $authchk = '';
1.873 raeburn 6019: if ($udom =~ /^$match_domain$/) {
6020: $homeserver = &domain($udom,'primary');
6021: }
6022: if ($homeserver eq '') {
6023: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6024: $homeserver = &homeserver($cnum,$cdom);
6025: }
6026: }
6027: if ($homeserver eq '') {
6028: $authchk = 'nodomain';
1.506 raeburn 6029: } else {
1.873 raeburn 6030: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6031: if ($response eq 'refused') {
6032: $authchk = 'refused';
6033: } else {
1.901 albertel 6034: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6035: }
1.506 raeburn 6036: }
6037: return ($authparam,$create_passwd,$authchk);
6038: }
6039:
1.706 raeburn 6040: sub auto_photo_permission {
6041: my ($cnum,$cdom,$students) = @_;
6042: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6043: my ($outcome,$perm_reqd,$conditions) =
6044: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6045: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6046: return (undef,undef);
6047: }
1.706 raeburn 6048: return ($outcome,$perm_reqd,$conditions);
6049: }
6050:
6051: sub auto_checkphotos {
6052: my ($uname,$udom,$pid) = @_;
6053: my $homeserver = &homeserver($uname,$udom);
6054: my ($result,$resulttype);
6055: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6056: &escape($uname).':'.&escape($pid),
6057: $homeserver));
1.709 albertel 6058: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6059: return (undef,undef);
6060: }
1.706 raeburn 6061: if ($outcome) {
6062: ($result,$resulttype) = split(/:/,$outcome);
6063: }
6064: return ($result,$resulttype);
6065: }
6066:
6067: sub auto_photochoice {
6068: my ($cnum,$cdom) = @_;
6069: my $homeserver = &homeserver($cnum,$cdom);
6070: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6071: &escape($cdom),
6072: $homeserver)));
1.709 albertel 6073: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6074: return (undef,undef);
6075: }
1.706 raeburn 6076: return ($update,$comment);
6077: }
6078:
6079: sub auto_photoupdate {
6080: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6081: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6082: my $host=&hostname($homeserver);
1.706 raeburn 6083: my $cmd = '';
6084: my $maxtries = 1;
1.800 albertel 6085: foreach my $affiliate (keys(%{$affiliatesref})) {
6086: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6087: }
6088: $cmd =~ s/%%$//;
6089: $cmd = &escape($cmd);
6090: my $query = 'institutionalphotos';
6091: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6092: unless ($queryid=~/^\Q$host\E\_/) {
6093: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6094: return 'error: '.$queryid;
6095: }
6096: my $reply = &get_query_reply($queryid);
6097: my $tries = 1;
6098: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6099: $reply = &get_query_reply($queryid);
6100: $tries ++;
6101: }
6102: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6103: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6104: } else {
6105: my @responses = split(/:/,$reply);
6106: my $outcome = shift(@responses);
6107: foreach my $item (@responses) {
6108: my ($key,$value) = split(/=/,$item);
6109: $$photo{$key} = $value;
6110: }
6111: return $outcome;
6112: }
6113: return 'error';
6114: }
6115:
1.521 raeburn 6116: sub auto_instcode_format {
1.793 albertel 6117: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6118: $cat_order) = @_;
1.521 raeburn 6119: my $courses = '';
1.772 raeburn 6120: my @homeservers;
1.521 raeburn 6121: if ($caller eq 'global') {
1.841 albertel 6122: my %servers = &get_servers($codedom,'library');
6123: foreach my $tryserver (keys(%servers)) {
6124: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6125: push(@homeservers,$tryserver);
6126: }
1.584 raeburn 6127: }
1.1022 raeburn 6128: } elsif ($caller eq 'requests') {
6129: if ($codedom =~ /^$match_domain$/) {
6130: my $chome = &domain($codedom,'primary');
6131: unless ($chome eq 'no_host') {
6132: push(@homeservers,$chome);
6133: }
6134: }
1.521 raeburn 6135: } else {
1.772 raeburn 6136: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6137: }
1.793 albertel 6138: foreach my $code (keys(%{$instcodes})) {
6139: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6140: }
6141: chop($courses);
1.772 raeburn 6142: my $ok_response = 0;
6143: my $response;
6144: while (@homeservers > 0 && $ok_response == 0) {
6145: my $server = shift(@homeservers);
6146: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6147: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6148: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6149: split(/:/,$response);
1.772 raeburn 6150: %{$codes} = (%{$codes},&str2hash($codes_str));
6151: push(@{$codetitles},&str2array($codetitles_str));
6152: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6153: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6154: $ok_response = 1;
6155: }
6156: }
6157: if ($ok_response) {
1.521 raeburn 6158: return 'ok';
1.772 raeburn 6159: } else {
6160: return $response;
1.521 raeburn 6161: }
6162: }
6163:
1.792 raeburn 6164: sub auto_instcode_defaults {
6165: my ($domain,$returnhash,$code_order) = @_;
6166: my @homeservers;
1.841 albertel 6167:
6168: my %servers = &get_servers($domain,'library');
6169: foreach my $tryserver (keys(%servers)) {
6170: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6171: push(@homeservers,$tryserver);
6172: }
1.792 raeburn 6173: }
1.841 albertel 6174:
1.792 raeburn 6175: my $response;
1.841 albertel 6176: foreach my $server (@homeservers) {
1.792 raeburn 6177: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6178: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6179:
6180: foreach my $pair (split(/\&/,$response)) {
6181: my ($name,$value)=split(/\=/,$pair);
6182: if ($name eq 'code_order') {
6183: @{$code_order} = split(/\&/,&unescape($value));
6184: } else {
6185: $returnhash->{&unescape($name)}=&unescape($value);
6186: }
6187: }
6188: return 'ok';
1.792 raeburn 6189: }
1.841 albertel 6190:
6191: return $response;
1.1003 raeburn 6192: }
6193:
6194: sub auto_possible_instcodes {
1.1007 raeburn 6195: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6196: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6197: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6198: return;
6199: }
1.1003 raeburn 6200: my (@homeservers,$uhome);
6201: if (defined(&domain($domain,'primary'))) {
6202: $uhome=&domain($domain,'primary');
6203: push(@homeservers,&domain($domain,'primary'));
6204: } else {
6205: my %servers = &get_servers($domain,'library');
6206: foreach my $tryserver (keys(%servers)) {
6207: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6208: push(@homeservers,$tryserver);
6209: }
6210: }
6211: }
6212: my $response;
6213: foreach my $server (@homeservers) {
6214: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6215: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6216: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6217: split(':',$response);
6218: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6219: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6220: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6221: my ($name,$value)=split('=',$item);
6222: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6223: }
6224: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6225: my ($name,$value)=split('=',$item);
6226: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6227: }
6228: return 'ok';
6229: }
6230: return $response;
6231: }
1.792 raeburn 6232:
1.1010 raeburn 6233: sub auto_courserequest_checks {
6234: my ($dom) = @_;
1.1020 raeburn 6235: my ($homeserver,%validations);
6236: if ($dom =~ /^$match_domain$/) {
6237: $homeserver = &domain($dom,'primary');
6238: }
6239: unless ($homeserver eq 'no_host') {
6240: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6241: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6242: my @items = split(/&/,$response);
6243: foreach my $item (@items) {
6244: my ($key,$value) = split('=',$item);
6245: $validations{&unescape($key)} = &thaw_unescape($value);
6246: }
6247: }
6248: }
1.1010 raeburn 6249: return %validations;
6250: }
6251:
1.1020 raeburn 6252: sub auto_courserequest_validation {
6253: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6254: my ($homeserver,$response);
6255: if ($dom =~ /^$match_domain$/) {
6256: $homeserver = &domain($dom,'primary');
6257: }
6258: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6259:
1.1020 raeburn 6260: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6261: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6262: ':'.&escape($instcode).':'.&escape($instseclist),
6263: $homeserver));
6264: }
6265: return $response;
6266: }
6267:
1.777 albertel 6268: sub auto_validate_class_sec {
1.918 raeburn 6269: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6270: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6271: my $ownerlist;
6272: if (ref($owners) eq 'ARRAY') {
6273: $ownerlist = join(',',@{$owners});
6274: } else {
6275: $ownerlist = $owners;
6276: }
1.773 raeburn 6277: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6278: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6279: return $response;
6280: }
6281:
1.679 raeburn 6282: # ------------------------------------------------------- Course Group routines
6283:
6284: sub get_coursegroups {
1.809 raeburn 6285: my ($cdom,$cnum,$group,$namespace) = @_;
6286: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6287: }
6288:
1.679 raeburn 6289: sub modify_coursegroup {
6290: my ($cdom,$cnum,$groupsettings) = @_;
6291: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6292: }
6293:
1.809 raeburn 6294: sub toggle_coursegroup_status {
6295: my ($cdom,$cnum,$group,$action) = @_;
6296: my ($from_namespace,$to_namespace);
6297: if ($action eq 'delete') {
6298: $from_namespace = 'coursegroups';
6299: $to_namespace = 'deleted_groups';
6300: } else {
6301: $from_namespace = 'deleted_groups';
6302: $to_namespace = 'coursegroups';
6303: }
6304: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6305: if (my $tmp = &error(%curr_group)) {
6306: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6307: return ('read error',$tmp);
6308: } else {
6309: my %savedsettings = %curr_group;
1.809 raeburn 6310: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6311: my $deloutcome;
6312: if ($result eq 'ok') {
1.809 raeburn 6313: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6314: } else {
6315: return ('write error',$result);
6316: }
6317: if ($deloutcome eq 'ok') {
6318: return 'ok';
6319: } else {
6320: return ('delete error',$deloutcome);
6321: }
6322: }
6323: }
6324:
1.679 raeburn 6325: sub modify_group_roles {
1.957 raeburn 6326: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6327: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6328: my $role = 'gr/'.&escape($userprivs);
6329: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6330: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6331: if ($result eq 'ok') {
6332: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6333: }
1.679 raeburn 6334: return $result;
6335: }
6336:
6337: sub modify_coursegroup_membership {
6338: my ($cdom,$cnum,$membership) = @_;
6339: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6340: return $result;
6341: }
6342:
1.682 raeburn 6343: sub get_active_groups {
6344: my ($udom,$uname,$cdom,$cnum) = @_;
6345: my $now = time;
6346: my %groups = ();
6347: foreach my $key (keys(%env)) {
1.811 albertel 6348: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6349: my ($start,$end) = split(/\./,$env{$key});
6350: if (($end!=0) && ($end<$now)) { next; }
6351: if (($start!=0) && ($start>$now)) { next; }
6352: if ($1 eq $cdom && $2 eq $cnum) {
6353: $groups{$3} = $env{$key} ;
6354: }
6355: }
6356: }
6357: return %groups;
6358: }
6359:
1.683 raeburn 6360: sub get_group_membership {
6361: my ($cdom,$cnum,$group) = @_;
6362: return(&dump('groupmembership',$cdom,$cnum,$group));
6363: }
6364:
6365: sub get_users_groups {
6366: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6367: my @usersgroups;
1.683 raeburn 6368: my $cachetime=1800;
6369:
6370: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6371: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6372: if (defined($cached)) {
1.734 albertel 6373: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6374: } else {
6375: $grouplist = '';
1.816 raeburn 6376: my $courseurl = &courseid_to_courseurl($courseid);
6377: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6378: my $access_end = $env{'course.'.$courseid.
6379: '.default_enrollment_end_date'};
6380: my $now = time;
6381: foreach my $key (keys(%roleshash)) {
6382: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6383: my $group = $1;
6384: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6385: my $start = $2;
6386: my $end = $1;
6387: if ($start == -1) { next; } # deleted from group
6388: if (($start!=0) && ($start>$now)) { next; }
6389: if (($end!=0) && ($end<$now)) {
6390: if ($access_end && $access_end < $now) {
6391: if ($access_end - $end < 86400) {
6392: push(@usersgroups,$group);
1.733 raeburn 6393: }
6394: }
1.817 raeburn 6395: next;
1.733 raeburn 6396: }
1.817 raeburn 6397: push(@usersgroups,$group);
1.683 raeburn 6398: }
6399: }
6400: }
1.817 raeburn 6401: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6402: $grouplist = join(':',@usersgroups);
6403: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6404: }
1.733 raeburn 6405: return @usersgroups;
1.683 raeburn 6406: }
6407:
6408: sub devalidate_getgroups_cache {
6409: my ($udom,$uname,$cdom,$cnum)=@_;
6410: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6411:
1.683 raeburn 6412: my $hashid="$udom:$uname:$courseid";
6413: &devalidate_cache_new('getgroups',$hashid);
6414: }
6415:
1.12 www 6416: # ------------------------------------------------------------------ Plain Text
6417:
6418: sub plaintext {
1.988 raeburn 6419: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6420: if ($short =~ m{^cr/}) {
1.758 albertel 6421: return (split('/',$short))[-1];
6422: }
1.742 raeburn 6423: if (!defined($cid)) {
6424: $cid = $env{'request.course.id'};
6425: }
6426: my %rolenames = (
1.1008 raeburn 6427: Course => 'std',
6428: Community => 'alt1',
1.742 raeburn 6429: );
1.1037 raeburn 6430: if ($cid ne '') {
6431: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6432: unless ($forcedefault) {
6433: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6434: &Apache::lonlocal::mt_escape(\$roletext);
6435: return &Apache::lonlocal::mt($roletext);
6436: }
6437: }
6438: }
6439: if ((defined($type)) && (defined($rolenames{$type})) &&
6440: (defined($rolenames{$type})) &&
6441: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6442: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6443: } elsif ($cid ne '') {
6444: my $crstype = $env{'course.'.$cid.'.type'};
6445: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6446: (defined($prp{$short}{$rolenames{$crstype}}))) {
6447: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6448: }
1.742 raeburn 6449: }
1.1037 raeburn 6450: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6451: }
6452:
6453: # ----------------------------------------------------------------- Assign Role
6454:
6455: sub assignrole {
1.957 raeburn 6456: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6457: $context)=@_;
1.21 www 6458: my $mrole;
6459: if ($role =~ /^cr\//) {
1.393 www 6460: my $cwosec=$url;
1.811 albertel 6461: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6462: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6463: my $refused = 1;
6464: if ($context eq 'requestcourses') {
6465: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6466: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6467: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6468: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6469: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6470: if ($crsenv{'internal.courseowner'} eq
6471: $env{'user.name'}.':'.$env{'user.domain'}) {
6472: $refused = '';
6473: }
6474: }
6475: }
6476: }
6477: }
6478: if ($refused) {
6479: &logthis('Refused custom assignrole: '.
6480: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6481: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6482: return 'refused';
6483: }
1.104 www 6484: }
1.21 www 6485: $mrole='cr';
1.678 raeburn 6486: } elsif ($role =~ /^gr\//) {
6487: my $cwogrp=$url;
1.811 albertel 6488: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6489: unless (&allowed('mdg',$cwogrp)) {
6490: &logthis('Refused group assignrole: '.
6491: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6492: $env{'user.name'}.' at '.$env{'user.domain'});
6493: return 'refused';
6494: }
6495: $mrole='gr';
1.21 www 6496: } else {
1.82 www 6497: my $cwosec=$url;
1.811 albertel 6498: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6499: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6500: my $refused;
6501: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6502: if (!(&allowed('c'.$role,$url))) {
6503: $refused = 1;
6504: }
6505: } else {
6506: $refused = 1;
6507: }
1.947 raeburn 6508: if ($refused) {
1.1045 raeburn 6509: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6510: if (!$selfenroll && $context eq 'course') {
6511: my %crsenv;
6512: if ($role eq 'cc' || $role eq 'co') {
6513: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6514: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6515: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6516: if ($crsenv{'internal.courseowner'} eq
6517: $env{'user.name'}.':'.$env{'user.domain'}) {
6518: $refused = '';
6519: }
6520: }
6521: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6522: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6523: if ($crsenv{'internal.courseowner'} eq
6524: $env{'user.name'}.':'.$env{'user.domain'}) {
6525: $refused = '';
6526: }
6527: }
6528: }
6529: }
6530: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6531: $refused = '';
1.1017 raeburn 6532: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6533: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6534: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6535: my $wrongcc;
6536: if ($cnum =~ /^$match_community$/) {
6537: $wrongcc = 1 if ($role eq 'cc');
6538: } else {
6539: $wrongcc = 1 if ($role eq 'co');
6540: }
6541: unless ($wrongcc) {
6542: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6543: if ($crsenv{'internal.courseowner'} eq
6544: $env{'user.name'}.':'.$env{'user.domain'}) {
6545: $refused = '';
6546: }
1.1017 raeburn 6547: }
6548: }
6549: }
6550: if ($refused) {
1.947 raeburn 6551: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6552: ' '.$role.' '.$end.' '.$start.' by '.
6553: $env{'user.name'}.' at '.$env{'user.domain'});
6554: return 'refused';
6555: }
1.932 raeburn 6556: }
1.104 www 6557: }
1.21 www 6558: $mrole=$role;
6559: }
1.620 albertel 6560: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6561: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6562: if ($end) { $command.='_'.$end; }
1.21 www 6563: if ($start) {
6564: if ($end) {
1.81 www 6565: $command.='_'.$start;
1.21 www 6566: } else {
1.81 www 6567: $command.='_0_'.$start;
1.21 www 6568: }
6569: }
1.739 raeburn 6570: my $origstart = $start;
6571: my $origend = $end;
1.957 raeburn 6572: my $delflag;
1.357 www 6573: # actually delete
6574: if ($deleteflag) {
1.373 www 6575: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6576: # modify command to delete the role
1.620 albertel 6577: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6578: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6579: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6580: # set start and finish to negative values for userrolelog
6581: $start=-1;
6582: $end=-1;
1.957 raeburn 6583: $delflag = 1;
1.357 www 6584: }
6585: }
6586: # send command
1.349 www 6587: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6588: # log new user role if status is ok
1.349 www 6589: if ($answer eq 'ok') {
1.663 raeburn 6590: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6591: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6592: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6593: unless ($role =~ /^gr/) {
6594: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6595: $origstart,$selfenroll,$context);
1.739 raeburn 6596: }
1.1053 raeburn 6597: if ($role eq 'cc') {
6598: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6599: }
1.349 www 6600: }
6601: return $answer;
1.169 harris41 6602: }
6603:
1.1053 raeburn 6604: sub autoupdate_coowners {
6605: my ($url,$end,$start,$uname,$udom) = @_;
6606: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6607: if (($cdom ne '') && ($cnum ne '')) {
6608: my $now = time;
6609: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6610: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6611: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6612: my $instcode = $coursehash{'internal.coursecode'};
6613: if ($instcode ne '') {
1.1056 raeburn 6614: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6615: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6616: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6617: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6618: if ($result eq 'valid') {
6619: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6620: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6621: push(@newcoowners,$coowner);
6622: }
6623: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6624: push(@newcoowners,$uname.':'.$udom);
6625: }
6626: @newcoowners = sort(@newcoowners);
6627: } else {
6628: push(@newcoowners,$uname.':'.$udom);
6629: }
6630: } else {
6631: if ($coursehash{'internal.co-owners'}) {
6632: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6633: unless ($coowner eq $uname.':'.$udom) {
6634: push(@newcoowners,$coowner);
6635: }
6636: }
6637: unless (@newcoowners > 0) {
6638: $delcoowners = 1;
6639: $coowners = '';
6640: }
6641: }
6642: }
6643: if (@newcoowners || $delcoowners) {
6644: &store_coowners($cdom,$cnum,$coursehash{'home'},
6645: $delcoowners,@newcoowners);
6646: }
6647: }
6648: }
6649: }
6650: }
6651: }
6652: }
6653:
6654: sub store_coowners {
6655: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6656: my $cid = $cdom.'_'.$cnum;
6657: my ($coowners,$delresult,$putresult);
6658: if (@newcoowners) {
6659: $coowners = join(',',@newcoowners);
6660: my %coownershash = (
6661: 'internal.co-owners' => $coowners,
6662: );
6663: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6664: if ($putresult eq 'ok') {
6665: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6666: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6667: }
6668: }
6669: }
6670: if ($delcoowners) {
6671: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6672: if ($delresult eq 'ok') {
6673: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6674: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6675: }
6676: }
6677: }
6678: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6679: my %crsinfo =
6680: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6681: if (ref($crsinfo{$cid}) eq 'HASH') {
6682: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6683: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6684: }
6685: }
6686: }
6687:
1.169 harris41 6688: # -------------------------------------------------- Modify user authentication
1.197 www 6689: # Overrides without validation
6690:
1.169 harris41 6691: sub modifyuserauth {
6692: my ($udom,$uname,$umode,$upass)=@_;
6693: my $uhome=&homeserver($uname,$udom);
1.197 www 6694: unless (&allowed('mau',$udom)) { return 'refused'; }
6695: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6696: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6697: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6698: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6699: &escape($upass),$uhome);
1.620 albertel 6700: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6701: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6702: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6703: &log($udom,,$uname,$uhome,
1.620 albertel 6704: 'Authentication changed by '.$env{'user.domain'}.', '.
6705: $env{'user.name'}.', '.$umode.
1.197 www 6706: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6707: unless ($reply eq 'ok') {
1.197 www 6708: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6709: return 'error: '.$reply;
6710: }
1.170 harris41 6711: return 'ok';
1.80 www 6712: }
6713:
1.81 www 6714: # --------------------------------------------------------------- Modify a user
1.80 www 6715:
1.81 www 6716: sub modifyuser {
1.206 matthew 6717: my ($udom, $uname, $uid,
6718: $umode, $upass, $first,
6719: $middle, $last, $gene,
1.1056.4.1 raeburn 6720: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6721: $udom= &LONCAPA::clean_domain($udom);
6722: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6723: my $showcandelete = 'none';
6724: if (ref($candelete) eq 'ARRAY') {
6725: if (@{$candelete} > 0) {
6726: $showcandelete = join(', ',@{$candelete});
6727: }
6728: }
1.81 www 6729: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6730: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6731: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6732: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6733: ' desiredhome not specified').
1.620 albertel 6734: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6735: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6736: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4! raeburn 6737: my $newuser;
! 6738: if ($uhome eq 'no_host') {
! 6739: $newuser = 1;
! 6740: }
! 6741:
1.80 www 6742: # ----------------------------------------------------------------- Create User
1.406 albertel 6743: if (($uhome eq 'no_host') &&
6744: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6745: my $unhome='';
1.844 albertel 6746: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6747: $unhome = $desiredhome;
1.620 albertel 6748: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6749: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6750: } else { # load balancing routine for determining $unhome
1.81 www 6751: my $loadm=10000000;
1.841 albertel 6752: my %servers = &get_servers($udom,'library');
6753: foreach my $tryserver (keys(%servers)) {
6754: my $answer=reply('load',$tryserver);
6755: if (($answer=~/\d+/) && ($answer<$loadm)) {
6756: $loadm=$answer;
6757: $unhome=$tryserver;
6758: }
1.80 www 6759: }
6760: }
6761: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6762: return 'error: unable to find a home server for '.$uname.
6763: ' in domain '.$udom;
1.80 www 6764: }
6765: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6766: &escape($upass),$unhome);
6767: unless ($reply eq 'ok') {
6768: return 'error: '.$reply;
6769: }
1.230 stredwic 6770: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6771: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6772: return 'error: unable verify users home machine.';
1.80 www 6773: }
1.209 matthew 6774: } # End of creation of new user
1.80 www 6775: # ---------------------------------------------------------------------- Add ID
6776: if ($uid) {
6777: $uid=~tr/A-Z/a-z/;
6778: my %uidhash=&idrget($udom,$uname);
1.196 www 6779: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6780: && (!$forceid)) {
1.80 www 6781: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6782: return 'error: user id "'.$uid.'" does not match '.
6783: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6784: }
6785: } else {
6786: &idput($udom,($uname => $uid));
6787: }
6788: }
6789: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6790: my @tmp=&get('environment',
1.899 raeburn 6791: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6792: 'permanentemail','inststatus'],
1.134 albertel 6793: $udom,$uname);
1.1056.4.4! raeburn 6794: my (%names,%oldnames);
1.313 matthew 6795: if ($tmp[0] =~ m/^error:.*/) {
6796: %names=();
6797: } else {
6798: %names = @tmp;
1.1056.4.4! raeburn 6799: %oldnames = %names;
1.313 matthew 6800: }
1.1056.4.1 raeburn 6801: # If name, email and/or uid are blank (e.g., because an uploaded file
6802: # of users did not contain them), do not overwrite existing values
6803: # unless field is in $candelete array ref.
6804: #
6805:
6806: my @fields = ('firstname','middlename','lastname','generation',
6807: 'permanentemail','id');
6808: my %newvalues;
6809: if (ref($candelete) eq 'ARRAY') {
6810: foreach my $field (@fields) {
6811: if (grep(/^\Q$field\E$/,@{$candelete})) {
6812: if ($field eq 'firstname') {
6813: $names{$field} = $first;
6814: } elsif ($field eq 'middlename') {
6815: $names{$field} = $middle;
6816: } elsif ($field eq 'lastname') {
6817: $names{$field} = $last;
6818: } elsif ($field eq 'generation') {
6819: $names{$field} = $gene;
6820: } elsif ($field eq 'permanentemail') {
6821: $names{$field} = $email;
6822: } elsif ($field eq 'id') {
6823: $names{$field} = $uid;
6824: }
6825: }
6826: }
6827: }
1.388 www 6828: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6829: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6830: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6831: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6832: if ($email) {
6833: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6834: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6835: }
1.899 raeburn 6836: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6837: if (defined($inststatus)) {
6838: $names{'inststatus'} = '';
6839: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6840: if (ref($usertypes) eq 'HASH') {
6841: my @okstatuses;
6842: foreach my $item (split(/:/,$inststatus)) {
6843: if (defined($usertypes->{$item})) {
6844: push(@okstatuses,$item);
6845: }
6846: }
6847: if (@okstatuses) {
6848: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6849: }
6850: }
6851: }
1.134 albertel 6852: my $reply = &put('environment', \%names, $udom,$uname);
6853: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6854: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6855: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.1056.4.4! raeburn 6856: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6857: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4! raeburn 6858: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6859: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6860: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6861: } else {
6862: $logmsg .= ' during self creation';
6863: }
1.1056.4.4! raeburn 6864: my $changed;
! 6865: if ($newuser) {
! 6866: $changed = 1;
! 6867: } else {
! 6868: foreach my $field (@fields) {
! 6869: if ($names{$field} ne $oldnames{$field}) {
! 6870: $changed = 1;
! 6871: last;
! 6872: }
! 6873: }
! 6874: }
! 6875: unless ($changed) {
! 6876: $logmsg = 'No changes in user information needed for: '.$logmsg;
! 6877: &logthis($logmsg);
! 6878: return 'ok';
! 6879: }
! 6880: my $reply = &put('environment', \%names, $udom,$uname);
! 6881: if ($reply ne 'ok') {
! 6882: return 'error: '.$reply;
! 6883: }
! 6884: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
! 6885: &devalidate_cache_new('namescache',$uname.':'.$udom);
! 6886: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6887: &logthis($logmsg);
1.134 albertel 6888: return 'ok';
1.80 www 6889: }
6890:
1.81 www 6891: # -------------------------------------------------------------- Modify student
1.80 www 6892:
1.81 www 6893: sub modifystudent {
6894: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6895: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6896: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6897: if (!$cid) {
1.620 albertel 6898: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6899: return 'not_in_class';
6900: }
1.80 www 6901: }
6902: # --------------------------------------------------------------- Make the user
1.81 www 6903: my $reply=&modifyuser
1.209 matthew 6904: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6905: $desiredhome,$email,$inststatus);
1.80 www 6906: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6907: # This will cause &modify_student_enrollment to get the uid from the
6908: # students environment
6909: $uid = undef if (!$forceid);
1.455 albertel 6910: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6911: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6912: return $reply;
6913: }
6914:
6915: sub modify_student_enrollment {
1.957 raeburn 6916: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6917: my ($cdom,$cnum,$chome);
6918: if (!$cid) {
1.620 albertel 6919: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6920: return 'not_in_class';
6921: }
1.620 albertel 6922: $cdom=$env{'course.'.$cid.'.domain'};
6923: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6924: } else {
6925: ($cdom,$cnum)=split(/_/,$cid);
6926: }
1.620 albertel 6927: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6928: if (!$chome) {
1.457 raeburn 6929: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6930: }
1.455 albertel 6931: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6932: # Make sure the user exists
1.81 www 6933: my $uhome=&homeserver($uname,$udom);
6934: if (($uhome eq '') || ($uhome eq 'no_host')) {
6935: return 'error: no such user';
6936: }
1.297 matthew 6937: # Get student data if we were not given enough information
6938: if (!defined($first) || $first eq '' ||
6939: !defined($last) || $last eq '' ||
6940: !defined($uid) || $uid eq '' ||
6941: !defined($middle) || $middle eq '' ||
6942: !defined($gene) || $gene eq '') {
1.294 matthew 6943: # They did not supply us with enough data to enroll the student, so
6944: # we need to pick up more information.
1.297 matthew 6945: my %tmp = &get('environment',
1.294 matthew 6946: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6947: ,$udom,$uname);
6948:
1.800 albertel 6949: #foreach my $key (keys(%tmp)) {
6950: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6951: #}
1.294 matthew 6952: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6953: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6954: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6955: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6956: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6957: }
1.556 albertel 6958: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6959: my $reply=cput('classlist',
6960: {"$uname:$udom" =>
1.515 raeburn 6961: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6962: $cdom,$cnum);
1.81 www 6963: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6964: return 'error: '.$reply;
1.652 albertel 6965: } else {
6966: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6967: }
1.297 matthew 6968: # Add student role to user
1.83 www 6969: my $uurl='/'.$cid;
1.81 www 6970: $uurl=~s/\_/\//g;
6971: if ($usec) {
6972: $uurl.='/'.$usec;
6973: }
1.957 raeburn 6974: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6975: }
6976:
1.556 albertel 6977: sub format_name {
6978: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6979: my $name;
6980: if ($first ne 'lastname') {
6981: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6982: } else {
6983: if ($lastname=~/\S/) {
6984: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6985: $name=~s/\s+,/,/;
6986: } else {
6987: $name.= $firstname.' '.$middlename.' '.$generation;
6988: }
6989: }
6990: $name=~s/^\s+//;
6991: $name=~s/\s+$//;
6992: $name=~s/\s+/ /g;
6993: return $name;
6994: }
6995:
1.84 www 6996: # ------------------------------------------------- Write to course preferences
6997:
6998: sub writecoursepref {
6999: my ($courseid,%prefs)=@_;
7000: $courseid=~s/^\///;
7001: $courseid=~s/\_/\//g;
7002: my ($cdomain,$cnum)=split(/\//,$courseid);
7003: my $chome=homeserver($cnum,$cdomain);
7004: if (($chome eq '') || ($chome eq 'no_host')) {
7005: return 'error: no such course';
7006: }
7007: my $cstring='';
1.800 albertel 7008: foreach my $pref (keys(%prefs)) {
7009: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7010: }
1.84 www 7011: $cstring=~s/\&$//;
7012: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7013: }
7014:
7015: # ---------------------------------------------------------- Make/modify course
7016:
7017: sub createcourse {
1.741 raeburn 7018: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7019: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7020: $url=&declutter($url);
7021: my $cid='';
1.1028 raeburn 7022: if ($context eq 'requestcourses') {
7023: my $can_create = 0;
7024: my ($ownername,$ownerdom) = split(':',$course_owner);
7025: if ($udom eq $ownerdom) {
7026: if (&usertools_access($ownername,$ownerdom,$category,undef,
7027: $context)) {
7028: $can_create = 1;
7029: }
7030: } else {
7031: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7032: $category);
7033: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7034: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7035: if (@curr > 0) {
7036: my @options = qw(approval validate autolimit);
7037: my $optregex = join('|',@options);
7038: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7039: $can_create = 1;
7040: }
7041: }
7042: }
7043: }
7044: if ($can_create) {
7045: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7046: unless (&allowed('ccc',$udom)) {
7047: return 'refused';
7048: }
1.1017 raeburn 7049: }
7050: } else {
7051: return 'refused';
7052: }
1.1028 raeburn 7053: } elsif (!&allowed('ccc',$udom)) {
7054: return 'refused';
1.84 www 7055: }
1.1011 raeburn 7056: # --------------------------------------------------------------- Get Unique ID
7057: my $uname;
7058: if ($cnum =~ /^$match_courseid$/) {
7059: my $chome=&homeserver($cnum,$udom,'true');
7060: if (($chome eq '') || ($chome eq 'no_host')) {
7061: $uname = $cnum;
7062: } else {
1.1038 raeburn 7063: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7064: }
7065: } else {
1.1038 raeburn 7066: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7067: }
7068: return $uname if ($uname =~ /^error/);
7069: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7070: if (!defined($course_server)) {
7071: if (defined(&domain($udom,'primary'))) {
7072: $course_server = &domain($udom,'primary');
7073: } else {
7074: $course_server = $env{'user.home'};
7075: }
7076: }
7077: my %host_servers =
7078: &Apache::lonnet::get_servers($udom,'library');
7079: unless ($host_servers{$course_server}) {
7080: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7081: }
1.84 www 7082: # ------------------------------------------------------------- Make the course
7083: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7084: $course_server);
1.84 www 7085: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7086: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7087: if (($uhome eq '') || ($uhome eq 'no_host')) {
7088: return 'error: no such course';
7089: }
1.271 www 7090: # ----------------------------------------------------------------- Course made
1.516 raeburn 7091: # log existence
1.1029 raeburn 7092: my $now = time;
1.918 raeburn 7093: my $newcourse = {
7094: $udom.'_'.$uname => {
1.921 raeburn 7095: description => $description,
7096: inst_code => $inst_code,
7097: owner => $course_owner,
7098: type => $crstype,
1.1029 raeburn 7099: creator => $env{'user.name'}.':'.
7100: $env{'user.domain'},
7101: created => $now,
7102: context => $context,
1.918 raeburn 7103: },
7104: };
1.921 raeburn 7105: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7106: # set toplevel url
1.271 www 7107: my $topurl=$url;
7108: unless ($nonstandard) {
7109: # ------------------------------------------ For standard courses, make top url
7110: my $mapurl=&clutter($url);
1.278 www 7111: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7112: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7113: <map>
7114: <resource id="1" type="start"></resource>
7115: <resource id="2" src="$mapurl"></resource>
7116: <resource id="3" type="finish"></resource>
7117: <link index="1" from="1" to="2"></link>
7118: <link index="2" from="2" to="3"></link>
7119: </map>
7120: ENDINITMAP
7121: $topurl=&declutter(
1.638 albertel 7122: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7123: );
7124: }
7125: # ----------------------------------------------------------- Write preferences
1.84 www 7126: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7127: ('description' => $description,
7128: 'url' => $topurl,
7129: 'internal.creator' => $env{'user.name'}.':'.
7130: $env{'user.domain'},
7131: 'internal.created' => $now,
7132: 'internal.creationcontext' => $context)
7133: );
1.84 www 7134: return '/'.$udom.'/'.$uname;
7135: }
7136:
1.1011 raeburn 7137: # ------------------------------------------------------------------- Create ID
7138: sub generate_coursenum {
1.1038 raeburn 7139: my ($udom,$crstype) = @_;
1.1011 raeburn 7140: my $domdesc = &domain($udom);
7141: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7142: my $first;
7143: if ($crstype eq 'Community') {
7144: $first = '0';
7145: } else {
7146: $first = int(1+rand(9));
7147: }
7148: my $uname=$first.
1.1011 raeburn 7149: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7150: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7151: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7152: # ----------------------------------------------- Make sure that does not exist
7153: my $uhome=&homeserver($uname,$udom,'true');
7154: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7155: if ($crstype eq 'Community') {
7156: $first = '0';
7157: } else {
7158: $first = int(1+rand(9));
7159: }
7160: $uname=$first.
1.1011 raeburn 7161: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7162: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7163: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7164: $uhome=&homeserver($uname,$udom,'true');
7165: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7166: return 'error: unable to generate unique course-ID';
7167: }
7168: }
7169: return $uname;
7170: }
7171:
1.813 albertel 7172: sub is_course {
7173: my ($cdom,$cnum) = @_;
7174: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7175: undef,'.');
1.813 albertel 7176: if (exists($courses{$cdom.'_'.$cnum})) {
7177: return 1;
7178: }
7179: return 0;
7180: }
7181:
1.1015 raeburn 7182: sub store_userdata {
7183: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7184: my $result;
1.1016 raeburn 7185: if ($datakey ne '') {
1.1013 raeburn 7186: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7187: if ($udom eq '' || $uname eq '') {
7188: $udom = $env{'user.domain'};
7189: $uname = $env{'user.name'};
7190: }
7191: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7192: if (($uhome eq '') || ($uhome eq 'no_host')) {
7193: $result = 'error: no_host';
7194: } else {
7195: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7196: $storehash->{'host'} = $perlvar{'lonHostID'};
7197:
7198: my $namevalue='';
7199: foreach my $key (keys(%{$storehash})) {
7200: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7201: }
7202: $namevalue=~s/\&$//;
7203: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7204: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7205: }
7206: } else {
7207: $result = 'error: data to store was not a hash reference';
7208: }
7209: } else {
7210: $result= 'error: invalid requestkey';
7211: }
7212: return $result;
7213: }
7214:
1.21 www 7215: # ---------------------------------------------------------- Assign Custom Role
7216:
7217: sub assigncustomrole {
1.957 raeburn 7218: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7219: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7220: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7221: }
7222:
7223: # ----------------------------------------------------------------- Revoke Role
7224:
7225: sub revokerole {
1.957 raeburn 7226: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7227: my $now=time;
1.965 raeburn 7228: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7229: }
7230:
7231: # ---------------------------------------------------------- Revoke Custom Role
7232:
7233: sub revokecustomrole {
1.957 raeburn 7234: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7235: my $now=time;
1.357 www 7236: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7237: $deleteflag,$selfenroll,$context);
1.17 www 7238: }
7239:
1.533 banghart 7240: # ------------------------------------------------------------ Disk usage
1.535 albertel 7241: sub diskusage {
1.955 raeburn 7242: my ($udom,$uname,$directorypath,$getpropath)=@_;
7243: $directorypath =~ s/\/$//;
7244: my $listing=&reply('du2:'.&escape($directorypath).':'
7245: .&escape($getpropath).':'.&escape($uname).':'
7246: .&escape($udom),homeserver($uname,$udom));
7247: if ($listing eq 'unknown_cmd') {
7248: if ($getpropath) {
7249: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7250: }
7251: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7252: }
1.514 albertel 7253: return $listing;
1.512 banghart 7254: }
7255:
1.566 banghart 7256: sub is_locked {
7257: my ($file_name, $domain, $user) = @_;
7258: my @check;
7259: my $is_locked;
7260: push @check, $file_name;
1.613 albertel 7261: my %locked = &get('file_permissions',\@check,
1.620 albertel 7262: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7263: my ($tmp)=keys(%locked);
7264: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7265:
1.566 banghart 7266: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7267: $is_locked = 'false';
7268: foreach my $entry (@{$locked{$file_name}}) {
7269: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7270: $is_locked = 'true';
7271: last;
1.745 raeburn 7272: }
7273: }
1.566 banghart 7274: } else {
7275: $is_locked = 'false';
7276: }
7277: }
7278:
1.759 albertel 7279: sub declutter_portfile {
7280: my ($file) = @_;
1.833 albertel 7281: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7282: return $file;
7283: }
7284:
1.559 banghart 7285: # ------------------------------------------------------------- Mark as Read Only
7286:
7287: sub mark_as_readonly {
7288: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7289: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7290: my ($tmp)=keys(%current_permissions);
7291: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7292: foreach my $file (@{$files}) {
1.759 albertel 7293: $file = &declutter_portfile($file);
1.561 banghart 7294: push(@{$current_permissions{$file}},$what);
1.559 banghart 7295: }
1.613 albertel 7296: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7297: return;
7298: }
7299:
1.572 banghart 7300: # ------------------------------------------------------------Save Selected Files
7301:
7302: sub save_selected_files {
7303: my ($user, $path, @files) = @_;
7304: my $filename = $user."savedfiles";
1.573 banghart 7305: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7306: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7307: foreach my $file (@files) {
1.620 albertel 7308: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7309: }
7310: foreach my $file (@other_files) {
1.574 banghart 7311: print (OUT $file."\n");
1.572 banghart 7312: }
1.574 banghart 7313: close (OUT);
1.572 banghart 7314: return 'ok';
7315: }
7316:
1.574 banghart 7317: sub clear_selected_files {
7318: my ($user) = @_;
7319: my $filename = $user."savedfiles";
7320: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7321: print (OUT undef);
7322: close (OUT);
7323: return ("ok");
7324: }
7325:
1.572 banghart 7326: sub files_in_path {
7327: my ($user, $path) = @_;
7328: my $filename = $user."savedfiles";
7329: my %return_files;
1.574 banghart 7330: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7331: while (my $line_in = <IN>) {
1.574 banghart 7332: chomp ($line_in);
7333: my @paths_and_file = split (m!/!, $line_in);
7334: my $file_part = pop (@paths_and_file);
7335: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7336: $path_part.='/';
7337: my $path_and_file = $path_part.$file_part;
7338: if ($path_part eq $path) {
7339: $return_files{$file_part}= 'selected';
7340: }
7341: }
1.574 banghart 7342: close (IN);
7343: return (\%return_files);
1.572 banghart 7344: }
7345:
7346: # called in portfolio select mode, to show files selected NOT in current directory
7347: sub files_not_in_path {
7348: my ($user, $path) = @_;
7349: my $filename = $user."savedfiles";
7350: my @return_files;
7351: my $path_part;
1.800 albertel 7352: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7353: while (my $line = <IN>) {
1.572 banghart 7354: #ok, I know it's clunky, but I want it to work
1.800 albertel 7355: my @paths_and_file = split(m|/|, $line);
7356: my $file_part = pop(@paths_and_file);
7357: chomp($file_part);
7358: my $path_part = join('/', @paths_and_file);
1.572 banghart 7359: $path_part .= '/';
7360: my $path_and_file = $path_part.$file_part;
7361: if ($path_part ne $path) {
1.800 albertel 7362: push(@return_files, ($path_and_file));
1.572 banghart 7363: }
7364: }
1.800 albertel 7365: close(OUT);
1.574 banghart 7366: return (@return_files);
1.572 banghart 7367: }
7368:
1.745 raeburn 7369: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7370:
1.745 raeburn 7371: sub get_portfile_permissions {
7372: my ($domain,$user) = @_;
1.613 albertel 7373: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7374: my ($tmp)=keys(%current_permissions);
7375: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7376: return \%current_permissions;
7377: }
7378:
7379: #---------------------------------------------Get portfolio file access controls
7380:
1.749 raeburn 7381: sub get_access_controls {
1.745 raeburn 7382: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7383: my %access;
7384: my $real_file = $file;
7385: $file =~ s/\.meta$//;
1.745 raeburn 7386: if (defined($file)) {
1.749 raeburn 7387: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7388: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7389: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7390: }
7391: }
1.745 raeburn 7392: } else {
1.749 raeburn 7393: foreach my $key (keys(%{$current_permissions})) {
7394: if ($key =~ /\0accesscontrol$/) {
7395: if (defined($group)) {
7396: if ($key !~ m-^\Q$group\E/-) {
7397: next;
7398: }
7399: }
7400: my ($fullpath) = split(/\0/,$key);
7401: if (ref($$current_permissions{$key}) eq 'HASH') {
7402: foreach my $control (keys(%{$$current_permissions{$key}})) {
7403: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7404: }
7405: }
7406: }
7407: }
7408: }
7409: return %access;
7410: }
7411:
7412: sub modify_access_controls {
7413: my ($file_name,$changes,$domain,$user)=@_;
7414: my ($outcome,$deloutcome);
7415: my %store_permissions;
7416: my %new_values;
7417: my %new_control;
7418: my %translation;
7419: my @deletions = ();
7420: my $now = time;
7421: if (exists($$changes{'activate'})) {
7422: if (ref($$changes{'activate'}) eq 'HASH') {
7423: my @newitems = sort(keys(%{$$changes{'activate'}}));
7424: my $numnew = scalar(@newitems);
7425: for (my $i=0; $i<$numnew; $i++) {
7426: my $newkey = $newitems[$i];
7427: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7428: if ($newkey =~ /^\d+:/) {
7429: $newkey =~ s/^(\d+)/$newid/;
7430: $translation{$1} = $newid;
7431: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7432: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7433: $translation{$1} = $newid;
7434: }
1.749 raeburn 7435: $new_values{$file_name."\0".$newkey} =
7436: $$changes{'activate'}{$newitems[$i]};
7437: $new_control{$newkey} = $now;
7438: }
7439: }
7440: }
7441: my %todelete;
7442: my %changed_items;
7443: foreach my $action ('delete','update') {
7444: if (exists($$changes{$action})) {
7445: if (ref($$changes{$action}) eq 'HASH') {
7446: foreach my $key (keys(%{$$changes{$action}})) {
7447: my ($itemnum) = ($key =~ /^([^:]+):/);
7448: if ($action eq 'delete') {
7449: $todelete{$itemnum} = 1;
7450: } else {
7451: $changed_items{$itemnum} = $key;
7452: }
7453: }
1.745 raeburn 7454: }
7455: }
1.749 raeburn 7456: }
7457: # get lock on access controls for file.
7458: my $lockhash = {
7459: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7460: ':'.$env{'user.domain'},
7461: };
7462: my $tries = 0;
7463: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7464:
7465: while (($gotlock ne 'ok') && $tries <3) {
7466: $tries ++;
7467: sleep 1;
7468: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7469: }
7470: if ($gotlock eq 'ok') {
7471: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7472: my ($tmp)=keys(%curr_permissions);
7473: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7474: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7475: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7476: if (ref($curr_controls) eq 'HASH') {
7477: foreach my $control_item (keys(%{$curr_controls})) {
7478: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7479: if (defined($todelete{$itemnum})) {
7480: push(@deletions,$file_name."\0".$control_item);
7481: } else {
7482: if (defined($changed_items{$itemnum})) {
7483: $new_control{$changed_items{$itemnum}} = $now;
7484: push(@deletions,$file_name."\0".$control_item);
7485: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7486: } else {
7487: $new_control{$control_item} = $$curr_controls{$control_item};
7488: }
7489: }
1.745 raeburn 7490: }
7491: }
7492: }
1.970 raeburn 7493: my ($group);
7494: if (&is_course($domain,$user)) {
7495: ($group,my $file) = split(/\//,$file_name,2);
7496: }
1.749 raeburn 7497: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7498: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7499: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7500: # remove lock
7501: my @del_lock = ($file_name."\0".'locked_access_records');
7502: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7503: my $sqlresult =
1.970 raeburn 7504: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7505: $group);
1.749 raeburn 7506: } else {
7507: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7508: }
1.749 raeburn 7509: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7510: }
7511:
1.827 raeburn 7512: sub make_public_indefinitely {
7513: my ($requrl) = @_;
7514: my $now = time;
7515: my $action = 'activate';
7516: my $aclnum = 0;
7517: if (&is_portfolio_url($requrl)) {
7518: my (undef,$udom,$unum,$file_name,$group) =
7519: &parse_portfolio_url($requrl);
7520: my $current_perms = &get_portfile_permissions($udom,$unum);
7521: my %access_controls = &get_access_controls($current_perms,
7522: $group,$file_name);
7523: foreach my $key (keys(%{$access_controls{$file_name}})) {
7524: my ($num,$scope,$end,$start) =
7525: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7526: if ($scope eq 'public') {
7527: if ($start <= $now && $end == 0) {
7528: $action = 'none';
7529: } else {
7530: $action = 'update';
7531: $aclnum = $num;
7532: }
7533: last;
7534: }
7535: }
7536: if ($action eq 'none') {
7537: return 'ok';
7538: } else {
7539: my %changes;
7540: my $newend = 0;
7541: my $newstart = $now;
7542: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7543: $changes{$action}{$newkey} = {
7544: type => 'public',
7545: time => {
7546: start => $newstart,
7547: end => $newend,
7548: },
7549: };
7550: my ($outcome,$deloutcome,$new_values,$translation) =
7551: &modify_access_controls($file_name,\%changes,$udom,$unum);
7552: return $outcome;
7553: }
7554: } else {
7555: return 'invalid';
7556: }
7557: }
7558:
1.745 raeburn 7559: #------------------------------------------------------Get Marked as Read Only
7560:
7561: sub get_marked_as_readonly {
7562: my ($domain,$user,$what,$group) = @_;
7563: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7564: my @readonly_files;
1.629 banghart 7565: my $cmp1=$what;
7566: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7567: while (my ($file_name,$value) = each(%{$current_permissions})) {
7568: if (defined($group)) {
7569: if ($file_name !~ m-^\Q$group\E/-) {
7570: next;
7571: }
7572: }
1.561 banghart 7573: if (ref($value) eq "ARRAY"){
7574: foreach my $stored_what (@{$value}) {
1.629 banghart 7575: my $cmp2=$stored_what;
1.759 albertel 7576: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7577: $cmp2=join('',@{$stored_what});
1.745 raeburn 7578: }
1.629 banghart 7579: if ($cmp1 eq $cmp2) {
1.561 banghart 7580: push(@readonly_files, $file_name);
1.745 raeburn 7581: last;
1.563 banghart 7582: } elsif (!defined($what)) {
7583: push(@readonly_files, $file_name);
1.745 raeburn 7584: last;
1.561 banghart 7585: }
7586: }
1.745 raeburn 7587: }
1.561 banghart 7588: }
7589: return @readonly_files;
7590: }
1.577 banghart 7591: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7592:
1.577 banghart 7593: sub get_marked_as_readonly_hash {
1.745 raeburn 7594: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7595: my %readonly_files;
1.745 raeburn 7596: while (my ($file_name,$value) = each(%{$current_permissions})) {
7597: if (defined($group)) {
7598: if ($file_name !~ m-^\Q$group\E/-) {
7599: next;
7600: }
7601: }
1.577 banghart 7602: if (ref($value) eq "ARRAY"){
7603: foreach my $stored_what (@{$value}) {
1.745 raeburn 7604: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7605: foreach my $lock_descriptor(@{$stored_what}) {
7606: if ($lock_descriptor eq 'graded') {
7607: $readonly_files{$file_name} = 'graded';
7608: } elsif ($lock_descriptor eq 'handback') {
7609: $readonly_files{$file_name} = 'handback';
7610: } else {
7611: if (!exists($readonly_files{$file_name})) {
7612: $readonly_files{$file_name} = 'locked';
7613: }
7614: }
1.745 raeburn 7615: }
1.750 banghart 7616: }
1.577 banghart 7617: }
7618: }
7619: }
7620: return %readonly_files;
7621: }
1.559 banghart 7622: # ------------------------------------------------------------ Unmark as Read Only
7623:
7624: sub unmark_as_readonly {
1.629 banghart 7625: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7626: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7627: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7628: $file_name = &declutter_portfile($file_name);
1.634 albertel 7629: my $symb_crs = $what;
7630: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7631: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7632: my ($tmp)=keys(%current_permissions);
7633: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7634: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7635: foreach my $file (@readonly_files) {
1.759 albertel 7636: my $clean_file = &declutter_portfile($file);
7637: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7638: my $current_locks = $current_permissions{$file};
1.563 banghart 7639: my @new_locks;
7640: my @del_keys;
7641: if (ref($current_locks) eq "ARRAY"){
7642: foreach my $locker (@{$current_locks}) {
1.632 albertel 7643: my $compare=$locker;
1.749 raeburn 7644: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7645: $compare=join('',@{$locker});
1.746 raeburn 7646: if ($compare ne $symb_crs) {
7647: push(@new_locks, $locker);
7648: }
1.563 banghart 7649: }
7650: }
1.650 albertel 7651: if (scalar(@new_locks) > 0) {
1.563 banghart 7652: $current_permissions{$file} = \@new_locks;
7653: } else {
7654: push(@del_keys, $file);
1.613 albertel 7655: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7656: delete($current_permissions{$file});
1.563 banghart 7657: }
7658: }
1.561 banghart 7659: }
1.613 albertel 7660: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7661: return;
7662: }
1.512 banghart 7663:
1.17 www 7664: # ------------------------------------------------------------ Directory lister
7665:
7666: sub dirlist {
1.955 raeburn 7667: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7668: $uri=~s/^\///;
7669: $uri=~s/\/$//;
1.253 stredwic 7670: my ($udom, $uname);
1.955 raeburn 7671: if ($getuserdir) {
1.253 stredwic 7672: $udom = $userdomain;
7673: $uname = $username;
1.955 raeburn 7674: } else {
7675: (undef,$udom,$uname)=split(/\//,$uri);
7676: if(defined($userdomain)) {
7677: $udom = $userdomain;
7678: }
7679: if(defined($username)) {
7680: $uname = $username;
7681: }
1.253 stredwic 7682: }
1.955 raeburn 7683: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7684:
1.955 raeburn 7685: $dirRoot = $perlvar{'lonDocRoot'};
7686: if (defined($getpropath)) {
7687: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7688: $dirRoot =~ s/\/$//;
1.955 raeburn 7689: } elsif (defined($getuserdir)) {
7690: my $subdir=$uname.'__';
7691: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7692: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7693: ."/$udom/$subdir/$uname";
7694: } elsif (defined($alternateRoot)) {
7695: $dirRoot = $alternateRoot;
1.751 banghart 7696: }
1.253 stredwic 7697:
7698: if($udom) {
7699: if($uname) {
1.955 raeburn 7700: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7701: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7702: .':'.&escape($uname).':'.&escape($udom),
7703: &homeserver($uname,$udom));
7704: if ($listing eq 'unknown_cmd') {
7705: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7706: &homeserver($uname,$udom));
7707: } else {
7708: @listing_results = map { &unescape($_); } split(/:/,$listing);
7709: }
1.605 matthew 7710: if ($listing eq 'unknown_cmd') {
1.800 albertel 7711: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7712: &homeserver($uname,$udom));
1.605 matthew 7713: @listing_results = split(/:/,$listing);
7714: } else {
7715: @listing_results = map { &unescape($_); } split(/:/,$listing);
7716: }
7717: return @listing_results;
1.955 raeburn 7718: } elsif(!$alternateRoot) {
1.800 albertel 7719: my %allusers;
1.841 albertel 7720: my %servers = &get_servers($udom,'library');
1.955 raeburn 7721: foreach my $tryserver (keys(%servers)) {
7722: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7723: &escape($udom),$tryserver);
7724: if ($listing eq 'unknown_cmd') {
7725: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7726: $udom, $tryserver);
7727: } else {
7728: @listing_results = map { &unescape($_); } split(/:/,$listing);
7729: }
1.841 albertel 7730: if ($listing eq 'unknown_cmd') {
7731: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7732: $udom, $tryserver);
7733: @listing_results = split(/:/,$listing);
7734: } else {
7735: @listing_results =
7736: map { &unescape($_); } split(/:/,$listing);
7737: }
7738: if ($listing_results[0] ne 'no_such_dir' &&
7739: $listing_results[0] ne 'empty' &&
7740: $listing_results[0] ne 'con_lost') {
7741: foreach my $line (@listing_results) {
7742: my ($entry) = split(/&/,$line,2);
7743: $allusers{$entry} = 1;
7744: }
7745: }
1.253 stredwic 7746: }
7747: my $alluserstr='';
1.800 albertel 7748: foreach my $user (sort(keys(%allusers))) {
7749: $alluserstr.=$user.'&user:';
1.253 stredwic 7750: }
7751: $alluserstr=~s/:$//;
7752: return split(/:/,$alluserstr);
7753: } else {
1.800 albertel 7754: return ('missing user name');
1.253 stredwic 7755: }
1.955 raeburn 7756: } elsif(!defined($getpropath)) {
1.841 albertel 7757: my @all_domains = sort(&all_domains());
1.955 raeburn 7758: foreach my $domain (@all_domains) {
7759: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7760: }
7761: return @all_domains;
7762: } else {
1.800 albertel 7763: return ('missing domain');
1.275 stredwic 7764: }
7765: }
7766:
7767: # --------------------------------------------- GetFileTimestamp
7768: # This function utilizes dirlist and returns the date stamp for
7769: # when it was last modified. It will also return an error of -1
7770: # if an error occurs
7771:
7772: sub GetFileTimestamp {
1.955 raeburn 7773: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7774: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7775: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7776: my ($fileStat) =
7777: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7778: undef,$getuserdir);
1.275 stredwic 7779: my @stats = split('&', $fileStat);
7780: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7781: # @stats contains first the filename, then the stat output
7782: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7783: } else {
7784: return -1;
1.253 stredwic 7785: }
1.26 www 7786: }
7787:
1.712 albertel 7788: sub stat_file {
7789: my ($uri) = @_;
1.787 albertel 7790: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7791:
1.955 raeburn 7792: my ($udom,$uname,$file);
1.712 albertel 7793: if ($uri =~ m-^/(uploaded|editupload)/-) {
7794: ($udom,$uname,$file) =
1.811 albertel 7795: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7796: $file = 'userfiles/'.$file;
7797: }
7798: if ($uri =~ m-^/res/-) {
7799: ($udom,$uname) =
1.807 albertel 7800: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7801: $file = $uri;
7802: }
7803:
7804: if (!$udom || !$uname || !$file) {
7805: # unable to handle the uri
7806: return ();
7807: }
1.956 raeburn 7808: my $getpropath;
7809: if ($file =~ /^userfiles\//) {
7810: $getpropath = 1;
7811: }
1.955 raeburn 7812: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7813: my @stats = split('&', $result);
1.721 banghart 7814:
1.712 albertel 7815: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7816: shift(@stats); #filename is first
7817: return @stats;
7818: }
7819: return ();
7820: }
7821:
1.26 www 7822: # -------------------------------------------------------- Value of a Condition
7823:
1.713 albertel 7824: # gets the value of a specific preevaluated condition
7825: # stored in the string $env{user.state.<cid>}
7826: # or looks up a condition reference in the bighash and if if hasn't
7827: # already been evaluated recurses into docondval to get the value of
7828: # the condition, then memoizing it to
7829: # $env{user.state.<cid>.<condition>}
1.40 www 7830: sub directcondval {
7831: my $number=shift;
1.620 albertel 7832: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7833: &Apache::lonuserstate::evalstate();
7834: }
1.713 albertel 7835: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7836: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7837: } elsif ($number =~ /^_/) {
7838: my $sub_condition;
7839: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7840: &GDBM_READER(),0640)) {
7841: $sub_condition=$bighash{'conditions'.$number};
7842: untie(%bighash);
7843: }
7844: my $value = &docondval($sub_condition);
1.949 raeburn 7845: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7846: return $value;
7847: }
1.620 albertel 7848: if ($env{'user.state.'.$env{'request.course.id'}}) {
7849: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7850: } else {
7851: return 2;
7852: }
7853: }
7854:
1.713 albertel 7855: # get the collection of conditions for this resource
1.26 www 7856: sub condval {
7857: my $condidx=shift;
1.54 www 7858: my $allpathcond='';
1.713 albertel 7859: foreach my $cond (split(/\|/,$condidx)) {
7860: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7861: $allpathcond.=
7862: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7863: }
1.191 harris41 7864: }
1.54 www 7865: $allpathcond=~s/\|$//;
1.713 albertel 7866: return &docondval($allpathcond);
7867: }
7868:
7869: #evaluates an expression of conditions
7870: sub docondval {
7871: my ($allpathcond) = @_;
7872: my $result=0;
7873: if ($env{'request.course.id'}
7874: && defined($allpathcond)) {
7875: my $operand='|';
7876: my @stack;
7877: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7878: if ($chunk eq '(') {
7879: push @stack,($operand,$result);
7880: } elsif ($chunk eq ')') {
7881: my $before=pop @stack;
7882: if (pop @stack eq '&') {
7883: $result=$result>$before?$before:$result;
7884: } else {
7885: $result=$result>$before?$result:$before;
7886: }
7887: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7888: $operand=$chunk;
7889: } else {
7890: my $new=directcondval($chunk);
7891: if ($operand eq '&') {
7892: $result=$result>$new?$new:$result;
7893: } else {
7894: $result=$result>$new?$result:$new;
7895: }
7896: }
7897: }
1.26 www 7898: }
7899: return $result;
1.421 albertel 7900: }
7901:
7902: # ---------------------------------------------------- Devalidate courseresdata
7903:
7904: sub devalidatecourseresdata {
7905: my ($coursenum,$coursedomain)=@_;
7906: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7907: &devalidate_cache_new('courseres',$hashid);
1.28 www 7908: }
7909:
1.763 www 7910:
1.200 www 7911: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7912: #
7913: # Parameters:
7914: # $coursenum - Number of the course.
7915: # $coursedomain - Domain at which the course was created.
7916: # Returns:
7917: # A hash of the course parameters along (I think) with timestamps
7918: # and version info.
1.877 foxr 7919:
1.624 albertel 7920: sub get_courseresdata {
7921: my ($coursenum,$coursedomain)=@_;
1.200 www 7922: my $coursehom=&homeserver($coursenum,$coursedomain);
7923: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7924: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7925: my %dumpreply;
1.417 albertel 7926: unless (defined($cached)) {
1.624 albertel 7927: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7928: $result=\%dumpreply;
1.251 albertel 7929: my ($tmp) = keys(%dumpreply);
7930: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7931: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7932: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7933: return $tmp;
1.416 albertel 7934: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7935: $result=undef;
1.599 albertel 7936: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7937: }
7938: }
1.624 albertel 7939: return $result;
7940: }
7941:
1.633 albertel 7942: sub devalidateuserresdata {
7943: my ($uname,$udom)=@_;
7944: my $hashid="$udom:$uname";
7945: &devalidate_cache_new('userres',$hashid);
7946: }
7947:
1.624 albertel 7948: sub get_userresdata {
7949: my ($uname,$udom)=@_;
7950: #most student don\'t have any data set, check if there is some data
7951: if (&EXT_cache_status($udom,$uname)) { return undef; }
7952:
7953: my $hashid="$udom:$uname";
7954: my ($result,$cached)=&is_cached_new('userres',$hashid);
7955: if (!defined($cached)) {
7956: my %resourcedata=&dump('resourcedata',$udom,$uname);
7957: $result=\%resourcedata;
7958: &do_cache_new('userres',$hashid,$result,600);
7959: }
7960: my ($tmp)=keys(%$result);
7961: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7962: return $result;
7963: }
7964: #error 2 occurs when the .db doesn't exist
7965: if ($tmp!~/error: 2 /) {
1.672 albertel 7966: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7967: " Trying to get resource data for ".
7968: $uname." at ".$udom.": ".
7969: $tmp."</font>");
7970: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7971: #&EXT_cache_set($udom,$uname);
7972: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7973: undef($tmp); # not really an error so don't send it back
1.624 albertel 7974: }
7975: return $tmp;
7976: }
1.879 foxr 7977: #----------------------------------------------- resdata - return resource data
7978: # Purpose:
7979: # Return resource data for either users or for a course.
7980: # Parameters:
7981: # $name - Course/user name.
7982: # $domain - Name of the domain the user/course is registered on.
7983: # $type - Type of thing $name is (must be 'course' or 'user'
7984: # @which - Array of names of resources desired.
7985: # Returns:
7986: # The value of the first reasource in @which that is found in the
7987: # resource hash.
7988: # Exceptional Conditions:
7989: # If the $type passed in is not valid (not the string 'course' or
7990: # 'user', an undefined reference is returned.
7991: # If none of the resources are found, an undef is returned
1.624 albertel 7992: sub resdata {
7993: my ($name,$domain,$type,@which)=@_;
7994: my $result;
7995: if ($type eq 'course') {
7996: $result=&get_courseresdata($name,$domain);
7997: } elsif ($type eq 'user') {
7998: $result=&get_userresdata($name,$domain);
7999: }
8000: if (!ref($result)) { return $result; }
1.251 albertel 8001: foreach my $item (@which) {
1.927 albertel 8002: if (defined($result->{$item->[0]})) {
8003: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8004: }
1.250 albertel 8005: }
1.291 albertel 8006: return undef;
1.200 www 8007: }
8008:
1.379 matthew 8009: #
8010: # EXT resource caching routines
8011: #
8012:
8013: sub clear_EXT_cache_status {
1.383 albertel 8014: &delenv('cache.EXT.');
1.379 matthew 8015: }
8016:
8017: sub EXT_cache_status {
8018: my ($target_domain,$target_user) = @_;
1.383 albertel 8019: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8020: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8021: # We know already the user has no data
8022: return 1;
8023: } else {
8024: return 0;
8025: }
8026: }
8027:
8028: sub EXT_cache_set {
8029: my ($target_domain,$target_user) = @_;
1.383 albertel 8030: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8031: #&appenv({$cachename => time});
1.379 matthew 8032: }
8033:
1.28 www 8034: # --------------------------------------------------------- Value of a Variable
1.58 www 8035: sub EXT {
1.715 albertel 8036:
1.395 albertel 8037: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8038: unless ($varname) { return ''; }
1.218 albertel 8039: #get real user name/domain, courseid and symb
8040: my $courseid;
1.359 albertel 8041: my $publicuser;
1.427 www 8042: if ($symbparm) {
8043: $symbparm=&get_symb_from_alias($symbparm);
8044: }
1.218 albertel 8045: if (!($uname && $udom)) {
1.790 albertel 8046: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8047: if (!$symbparm) { $symbparm=$cursymb; }
8048: } else {
1.620 albertel 8049: $courseid=$env{'request.course.id'};
1.218 albertel 8050: }
1.48 www 8051: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8052: my $rest;
1.320 albertel 8053: if (defined($therest[0])) {
1.48 www 8054: $rest=join('.',@therest);
8055: } else {
8056: $rest='';
8057: }
1.320 albertel 8058:
1.57 www 8059: my $qualifierrest=$qualifier;
8060: if ($rest) { $qualifierrest.='.'.$rest; }
8061: my $spacequalifierrest=$space;
8062: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8063: if ($realm eq 'user') {
1.48 www 8064: # --------------------------------------------------------------- user.resource
8065: if ($space eq 'resource') {
1.651 albertel 8066: if ( (defined($Apache::lonhomework::parsing_a_problem)
8067: || defined($Apache::lonhomework::parsing_a_task))
8068: &&
1.744 albertel 8069: ($symbparm eq &symbread()) ) {
8070: # if we are in the middle of processing the resource the
8071: # get the value we are planning on committing
8072: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8073: return $Apache::lonhomework::results{$qualifierrest};
8074: } else {
8075: return $Apache::lonhomework::history{$qualifierrest};
8076: }
1.335 albertel 8077: } else {
1.359 albertel 8078: my %restored;
1.620 albertel 8079: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8080: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8081: } else {
8082: %restored=&restore($symbparm,$courseid,$udom,$uname);
8083: }
1.335 albertel 8084: return $restored{$qualifierrest};
8085: }
1.48 www 8086: # ----------------------------------------------------------------- user.access
8087: } elsif ($space eq 'access') {
1.218 albertel 8088: # FIXME - not supporting calls for a specific user
1.48 www 8089: return &allowed($qualifier,$rest);
8090: # ------------------------------------------ user.preferences, user.environment
8091: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8092: if (($uname eq $env{'user.name'}) &&
8093: ($udom eq $env{'user.domain'})) {
8094: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8095: } else {
1.359 albertel 8096: my %returnhash;
8097: if (!$publicuser) {
8098: %returnhash=&userenvironment($udom,$uname,
8099: $qualifierrest);
8100: }
1.218 albertel 8101: return $returnhash{$qualifierrest};
8102: }
1.48 www 8103: # ----------------------------------------------------------------- user.course
8104: } elsif ($space eq 'course') {
1.218 albertel 8105: # FIXME - not supporting calls for a specific user
1.620 albertel 8106: return $env{join('.',('request.course',$qualifier))};
1.48 www 8107: # ------------------------------------------------------------------- user.role
8108: } elsif ($space eq 'role') {
1.218 albertel 8109: # FIXME - not supporting calls for a specific user
1.620 albertel 8110: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8111: if ($qualifier eq 'value') {
8112: return $role;
8113: } elsif ($qualifier eq 'extent') {
8114: return $where;
8115: }
8116: # ----------------------------------------------------------------- user.domain
8117: } elsif ($space eq 'domain') {
1.218 albertel 8118: return $udom;
1.48 www 8119: # ------------------------------------------------------------------- user.name
8120: } elsif ($space eq 'name') {
1.218 albertel 8121: return $uname;
1.48 www 8122: # ---------------------------------------------------- Any other user namespace
1.29 www 8123: } else {
1.359 albertel 8124: my %reply;
8125: if (!$publicuser) {
8126: %reply=&get($space,[$qualifierrest],$udom,$uname);
8127: }
8128: return $reply{$qualifierrest};
1.48 www 8129: }
1.236 www 8130: } elsif ($realm eq 'query') {
8131: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8132: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8133: [$spacequalifierrest]);
1.620 albertel 8134: return $env{'form.'.$spacequalifierrest};
1.236 www 8135: } elsif ($realm eq 'request') {
1.48 www 8136: # ------------------------------------------------------------- request.browser
8137: if ($space eq 'browser') {
1.430 www 8138: if ($qualifier eq 'textremote') {
1.676 albertel 8139: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8140: return 1;
8141: } else {
8142: return 0;
8143: }
8144: } else {
1.620 albertel 8145: return $env{'browser.'.$qualifier};
1.430 www 8146: }
1.57 www 8147: # ------------------------------------------------------------ request.filename
8148: } else {
1.620 albertel 8149: return $env{'request.'.$spacequalifierrest};
1.29 www 8150: }
1.28 www 8151: } elsif ($realm eq 'course') {
1.48 www 8152: # ---------------------------------------------------------- course.description
1.620 albertel 8153: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8154: } elsif ($realm eq 'resource') {
1.165 www 8155:
1.620 albertel 8156: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8157: if (!$symbparm) { $symbparm=&symbread(); }
8158: }
1.693 albertel 8159:
8160: if ($space eq 'title') {
8161: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8162: return &gettitle($symbparm);
8163: }
8164:
8165: if ($space eq 'map') {
8166: my ($map) = &decode_symb($symbparm);
8167: return &symbread($map);
8168: }
1.905 albertel 8169: if ($space eq 'filename') {
8170: if ($symbparm) {
8171: return &clutter((&decode_symb($symbparm))[2]);
8172: }
8173: return &hreflocation('',$env{'request.filename'});
8174: }
1.693 albertel 8175:
8176: my ($section, $group, @groups);
1.593 albertel 8177: my ($courselevelm,$courselevel);
1.539 albertel 8178: if ($symbparm && defined($courseid) &&
1.620 albertel 8179: $courseid eq $env{'request.course.id'}) {
1.165 www 8180:
1.218 albertel 8181: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8182:
1.60 www 8183: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8184: my $symbp=$symbparm;
1.735 albertel 8185: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8186:
8187: my $symbparm=$symbp.'.'.$spacequalifierrest;
8188: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8189:
1.620 albertel 8190: if (($env{'user.name'} eq $uname) &&
8191: ($env{'user.domain'} eq $udom)) {
8192: $section=$env{'request.course.sec'};
1.733 raeburn 8193: @groups = split(/:/,$env{'request.course.groups'});
8194: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8195: } else {
1.539 albertel 8196: if (! defined($usection)) {
1.551 albertel 8197: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8198: } else {
8199: $section = $usection;
8200: }
1.733 raeburn 8201: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8202: }
8203:
8204: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8205: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8206: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8207:
1.593 albertel 8208: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8209: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8210: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8211:
1.60 www 8212: # ----------------------------------------------------------- first, check user
1.624 albertel 8213:
8214: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8215: ([$courselevelr,'resource'],
8216: [$courselevelm,'map' ],
8217: [$courselevel, 'course' ]));
1.931 albertel 8218: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8219:
1.594 albertel 8220: # ------------------------------------------------ second, check some of course
1.684 raeburn 8221: my $coursereply;
1.691 raeburn 8222: if (@groups > 0) {
8223: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8224: $mapparm,$spacequalifierrest);
1.927 albertel 8225: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8226: }
1.96 www 8227:
1.684 raeburn 8228: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8229: $env{'course.'.$courseid.'.domain'},
8230: 'course',
8231: ([$seclevelr, 'resource'],
8232: [$seclevelm, 'map' ],
8233: [$seclevel, 'course' ],
8234: [$courselevelr,'resource']));
8235: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8236:
1.60 www 8237: # ------------------------------------------------------ third, check map parms
1.218 albertel 8238: my %parmhash=();
8239: my $thisparm='';
8240: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8241: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8242: &GDBM_READER(),0640)) {
1.218 albertel 8243: $thisparm=$parmhash{$symbparm};
8244: untie(%parmhash);
8245: }
1.927 albertel 8246: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8247: }
1.594 albertel 8248: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8249:
1.218 albertel 8250: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8251: my $filename;
8252: if (!$symbparm) { $symbparm=&symbread(); }
8253: if ($symbparm) {
1.409 www 8254: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8255: } else {
1.620 albertel 8256: $filename=$env{'request.filename'};
1.282 albertel 8257: }
8258: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8259: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8260: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8261: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8262:
1.927 albertel 8263: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8264: if ($symbparm && defined($courseid) &&
1.620 albertel 8265: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8266: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8267: $env{'course.'.$courseid.'.domain'},
8268: 'course',
1.927 albertel 8269: ([$courselevelm,'map' ],
8270: [$courselevel, 'course']));
8271: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8272: }
1.145 www 8273: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8274: unless ($space eq '0') {
1.336 albertel 8275: my @parts=split(/_/,$space);
8276: my $id=pop(@parts);
8277: my $part=join('_',@parts);
8278: if ($part eq '') { $part='0'; }
1.927 albertel 8279: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8280: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8281: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8282: }
1.395 albertel 8283: if ($recurse) { return undef; }
8284: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8285: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8286: # ---------------------------------------------------- Any other user namespace
8287: } elsif ($realm eq 'environment') {
8288: # ----------------------------------------------------------------- environment
1.620 albertel 8289: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8290: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8291: } else {
1.770 albertel 8292: if ($uname eq 'anonymous' && $udom eq '') {
8293: return '';
8294: }
1.219 albertel 8295: my %returnhash=&userenvironment($udom,$uname,
8296: $spacequalifierrest);
8297: return $returnhash{$spacequalifierrest};
8298: }
1.28 www 8299: } elsif ($realm eq 'system') {
1.48 www 8300: # ----------------------------------------------------------------- system.time
8301: if ($space eq 'time') {
8302: return time;
8303: }
1.696 albertel 8304: } elsif ($realm eq 'server') {
8305: # ----------------------------------------------------------------- system.time
8306: if ($space eq 'name') {
8307: return $ENV{'SERVER_NAME'};
8308: }
1.28 www 8309: }
1.48 www 8310: return '';
1.61 www 8311: }
8312:
1.927 albertel 8313: sub get_reply {
8314: my ($reply_value) = @_;
1.940 raeburn 8315: if (ref($reply_value) eq 'ARRAY') {
8316: if (wantarray) {
8317: return @$reply_value;
8318: }
8319: return $reply_value->[0];
8320: } else {
8321: return $reply_value;
1.927 albertel 8322: }
8323: }
8324:
1.691 raeburn 8325: sub check_group_parms {
8326: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8327: my @groupitems = ();
8328: my $resultitem;
1.927 albertel 8329: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8330: foreach my $group (@{$groups}) {
8331: foreach my $level (@levels) {
1.927 albertel 8332: my $item = $courseid.'.['.$group.'].'.$level->[0];
8333: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8334: }
8335: }
8336: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8337: $env{'course.'.$courseid.'.domain'},
8338: 'course',@groupitems);
8339: return $coursereply;
8340: }
8341:
8342: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8343: my ($courseid,@groups) = @_;
8344: @groups = sort(@groups);
1.691 raeburn 8345: return @groups;
8346: }
8347:
1.395 albertel 8348: sub packages_tab_default {
8349: my ($uri,$varname)=@_;
8350: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8351:
8352: my (@extension,@specifics,$do_default);
8353: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8354: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8355: if ($pack_type eq 'default') {
8356: $do_default=1;
8357: } elsif ($pack_type eq 'extension') {
8358: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8359: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8360: # only look at packages defaults for packages that this id is
1.738 albertel 8361: push(@specifics,[$package,$pack_type,$pack_part]);
8362: }
8363: }
8364: # first look for a package that matches the requested part id
8365: foreach my $package (@specifics) {
8366: my (undef,$pack_type,$pack_part)=@{$package};
8367: next if ($pack_part ne $part);
8368: if (defined($packagetab{"$pack_type&$name&default"})) {
8369: return $packagetab{"$pack_type&$name&default"};
8370: }
8371: }
8372: # look for any possible matching non extension_ package
8373: foreach my $package (@specifics) {
8374: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8375: if (defined($packagetab{"$pack_type&$name&default"})) {
8376: return $packagetab{"$pack_type&$name&default"};
8377: }
1.585 albertel 8378: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8379: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8380: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8381: }
8382: }
1.738 albertel 8383: # look for any posible extension_ match
8384: foreach my $package (@extension) {
8385: my ($package,$pack_type)=@{$package};
8386: if (defined($packagetab{"$pack_type&$name&default"})) {
8387: return $packagetab{"$pack_type&$name&default"};
8388: }
8389: if (defined($packagetab{$package."&$name&default"})) {
8390: return $packagetab{$package."&$name&default"};
8391: }
8392: }
8393: # look for a global default setting
8394: if ($do_default && defined($packagetab{"default&$name&default"})) {
8395: return $packagetab{"default&$name&default"};
8396: }
1.395 albertel 8397: return undef;
8398: }
8399:
1.334 albertel 8400: sub add_prefix_and_part {
8401: my ($prefix,$part)=@_;
8402: my $keyroot;
8403: if (defined($prefix) && $prefix !~ /^__/) {
8404: # prefix that has a part already
8405: $keyroot=$prefix;
8406: } elsif (defined($prefix)) {
8407: # prefix that is missing a part
8408: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8409: } else {
8410: # no prefix at all
8411: if (defined($part)) { $keyroot='_'.$part; }
8412: }
8413: return $keyroot;
8414: }
8415:
1.71 www 8416: # ---------------------------------------------------------------- Get metadata
8417:
1.599 albertel 8418: my %metaentry;
1.71 www 8419: sub metadata {
1.176 www 8420: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8421: $uri=&declutter($uri);
1.288 albertel 8422: # if it is a non metadata possible uri return quickly
1.529 albertel 8423: if (($uri eq '') ||
8424: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8425: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8426: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8427: return undef;
8428: }
8429: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8430: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8431: return undef;
1.288 albertel 8432: }
1.73 www 8433: my $filename=$uri;
8434: $uri=~s/\.meta$//;
1.172 www 8435: #
8436: # Is the metadata already cached?
1.177 www 8437: # Look at timestamp of caching
1.172 www 8438: # Everything is cached by the main uri, libraries are never directly cached
8439: #
1.428 albertel 8440: if (!defined($liburi)) {
1.599 albertel 8441: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8442: if (defined($cached)) { return $result->{':'.$what}; }
8443: }
8444: {
1.172 www 8445: #
8446: # Is this a recursive call for a library?
8447: #
1.599 albertel 8448: # if (! exists($metacache{$uri})) {
8449: # $metacache{$uri}={};
8450: # }
1.924 albertel 8451: my $cachetime = 60*60;
1.171 www 8452: if ($liburi) {
8453: $liburi=&declutter($liburi);
8454: $filename=$liburi;
1.401 bowersj2 8455: } else {
1.599 albertel 8456: &devalidate_cache_new('meta',$uri);
8457: undef(%metaentry);
1.401 bowersj2 8458: }
1.140 www 8459: my %metathesekeys=();
1.73 www 8460: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8461: my $metastring;
1.924 albertel 8462: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8463: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8464: $metastring =
1.929 albertel 8465: &Apache::lonnet::ssi_body($which,
1.924 albertel 8466: ('grade_target' => 'meta'));
8467: $cachetime = 1; # only want this cached in the child not long term
8468: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8469: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8470: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8471: $metastring=&getfile($file);
1.489 albertel 8472: }
1.208 albertel 8473: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8474: my $token;
1.140 www 8475: undef %metathesekeys;
1.71 www 8476: while ($token=$parser->get_token) {
1.339 albertel 8477: if ($token->[0] eq 'S') {
8478: if (defined($token->[2]->{'package'})) {
1.172 www 8479: #
8480: # This is a package - get package info
8481: #
1.339 albertel 8482: my $package=$token->[2]->{'package'};
8483: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8484: if (defined($token->[2]->{'id'})) {
8485: $keyroot.='_'.$token->[2]->{'id'};
8486: }
1.599 albertel 8487: if ($metaentry{':packages'}) {
8488: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8489: } else {
1.599 albertel 8490: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8491: }
1.736 albertel 8492: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8493: my $part=$keyroot;
8494: $part=~s/^\_//;
1.736 albertel 8495: if ($pack_entry=~/^\Q$package\E\&/ ||
8496: $pack_entry=~/^\Q$package\E_0\&/) {
8497: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8498: # ignore package.tab specified default values
8499: # here &package_tab_default() will fetch those
8500: if ($subp eq 'default') { next; }
1.736 albertel 8501: my $value=$packagetab{$pack_entry};
1.432 albertel 8502: my $unikey;
8503: if ($pack =~ /_0$/) {
8504: $unikey='parameter_0_'.$name;
8505: $part=0;
8506: } else {
8507: $unikey='parameter'.$keyroot.'_'.$name;
8508: }
1.339 albertel 8509: if ($subp eq 'display') {
8510: $value.=' [Part: '.$part.']';
8511: }
1.599 albertel 8512: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8513: $metathesekeys{$unikey}=1;
1.599 albertel 8514: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8515: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8516: }
1.599 albertel 8517: if (defined($metaentry{':'.$unikey.'.default'})) {
8518: $metaentry{':'.$unikey}=
8519: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8520: }
1.339 albertel 8521: }
8522: }
8523: } else {
1.172 www 8524: #
8525: # This is not a package - some other kind of start tag
1.339 albertel 8526: #
8527: my $entry=$token->[1];
8528: my $unikey;
8529: if ($entry eq 'import') {
8530: $unikey='';
8531: } else {
8532: $unikey=$entry;
8533: }
8534: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8535:
8536: if (defined($token->[2]->{'id'})) {
8537: $unikey.='_'.$token->[2]->{'id'};
8538: }
1.175 www 8539:
1.339 albertel 8540: if ($entry eq 'import') {
1.175 www 8541: #
8542: # Importing a library here
1.339 albertel 8543: #
8544: if ($depthcount<20) {
8545: my $location=$parser->get_text('/import');
8546: my $dir=$filename;
8547: $dir=~s|[^/]*$||;
8548: $location=&filelocation($dir,$location);
1.736 albertel 8549: my $metadata =
8550: &metadata($uri,'keys', $location,$unikey,
8551: $depthcount+1);
8552: foreach my $meta (split(',',$metadata)) {
8553: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8554: $metathesekeys{$meta}=1;
1.339 albertel 8555: }
8556: }
8557: } else {
8558:
8559: if (defined($token->[2]->{'name'})) {
8560: $unikey.='_'.$token->[2]->{'name'};
8561: }
8562: $metathesekeys{$unikey}=1;
1.736 albertel 8563: foreach my $param (@{$token->[3]}) {
8564: $metaentry{':'.$unikey.'.'.$param} =
8565: $token->[2]->{$param};
1.339 albertel 8566: }
8567: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8568: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8569: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8570: # only ws inside the tag, and not in default, so use default
8571: # as value
1.599 albertel 8572: $metaentry{':'.$unikey}=$default;
1.908 albertel 8573: } elsif ( $internaltext =~ /\S/ ) {
8574: # something interesting inside the tag
8575: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8576: } else {
1.908 albertel 8577: # no interesting values, don't set a default
1.339 albertel 8578: }
1.172 www 8579: # end of not-a-package not-a-library import
1.339 albertel 8580: }
1.172 www 8581: # end of not-a-package start tag
1.339 albertel 8582: }
1.172 www 8583: # the next is the end of "start tag"
1.339 albertel 8584: }
8585: }
1.483 albertel 8586: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8587: $extension = lc($extension);
8588: if ($extension eq 'htm') { $extension='html'; }
8589:
1.737 albertel 8590: foreach my $key (keys(%packagetab)) {
1.483 albertel 8591: #no specific packages #how's our extension
8592: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8593: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8594: \%metathesekeys);
8595: }
1.883 albertel 8596:
8597: if (!exists($metaentry{':packages'})
8598: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8599: foreach my $key (keys(%packagetab)) {
1.483 albertel 8600: #no specific packages well let's get default then
8601: if ($key!~/^default&/) { next; }
1.488 albertel 8602: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8603: \%metathesekeys);
8604: }
8605: }
1.338 www 8606: # are there custom rights to evaluate
1.599 albertel 8607: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8608:
1.338 www 8609: #
8610: # Importing a rights file here
1.339 albertel 8611: #
8612: unless ($depthcount) {
1.599 albertel 8613: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8614: my $dir=$filename;
8615: $dir=~s|[^/]*$||;
8616: $location=&filelocation($dir,$location);
1.736 albertel 8617: my $rights_metadata =
8618: &metadata($uri,'keys',$location,'_rights',
8619: $depthcount+1);
8620: foreach my $rights (split(',',$rights_metadata)) {
8621: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8622: $metathesekeys{$rights}=1;
1.339 albertel 8623: }
8624: }
8625: }
1.737 albertel 8626: # uniqifiy package listing
8627: my %seen;
8628: my @uniq_packages =
8629: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8630: $metaentry{':packages'} = join(',',@uniq_packages);
8631:
8632: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8633: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8634: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8635: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8636: # this is the end of "was not already recently cached
1.71 www 8637: }
1.599 albertel 8638: return $metaentry{':'.$what};
1.261 albertel 8639: }
8640:
1.488 albertel 8641: sub metadata_create_package_def {
1.483 albertel 8642: my ($uri,$key,$package,$metathesekeys)=@_;
8643: my ($pack,$name,$subp)=split(/\&/,$key);
8644: if ($subp eq 'default') { next; }
8645:
1.599 albertel 8646: if (defined($metaentry{':packages'})) {
8647: $metaentry{':packages'}.=','.$package;
1.483 albertel 8648: } else {
1.599 albertel 8649: $metaentry{':packages'}=$package;
1.483 albertel 8650: }
8651: my $value=$packagetab{$key};
8652: my $unikey;
8653: $unikey='parameter_0_'.$name;
1.599 albertel 8654: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8655: $$metathesekeys{$unikey}=1;
1.599 albertel 8656: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8657: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8658: }
1.599 albertel 8659: if (defined($metaentry{':'.$unikey.'.default'})) {
8660: $metaentry{':'.$unikey}=
8661: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8662: }
8663: }
8664:
1.261 albertel 8665: sub metadata_generate_part0 {
8666: my ($metadata,$metacache,$uri) = @_;
8667: my %allnames;
1.737 albertel 8668: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8669: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8670: my $part=$$metacache{':'.$metakey.'.part'};
8671: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8672: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8673: $allnames{$name}=$part;
8674: }
8675: }
8676: }
8677: foreach my $name (keys(%allnames)) {
8678: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8679: my $key=":parameter_0_$name";
1.261 albertel 8680: $$metacache{"$key.part"}='0';
8681: $$metacache{"$key.name"}=$name;
1.428 albertel 8682: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8683: $allnames{$name}.'_'.$name.
8684: '.type'};
1.428 albertel 8685: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8686: '.display'};
1.644 www 8687: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8688: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8689: $$metacache{"$key.display"}=$olddis;
8690: }
1.71 www 8691: }
8692:
1.764 albertel 8693: # ------------------------------------------------------ Devalidate title cache
8694:
8695: sub devalidate_title_cache {
8696: my ($url)=@_;
8697: if (!$env{'request.course.id'}) { return; }
8698: my $symb=&symbread($url);
8699: if (!$symb) { return; }
8700: my $key=$env{'request.course.id'}."\0".$symb;
8701: &devalidate_cache_new('title',$key);
8702: }
8703:
1.1014 droeschl 8704: # ------------------------------------------------- Get the title of a course
8705:
8706: sub current_course_title {
8707: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8708: }
1.301 www 8709: # ------------------------------------------------- Get the title of a resource
8710:
8711: sub gettitle {
8712: my $urlsymb=shift;
8713: my $symb=&symbread($urlsymb);
1.534 albertel 8714: if ($symb) {
1.620 albertel 8715: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8716: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8717: if (defined($cached)) {
8718: return $result;
8719: }
1.534 albertel 8720: my ($map,$resid,$url)=&decode_symb($symb);
8721: my $title='';
1.907 albertel 8722: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8723: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8724: } else {
8725: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8726: &GDBM_READER(),0640)) {
8727: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8728: $title=$bighash{'title_'.$mapid.'.'.$resid};
8729: untie(%bighash);
8730: }
1.534 albertel 8731: }
8732: $title=~s/\&colon\;/\:/gs;
8733: if ($title) {
1.599 albertel 8734: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8735: }
8736: $urlsymb=$url;
8737: }
8738: my $title=&metadata($urlsymb,'title');
8739: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8740: return $title;
1.301 www 8741: }
1.613 albertel 8742:
1.614 albertel 8743: sub get_slot {
8744: my ($which,$cnum,$cdom)=@_;
8745: if (!$cnum || !$cdom) {
1.790 albertel 8746: (undef,my $courseid)=&whichuser();
1.620 albertel 8747: $cdom=$env{'course.'.$courseid.'.domain'};
8748: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8749: }
1.703 albertel 8750: my $key=join("\0",'slots',$cdom,$cnum,$which);
8751: my %slotinfo;
8752: if (exists($remembered{$key})) {
8753: $slotinfo{$which} = $remembered{$key};
8754: } else {
8755: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8756: &Apache::lonhomework::showhash(%slotinfo);
8757: my ($tmp)=keys(%slotinfo);
8758: if ($tmp=~/^error:/) { return (); }
8759: $remembered{$key} = $slotinfo{$which};
8760: }
1.616 albertel 8761: if (ref($slotinfo{$which}) eq 'HASH') {
8762: return %{$slotinfo{$which}};
8763: }
8764: return $slotinfo{$which};
1.614 albertel 8765: }
1.31 www 8766: # ------------------------------------------------- Update symbolic store links
8767:
8768: sub symblist {
8769: my ($mapname,%newhash)=@_;
1.438 www 8770: $mapname=&deversion(&declutter($mapname));
1.31 www 8771: my %hash;
1.620 albertel 8772: if (($env{'request.course.fn'}) && (%newhash)) {
8773: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8774: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8775: foreach my $url (keys(%newhash)) {
1.711 albertel 8776: next if ($url eq 'last_known'
8777: && $env{'form.no_update_last_known'});
8778: $hash{declutter($url)}=&encode_symb($mapname,
8779: $newhash{$url}->[1],
8780: $newhash{$url}->[0]);
1.191 harris41 8781: }
1.31 www 8782: if (untie(%hash)) {
8783: return 'ok';
8784: }
8785: }
8786: }
8787: return 'error';
1.212 www 8788: }
8789:
8790: # --------------------------------------------------------------- Verify a symb
8791:
8792: sub symbverify {
1.510 www 8793: my ($symb,$thisurl)=@_;
8794: my $thisfn=$thisurl;
1.439 www 8795: $thisfn=&declutter($thisfn);
1.215 www 8796: # direct jump to resource in page or to a sequence - will construct own symbs
8797: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8798: # check URL part
1.409 www 8799: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8800:
1.431 www 8801: unless ($url eq $thisfn) { return 0; }
1.213 www 8802:
1.216 www 8803: $symb=&symbclean($symb);
1.510 www 8804: $thisurl=&deversion($thisurl);
1.439 www 8805: $thisfn=&deversion($thisfn);
1.213 www 8806:
8807: my %bighash;
8808: my $okay=0;
1.431 www 8809:
1.620 albertel 8810: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8811: &GDBM_READER(),0640)) {
1.1032 raeburn 8812: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8813: $thisurl =~ s/\?.+$//;
8814: }
1.510 www 8815: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8816: unless ($ids) {
1.510 www 8817: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8818: }
8819: if ($ids) {
8820: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8821: foreach my $id (split(/\,/,$ids)) {
8822: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8823: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8824: $symb =~ s/\?.+$//;
8825: }
1.216 www 8826: if (
8827: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8828: eq $symb) {
1.620 albertel 8829: if (($env{'request.role.adv'}) ||
1.800 albertel 8830: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8831: $okay=1;
8832: }
8833: }
1.216 www 8834: }
8835: }
1.213 www 8836: untie(%bighash);
8837: }
8838: return $okay;
1.31 www 8839: }
8840:
1.210 www 8841: # --------------------------------------------------------------- Clean-up symb
8842:
8843: sub symbclean {
8844: my $symb=shift;
1.568 albertel 8845: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8846: # remove version from map
8847: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8848:
1.210 www 8849: # remove version from URL
8850: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8851:
1.507 www 8852: # remove wrapper
8853:
1.510 www 8854: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8855: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8856: return $symb;
1.409 www 8857: }
8858:
8859: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8860:
8861: sub encode_symb {
8862: my ($map,$resid,$url)=@_;
8863: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8864: }
1.409 www 8865:
8866: sub decode_symb {
1.568 albertel 8867: my $symb=shift;
8868: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8869: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8870: return (&fixversion($map),$resid,&fixversion($url));
8871: }
8872:
8873: sub fixversion {
8874: my $fn=shift;
1.609 banghart 8875: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8876: my %bighash;
8877: my $uri=&clutter($fn);
1.620 albertel 8878: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8879: # is this cached?
1.599 albertel 8880: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8881: if (defined($cached)) { return $result; }
8882: # unfortunately not cached, or expired
1.620 albertel 8883: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8884: &GDBM_READER(),0640)) {
8885: if ($bighash{'version_'.$uri}) {
8886: my $version=$bighash{'version_'.$uri};
1.444 www 8887: unless (($version eq 'mostrecent') ||
8888: ($version==&getversion($uri))) {
1.440 www 8889: $uri=~s/\.(\w+)$/\.$version\.$1/;
8890: }
8891: }
8892: untie %bighash;
1.413 www 8893: }
1.599 albertel 8894: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8895: }
8896:
8897: sub deversion {
8898: my $url=shift;
8899: $url=~s/\.\d+\.(\w+)$/\.$1/;
8900: return $url;
1.210 www 8901: }
8902:
1.31 www 8903: # ------------------------------------------------------ Return symb list entry
8904:
8905: sub symbread {
1.249 www 8906: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8907: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8908: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8909: # no filename provided? try from environment
1.44 www 8910: unless ($thisfn) {
1.620 albertel 8911: if ($env{'request.symb'}) {
8912: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8913: }
1.620 albertel 8914: $thisfn=$env{'request.filename'};
1.44 www 8915: }
1.569 albertel 8916: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8917: # is that filename actually a symb? Verify, clean, and return
8918: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8919: if (&symbverify($thisfn,$1)) {
1.620 albertel 8920: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8921: }
1.242 www 8922: }
1.44 www 8923: $thisfn=declutter($thisfn);
1.31 www 8924: my %hash;
1.37 www 8925: my %bighash;
8926: my $syval='';
1.620 albertel 8927: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8928: my $targetfn = $thisfn;
1.609 banghart 8929: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8930: $targetfn = 'adm/wrapper/'.$thisfn;
8931: }
1.687 albertel 8932: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8933: $targetfn=$1;
8934: }
1.620 albertel 8935: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8936: &GDBM_READER(),0640)) {
1.481 raeburn 8937: $syval=$hash{$targetfn};
1.37 www 8938: untie(%hash);
8939: }
8940: # ---------------------------------------------------------- There was an entry
8941: if ($syval) {
1.601 albertel 8942: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8943: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8944: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8945: #return $env{$cache_str}='';
1.601 albertel 8946: #}
8947: #$syval.=$1;
8948: #}
1.37 www 8949: } else {
8950: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8951: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8952: &GDBM_READER(),0640)) {
1.37 www 8953: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8954: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8955: unless ($ids) {
8956: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8957: }
8958: unless ($ids) {
8959: # alias?
8960: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8961: }
1.37 www 8962: if ($ids) {
8963: # ------------------------------------------------------------------- Has ID(s)
8964: my @possibilities=split(/\,/,$ids);
1.39 www 8965: if ($#possibilities==0) {
8966: # ----------------------------------------------- There is only one possibility
1.37 www 8967: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8968: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8969: $resid,$thisfn);
1.249 www 8970: } elsif (!$donotrecurse) {
1.39 www 8971: # ------------------------------------------ There is more than one possibility
8972: my $realpossible=0;
1.800 albertel 8973: foreach my $id (@possibilities) {
8974: my $file=$bighash{'src_'.$id};
1.39 www 8975: if (&allowed('bre',$file)) {
1.800 albertel 8976: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8977: if ($bighash{'map_type_'.$mapid} ne 'page') {
8978: $realpossible++;
1.626 albertel 8979: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8980: $resid,$thisfn);
1.39 www 8981: }
8982: }
1.191 harris41 8983: }
1.39 www 8984: if ($realpossible!=1) { $syval=''; }
1.249 www 8985: } else {
8986: $syval='';
1.37 www 8987: }
8988: }
8989: untie(%bighash)
1.481 raeburn 8990: }
1.31 www 8991: }
1.62 www 8992: if ($syval) {
1.620 albertel 8993: return $env{$cache_str}=$syval;
1.62 www 8994: }
1.31 www 8995: }
1.949 raeburn 8996: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8997: return $env{$cache_str}='';
1.31 www 8998: }
8999:
9000: # ---------------------------------------------------------- Return random seed
9001:
1.32 www 9002: sub numval {
9003: my $txt=shift;
9004: $txt=~tr/A-J/0-9/;
9005: $txt=~tr/a-j/0-9/;
9006: $txt=~tr/K-T/0-9/;
9007: $txt=~tr/k-t/0-9/;
9008: $txt=~tr/U-Z/0-5/;
9009: $txt=~tr/u-z/0-5/;
9010: $txt=~s/\D//g;
1.564 albertel 9011: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9012: return int($txt);
1.368 albertel 9013: }
9014:
1.484 albertel 9015: sub numval2 {
9016: my $txt=shift;
9017: $txt=~tr/A-J/0-9/;
9018: $txt=~tr/a-j/0-9/;
9019: $txt=~tr/K-T/0-9/;
9020: $txt=~tr/k-t/0-9/;
9021: $txt=~tr/U-Z/0-5/;
9022: $txt=~tr/u-z/0-5/;
9023: $txt=~s/\D//g;
9024: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9025: my $total;
9026: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9027: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9028: return int($total);
9029: }
9030:
1.575 albertel 9031: sub numval3 {
9032: use integer;
9033: my $txt=shift;
9034: $txt=~tr/A-J/0-9/;
9035: $txt=~tr/a-j/0-9/;
9036: $txt=~tr/K-T/0-9/;
9037: $txt=~tr/k-t/0-9/;
9038: $txt=~tr/U-Z/0-5/;
9039: $txt=~tr/u-z/0-5/;
9040: $txt=~s/\D//g;
9041: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9042: my $total;
9043: foreach my $val (@txts) { $total+=$val; }
9044: if ($_64bit) { $total=(($total<<32)>>32); }
9045: return $total;
9046: }
9047:
1.675 albertel 9048: sub digest {
9049: my ($data)=@_;
9050: my $digest=&Digest::MD5::md5($data);
9051: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9052: my ($e,$f);
9053: {
9054: use integer;
9055: $e=($a+$b);
9056: $f=($c+$d);
9057: if ($_64bit) {
9058: $e=(($e<<32)>>32);
9059: $f=(($f<<32)>>32);
9060: }
9061: }
9062: if (wantarray) {
9063: return ($e,$f);
9064: } else {
9065: my $g;
9066: {
9067: use integer;
9068: $g=($e+$f);
9069: if ($_64bit) {
9070: $g=(($g<<32)>>32);
9071: }
9072: }
9073: return $g;
9074: }
9075: }
9076:
1.368 albertel 9077: sub latest_rnd_algorithm_id {
1.675 albertel 9078: return '64bit5';
1.366 albertel 9079: }
1.32 www 9080:
1.503 albertel 9081: sub get_rand_alg {
9082: my ($courseid)=@_;
1.790 albertel 9083: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9084: if ($courseid) {
1.620 albertel 9085: return $env{"course.$courseid.rndseed"};
1.503 albertel 9086: }
9087: return &latest_rnd_algorithm_id();
9088: }
9089:
1.562 albertel 9090: sub validCODE {
9091: my ($CODE)=@_;
9092: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9093: return 0;
9094: }
9095:
1.491 albertel 9096: sub getCODE {
1.620 albertel 9097: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9098: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9099: defined($Apache::lonhomework::parsing_a_task) ) &&
9100: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9101: return $Apache::lonhomework::history{'resource.CODE'};
9102: }
9103: return undef;
9104: }
9105:
1.31 www 9106: sub rndseed {
1.155 albertel 9107: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9108: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9109: if (!defined($symb)) {
1.366 albertel 9110: unless ($symb=$wsymb) { return time; }
9111: }
9112: if (!$courseid) { $courseid=$wcourseid; }
9113: if (!$domain) { $domain=$wdomain; }
9114: if (!$username) { $username=$wusername }
1.503 albertel 9115: my $which=&get_rand_alg();
1.803 albertel 9116:
1.491 albertel 9117: if (defined(&getCODE())) {
1.675 albertel 9118: if ($which eq '64bit5') {
9119: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9120: } elsif ($which eq '64bit4') {
1.575 albertel 9121: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9122: } else {
9123: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9124: }
1.675 albertel 9125: } elsif ($which eq '64bit5') {
9126: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9127: } elsif ($which eq '64bit4') {
9128: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9129: } elsif ($which eq '64bit3') {
9130: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9131: } elsif ($which eq '64bit2') {
9132: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9133: } elsif ($which eq '64bit') {
9134: return &rndseed_64bit($symb,$courseid,$domain,$username);
9135: }
9136: return &rndseed_32bit($symb,$courseid,$domain,$username);
9137: }
9138:
9139: sub rndseed_32bit {
9140: my ($symb,$courseid,$domain,$username)=@_;
9141: {
9142: use integer;
9143: my $symbchck=unpack("%32C*",$symb) << 27;
9144: my $symbseed=numval($symb) << 22;
9145: my $namechck=unpack("%32C*",$username) << 17;
9146: my $nameseed=numval($username) << 12;
9147: my $domainseed=unpack("%32C*",$domain) << 7;
9148: my $courseseed=unpack("%32C*",$courseid);
9149: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9150: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9151: #&logthis("rndseed :$num:$symb");
1.564 albertel 9152: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9153: return $num;
9154: }
9155: }
9156:
9157: sub rndseed_64bit {
9158: my ($symb,$courseid,$domain,$username)=@_;
9159: {
9160: use integer;
9161: my $symbchck=unpack("%32S*",$symb) << 21;
9162: my $symbseed=numval($symb) << 10;
9163: my $namechck=unpack("%32S*",$username);
9164:
9165: my $nameseed=numval($username) << 21;
9166: my $domainseed=unpack("%32S*",$domain) << 10;
9167: my $courseseed=unpack("%32S*",$courseid);
9168:
9169: my $num1=$symbchck+$symbseed+$namechck;
9170: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9171: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9172: #&logthis("rndseed :$num:$symb");
1.564 albertel 9173: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9174: return "$num1,$num2";
1.155 albertel 9175: }
1.366 albertel 9176: }
9177:
1.443 albertel 9178: sub rndseed_64bit2 {
9179: my ($symb,$courseid,$domain,$username)=@_;
9180: {
9181: use integer;
9182: # strings need to be an even # of cahracters long, it it is odd the
9183: # last characters gets thrown away
9184: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9185: my $symbseed=numval($symb) << 10;
9186: my $namechck=unpack("%32S*",$username.' ');
9187:
9188: my $nameseed=numval($username) << 21;
1.501 albertel 9189: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9190: my $courseseed=unpack("%32S*",$courseid.' ');
9191:
9192: my $num1=$symbchck+$symbseed+$namechck;
9193: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9194: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9195: #&logthis("rndseed :$num:$symb");
1.803 albertel 9196: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9197: return "$num1,$num2";
9198: }
9199: }
9200:
9201: sub rndseed_64bit3 {
9202: my ($symb,$courseid,$domain,$username)=@_;
9203: {
9204: use integer;
9205: # strings need to be an even # of cahracters long, it it is odd the
9206: # last characters gets thrown away
9207: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9208: my $symbseed=numval2($symb) << 10;
9209: my $namechck=unpack("%32S*",$username.' ');
9210:
9211: my $nameseed=numval2($username) << 21;
1.443 albertel 9212: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9213: my $courseseed=unpack("%32S*",$courseid.' ');
9214:
9215: my $num1=$symbchck+$symbseed+$namechck;
9216: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9217: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9218: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9219: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9220:
1.503 albertel 9221: return "$num1:$num2";
1.443 albertel 9222: }
9223: }
9224:
1.575 albertel 9225: sub rndseed_64bit4 {
9226: my ($symb,$courseid,$domain,$username)=@_;
9227: {
9228: use integer;
9229: # strings need to be an even # of cahracters long, it it is odd the
9230: # last characters gets thrown away
9231: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9232: my $symbseed=numval3($symb) << 10;
9233: my $namechck=unpack("%32S*",$username.' ');
9234:
9235: my $nameseed=numval3($username) << 21;
9236: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9237: my $courseseed=unpack("%32S*",$courseid.' ');
9238:
9239: my $num1=$symbchck+$symbseed+$namechck;
9240: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9241: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9242: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9243: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9244:
9245: return "$num1:$num2";
9246: }
9247: }
9248:
1.675 albertel 9249: sub rndseed_64bit5 {
9250: my ($symb,$courseid,$domain,$username)=@_;
9251: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9252: return "$num1:$num2";
9253: }
9254:
1.366 albertel 9255: sub rndseed_CODE_64bit {
9256: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9257: {
1.366 albertel 9258: use integer;
1.443 albertel 9259: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9260: my $symbseed=numval2($symb);
1.491 albertel 9261: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9262: my $CODEseed=numval(&getCODE());
1.443 albertel 9263: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9264: my $num1=$symbseed+$CODEchck;
9265: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9266: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9267: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9268: if ($_64bit) { $num1=(($num1<<32)>>32); }
9269: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9270: return "$num1:$num2";
1.366 albertel 9271: }
9272: }
9273:
1.575 albertel 9274: sub rndseed_CODE_64bit4 {
9275: my ($symb,$courseid,$domain,$username)=@_;
9276: {
9277: use integer;
9278: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9279: my $symbseed=numval3($symb);
9280: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9281: my $CODEseed=numval3(&getCODE());
9282: my $courseseed=unpack("%32S*",$courseid.' ');
9283: my $num1=$symbseed+$CODEchck;
9284: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9285: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9286: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9287: if ($_64bit) { $num1=(($num1<<32)>>32); }
9288: if ($_64bit) { $num2=(($num2<<32)>>32); }
9289: return "$num1:$num2";
9290: }
9291: }
9292:
1.675 albertel 9293: sub rndseed_CODE_64bit5 {
9294: my ($symb,$courseid,$domain,$username)=@_;
9295: my $code = &getCODE();
9296: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9297: return "$num1:$num2";
9298: }
9299:
1.366 albertel 9300: sub setup_random_from_rndseed {
9301: my ($rndseed)=@_;
1.503 albertel 9302: if ($rndseed =~/([,:])/) {
9303: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9304: &Math::Random::random_set_seed(abs($num1),abs($num2));
9305: } else {
9306: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9307: }
1.36 albertel 9308: }
9309:
1.474 albertel 9310: sub latest_receipt_algorithm_id {
1.835 albertel 9311: return 'receipt3';
1.474 albertel 9312: }
9313:
1.480 www 9314: sub recunique {
9315: my $fucourseid=shift;
9316: my $unique;
1.835 albertel 9317: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9318: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9319: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9320: } else {
9321: $unique=$perlvar{'lonReceipt'};
9322: }
9323: return unpack("%32C*",$unique);
9324: }
9325:
9326: sub recprefix {
9327: my $fucourseid=shift;
9328: my $prefix;
1.835 albertel 9329: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9330: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9331: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9332: } else {
9333: $prefix=$perlvar{'lonHostID'};
9334: }
9335: return unpack("%32C*",$prefix);
9336: }
9337:
1.76 www 9338: sub ireceipt {
1.474 albertel 9339: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9340:
9341: my $return =&recprefix($fucourseid).'-';
9342:
9343: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9344: $env{'request.state'} eq 'construct') {
9345: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9346: return $return;
9347: }
9348:
1.76 www 9349: my $cuname=unpack("%32C*",$funame);
9350: my $cudom=unpack("%32C*",$fudom);
9351: my $cucourseid=unpack("%32C*",$fucourseid);
9352: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9353: my $cunique=&recunique($fucourseid);
1.474 albertel 9354: my $cpart=unpack("%32S*",$part);
1.835 albertel 9355: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9356:
1.790 albertel 9357: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9358:
9359: $return.= ($cunique%$cuname+
9360: $cunique%$cudom+
9361: $cusymb%$cuname+
9362: $cusymb%$cudom+
9363: $cucourseid%$cuname+
9364: $cucourseid%$cudom+
9365: $cpart%$cuname+
9366: $cpart%$cudom);
9367: } else {
9368: $return.= ($cunique%$cuname+
9369: $cunique%$cudom+
9370: $cusymb%$cuname+
9371: $cusymb%$cudom+
9372: $cucourseid%$cuname+
9373: $cucourseid%$cudom);
9374: }
9375: return $return;
1.76 www 9376: }
9377:
9378: sub receipt {
1.474 albertel 9379: my ($part)=@_;
1.790 albertel 9380: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9381: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9382: }
1.260 ng 9383:
1.790 albertel 9384: sub whichuser {
9385: my ($passedsymb)=@_;
9386: my ($symb,$courseid,$domain,$name,$publicuser);
9387: if (defined($env{'form.grade_symb'})) {
9388: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9389: my $allowed=&allowed('vgr',$tmp_courseid);
9390: if (!$allowed &&
9391: exists($env{'request.course.sec'}) &&
9392: $env{'request.course.sec'} !~ /^\s*$/) {
9393: $allowed=&allowed('vgr',$tmp_courseid.
9394: '/'.$env{'request.course.sec'});
9395: }
9396: if ($allowed) {
9397: ($symb)=&get_env_multiple('form.grade_symb');
9398: $courseid=$tmp_courseid;
9399: ($domain)=&get_env_multiple('form.grade_domain');
9400: ($name)=&get_env_multiple('form.grade_username');
9401: return ($symb,$courseid,$domain,$name,$publicuser);
9402: }
9403: }
9404: if (!$passedsymb) {
9405: $symb=&symbread();
9406: } else {
9407: $symb=$passedsymb;
9408: }
9409: $courseid=$env{'request.course.id'};
9410: $domain=$env{'user.domain'};
9411: $name=$env{'user.name'};
9412: if ($name eq 'public' && $domain eq 'public') {
9413: if (!defined($env{'form.username'})) {
9414: $env{'form.username'}.=time.rand(10000000);
9415: }
9416: $name.=$env{'form.username'};
9417: }
9418: return ($symb,$courseid,$domain,$name,$publicuser);
9419:
9420: }
9421:
1.36 albertel 9422: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9423: # returns either the contents of the file or
9424: # -1 if the file doesn't exist
1.481 raeburn 9425: #
9426: # if the target is a file that was uploaded via DOCS,
9427: # a check will be made to see if a current copy exists on the local server,
9428: # if it does this will be served, otherwise a copy will be retrieved from
9429: # the home server for the course and stored in /home/httpd/html/userfiles on
9430: # the local server.
1.472 albertel 9431:
1.36 albertel 9432: sub getfile {
1.538 albertel 9433: my ($file) = @_;
1.609 banghart 9434: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9435: &repcopy($file);
9436: return &readfile($file);
9437: }
9438:
9439: sub repcopy_userfile {
9440: my ($file)=@_;
1.609 banghart 9441: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9442: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9443: my ($cdom,$cnum,$filename) =
1.811 albertel 9444: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9445: my $uri="/uploaded/$cdom/$cnum/$filename";
9446: if (-e "$file") {
1.828 www 9447: # we already have a local copy, check it out
1.538 albertel 9448: my @fileinfo = stat($file);
1.828 www 9449: my $rtncode;
9450: my $info;
1.538 albertel 9451: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9452: if ($lwpresp ne 'ok') {
1.828 www 9453: # there is no such file anymore, even though we had a local copy
1.482 albertel 9454: if ($rtncode eq '404') {
1.538 albertel 9455: unlink($file);
1.482 albertel 9456: }
9457: return -1;
9458: }
9459: if ($info < $fileinfo[9]) {
1.828 www 9460: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9461: return 'ok';
1.828 www 9462: } else {
9463: # the file is outdated, get rid of it
9464: unlink($file);
1.482 albertel 9465: }
1.828 www 9466: }
9467: # one way or the other, at this point, we don't have the file
9468: # construct the correct path for the file
9469: my @parts = ($cdom,$cnum);
9470: if ($filename =~ m|^(.+)/[^/]+$|) {
9471: push @parts, split(/\//,$1);
9472: }
9473: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9474: foreach my $part (@parts) {
9475: $path .= '/'.$part;
9476: if (!-e $path) {
9477: mkdir($path,0770);
1.482 albertel 9478: }
9479: }
1.828 www 9480: # now the path exists for sure
9481: # get a user agent
9482: my $ua=new LWP::UserAgent;
9483: my $transferfile=$file.'.in.transfer';
9484: # FIXME: this should flock
9485: if (-e $transferfile) { return 'ok'; }
9486: my $request;
9487: $uri=~s/^\///;
1.980 raeburn 9488: my $homeserver = &homeserver($cnum,$cdom);
9489: my $protocol = $protocol{$homeserver};
9490: $protocol = 'http' if ($protocol ne 'https');
9491: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9492: my $response=$ua->request($request,$transferfile);
9493: # did it work?
9494: if ($response->is_error()) {
9495: unlink($transferfile);
9496: &logthis("Userfile repcopy failed for $uri");
9497: return -1;
9498: }
9499: # worked, rename the transfer file
9500: rename($transferfile,$file);
1.607 raeburn 9501: return 'ok';
1.481 raeburn 9502: }
9503:
1.517 albertel 9504: sub tokenwrapper {
9505: my $uri=shift;
1.980 raeburn 9506: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9507: $uri=~s|^/||;
1.620 albertel 9508: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9509: my $token=$1;
1.552 albertel 9510: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9511: if ($udom && $uname && $file) {
9512: $file=~s|(\?\.*)*$||;
1.949 raeburn 9513: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9514: my $homeserver = &homeserver($uname,$udom);
9515: my $protocol = $protocol{$homeserver};
9516: $protocol = 'http' if ($protocol ne 'https');
9517: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9518: (($uri=~/\?/)?'&':'?').'token='.$token.
9519: '&tokenissued='.$perlvar{'lonHostID'};
9520: } else {
9521: return '/adm/notfound.html';
9522: }
9523: }
9524:
1.828 www 9525: # call with reqtype HEAD: get last modification time
9526: # call with reqtype GET: get the file contents
9527: # Do not call this with reqtype GET for large files! It loads everything into memory
9528: #
1.481 raeburn 9529: sub getuploaded {
9530: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9531: $uri=~s/^\///;
1.980 raeburn 9532: my $homeserver = &homeserver($cnum,$cdom);
9533: my $protocol = $protocol{$homeserver};
9534: $protocol = 'http' if ($protocol ne 'https');
9535: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9536: my $ua=new LWP::UserAgent;
9537: my $request=new HTTP::Request($reqtype,$uri);
9538: my $response=$ua->request($request);
9539: $$rtncode = $response->code;
1.482 albertel 9540: if (! $response->is_success()) {
9541: return 'failed';
9542: }
9543: if ($reqtype eq 'HEAD') {
1.486 www 9544: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9545: } elsif ($reqtype eq 'GET') {
9546: $$info = $response->content;
1.472 albertel 9547: }
1.482 albertel 9548: return 'ok';
1.36 albertel 9549: }
9550:
1.481 raeburn 9551: sub readfile {
9552: my $file = shift;
9553: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9554: my $fh;
9555: open($fh,"<$file");
9556: my $a='';
1.800 albertel 9557: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9558: return $a;
9559: }
9560:
1.36 albertel 9561: sub filelocation {
1.590 banghart 9562: my ($dir,$file) = @_;
9563: my $location;
9564: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9565:
9566: if ($file =~ m-^/adm/-) {
9567: $file=~s-^/adm/wrapper/-/-;
9568: $file=~s-^/adm/coursedocs/showdoc/-/-;
9569: }
1.882 albertel 9570:
1.590 banghart 9571: if ($file=~m:^/~:) { # is a contruction space reference
9572: $location = $file;
9573: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9574: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9575: # is a correct contruction space reference
9576: $location = $file;
1.956 raeburn 9577: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9578: $location = $file;
1.609 banghart 9579: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9580: my ($udom,$uname,$filename)=
1.811 albertel 9581: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9582: my $home=&homeserver($uname,$udom);
9583: my $is_me=0;
9584: my @ids=¤t_machine_ids();
9585: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9586: if ($is_me) {
1.955 raeburn 9587: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9588: } else {
9589: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9590: $udom.'/'.$uname.'/'.$filename;
9591: }
1.882 albertel 9592: } elsif ($file =~ m-^/adm/-) {
9593: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9594: } else {
9595: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9596: $file=~s:^/res/:/:;
9597: if ( !( $file =~ m:^/:) ) {
9598: $location = $dir. '/'.$file;
9599: } else {
9600: $location = '/home/httpd/html/res'.$file;
9601: }
1.59 albertel 9602: }
1.590 banghart 9603: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9604: while ($location=~m{/\.\./}) {
9605: if ($location =~ m{/[^/]+/\.\./}) {
9606: $location=~ s{/[^/]+/\.\./}{/}g;
9607: } else {
9608: $location=~ s{/\.\./}{/}g;
9609: }
9610: } #remove dir/..
1.590 banghart 9611: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9612: return $location;
1.46 www 9613: }
1.36 albertel 9614:
1.46 www 9615: sub hreflocation {
9616: my ($dir,$file)=@_;
1.980 raeburn 9617: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9618: $file=filelocation($dir,$file);
1.700 albertel 9619: } elsif ($file=~m-^/adm/-) {
9620: $file=~s-^/adm/wrapper/-/-;
9621: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9622: }
9623: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9624: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9625: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9626: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9627: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9628: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9629: -/uploaded/$1/$2/-x;
1.46 www 9630: }
1.913 albertel 9631: if ($file=~ m{^/userfiles/}) {
9632: $file =~ s{^/userfiles/}{/uploaded/};
9633: }
1.462 albertel 9634: return $file;
1.465 albertel 9635: }
9636:
9637: sub current_machine_domains {
1.853 albertel 9638: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9639: }
9640:
9641: sub machine_domains {
9642: my ($hostname) = @_;
1.465 albertel 9643: my @domains;
1.838 albertel 9644: my %hostname = &all_hostnames();
1.465 albertel 9645: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9646: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9647: if ($hostname eq $name) {
1.844 albertel 9648: push(@domains,&host_domain($id));
1.465 albertel 9649: }
9650: }
9651: return @domains;
9652: }
9653:
9654: sub current_machine_ids {
1.853 albertel 9655: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9656: }
9657:
9658: sub machine_ids {
9659: my ($hostname) = @_;
9660: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9661: my @ids;
1.888 albertel 9662: my %name_to_host = &all_names();
1.889 albertel 9663: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9664: return @{ $name_to_host{$hostname} };
9665: }
9666: return;
1.31 www 9667: }
9668:
1.824 raeburn 9669: sub additional_machine_domains {
9670: my @domains;
9671: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9672: while( my $line = <$fh>) {
9673: $line =~ s/\s//g;
9674: push(@domains,$line);
9675: }
9676: return @domains;
9677: }
9678:
9679: sub default_login_domain {
9680: my $domain = $perlvar{'lonDefDomain'};
9681: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9682: foreach my $posdom (¤t_machine_domains(),
9683: &additional_machine_domains()) {
9684: if (lc($posdom) eq lc($testdomain)) {
9685: $domain=$posdom;
9686: last;
9687: }
9688: }
9689: return $domain;
9690: }
9691:
1.31 www 9692: # ------------------------------------------------------------- Declutters URLs
9693:
9694: sub declutter {
9695: my $thisfn=shift;
1.569 albertel 9696: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9697: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9698: $thisfn=~s/^\///;
1.697 albertel 9699: $thisfn=~s|^adm/wrapper/||;
9700: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9701: $thisfn=~s/^res\///;
1.1032 raeburn 9702: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9703: $thisfn=~s/\?.+$//;
9704: }
1.268 www 9705: return $thisfn;
9706: }
9707:
9708: # ------------------------------------------------------------- Clutter up URLs
9709:
9710: sub clutter {
9711: my $thisfn='/'.&declutter(shift);
1.887 albertel 9712: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9713: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9714: $thisfn='/res'.$thisfn;
9715: }
1.1031 raeburn 9716: if ($thisfn !~m|^/adm|) {
9717: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9718: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9719: } else {
9720: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9721: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9722: if ($embstyle eq 'ssi'
9723: || ($embstyle eq 'hdn')
9724: || ($embstyle eq 'rat')
9725: || ($embstyle eq 'prv')
9726: || ($embstyle eq 'ign')) {
9727: #do nothing with these
9728: } elsif (($embstyle eq 'img')
1.695 albertel 9729: || ($embstyle eq 'emb')
9730: || ($embstyle eq 'wrp')) {
9731: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9732: } elsif ($embstyle eq 'unk'
9733: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9734: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9735: } else {
1.718 www 9736: # &logthis("Got a blank emb style");
1.695 albertel 9737: }
1.694 albertel 9738: }
9739: }
1.31 www 9740: return $thisfn;
1.12 www 9741: }
9742:
1.787 albertel 9743: sub clutter_with_no_wrapper {
9744: my $uri = &clutter(shift);
9745: if ($uri =~ m-^/adm/-) {
9746: $uri =~ s-^/adm/wrapper/-/-;
9747: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9748: }
9749: return $uri;
9750: }
9751:
1.557 albertel 9752: sub freeze_escape {
9753: my ($value)=@_;
9754: if (ref($value)) {
9755: $value=&nfreeze($value);
9756: return '__FROZEN__'.&escape($value);
9757: }
9758: return &escape($value);
9759: }
9760:
1.11 www 9761:
1.557 albertel 9762: sub thaw_unescape {
9763: my ($value)=@_;
9764: if ($value =~ /^__FROZEN__/) {
9765: substr($value,0,10,undef);
9766: $value=&unescape($value);
9767: return &thaw($value);
9768: }
9769: return &unescape($value);
9770: }
9771:
1.436 albertel 9772: sub correct_line_ends {
9773: my ($result)=@_;
9774: $$result =~s/\r\n/\n/mg;
9775: $$result =~s/\r/\n/mg;
1.415 albertel 9776: }
1.1 albertel 9777: # ================================================================ Main Program
9778:
1.184 www 9779: sub goodbye {
1.204 albertel 9780: &logthis("Starting Shut down");
1.443 albertel 9781: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9782: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9783: #converted
1.599 albertel 9784: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9785: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9786: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9787: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9788: #1.1 only
1.870 albertel 9789: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9790: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9791: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9792: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9793: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9794: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9795: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9796: &flushcourselogs();
9797: &logthis("Shutting down");
9798: }
9799:
1.852 albertel 9800: sub get_dns {
1.869 albertel 9801: my ($url,$func,$ignore_cache) = @_;
9802: if (!$ignore_cache) {
9803: my ($content,$cached)=
9804: &Apache::lonnet::is_cached_new('dns',$url);
9805: if ($cached) {
9806: &$func($content);
9807: return;
9808: }
9809: }
9810:
9811: my %alldns;
1.852 albertel 9812: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9813: foreach my $dns (<$config>) {
9814: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9815: my $line = $1;
9816: my ($host,$protocol) = split(/:/,$line);
9817: if ($protocol ne 'https') {
9818: $protocol = 'http';
9819: }
9820: $alldns{$host} = $protocol;
1.869 albertel 9821: }
9822: while (%alldns) {
9823: my ($dns) = keys(%alldns);
1.852 albertel 9824: my $ua=new LWP::UserAgent;
1.979 raeburn 9825: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9826: my $response=$ua->request($request);
1.979 raeburn 9827: delete($alldns{$dns});
1.852 albertel 9828: next if ($response->is_error());
9829: my @content = split("\n",$response->content);
1.869 albertel 9830: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9831: &$func(\@content);
1.869 albertel 9832: return;
1.852 albertel 9833: }
9834: close($config);
1.871 albertel 9835: my $which = (split('/',$url))[3];
9836: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9837: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9838: my @content = <$config>;
9839: &$func(\@content);
9840: return;
1.852 albertel 9841: }
1.327 albertel 9842: # ------------------------------------------------------------ Read domain file
9843: {
1.852 albertel 9844: my $loaded;
1.846 albertel 9845: my %domain;
9846:
1.852 albertel 9847: sub parse_domain_tab {
9848: my ($lines) = @_;
9849: foreach my $line (@$lines) {
9850: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9851:
1.846 albertel 9852: chomp($line);
1.852 albertel 9853: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9854: my %this_domain;
9855: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9856: 'lang_def', 'city', 'longi', 'lati',
9857: 'primary') {
9858: $this_domain{$field} = shift(@elements);
9859: }
9860: $domain{$name} = \%this_domain;
1.852 albertel 9861: }
9862: }
1.864 albertel 9863:
9864: sub reset_domain_info {
9865: undef($loaded);
9866: undef(%domain);
9867: }
9868:
1.852 albertel 9869: sub load_domain_tab {
1.869 albertel 9870: my ($ignore_cache) = @_;
9871: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9872: my $fh;
9873: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9874: my @lines = <$fh>;
9875: &parse_domain_tab(\@lines);
1.448 albertel 9876: }
1.852 albertel 9877: close($fh);
9878: $loaded = 1;
1.327 albertel 9879: }
1.846 albertel 9880:
9881: sub domain {
1.852 albertel 9882: &load_domain_tab() if (!$loaded);
9883:
1.846 albertel 9884: my ($name,$what) = @_;
9885: return if ( !exists($domain{$name}) );
9886:
9887: if (!$what) {
9888: return $domain{$name}{'description'};
9889: }
9890: return $domain{$name}{$what};
9891: }
1.974 raeburn 9892:
9893: sub domain_info {
9894: &load_domain_tab() if (!$loaded);
9895: return %domain;
9896: }
9897:
1.327 albertel 9898: }
9899:
9900:
1.1 albertel 9901: # ------------------------------------------------------------- Read hosts file
9902: {
1.838 albertel 9903: my %hostname;
1.844 albertel 9904: my %hostdom;
1.845 albertel 9905: my %libserv;
1.852 albertel 9906: my $loaded;
1.888 albertel 9907: my %name_to_host;
1.852 albertel 9908:
9909: sub parse_hosts_tab {
9910: my ($file) = @_;
9911: foreach my $configline (@$file) {
9912: next if ($configline =~ /^(\#|\s*$ )/x);
9913: next if ($configline =~ /^\^/);
9914: chomp($configline);
1.968 raeburn 9915: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9916: $name=~s/\s//g;
9917: if ($id && $domain && $role && $name) {
9918: $hostname{$id}=$name;
1.888 albertel 9919: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9920: $hostdom{$id}=$domain;
9921: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9922: if (defined($protocol)) {
9923: if ($protocol eq 'https') {
9924: $protocol{$id} = $protocol;
9925: } else {
9926: $protocol{$id} = 'http';
9927: }
1.968 raeburn 9928: } else {
1.969 raeburn 9929: $protocol{$id} = 'http';
1.968 raeburn 9930: }
1.852 albertel 9931: }
9932: }
9933: }
1.864 albertel 9934:
9935: sub reset_hosts_info {
1.897 albertel 9936: &purge_remembered();
1.864 albertel 9937: &reset_domain_info();
9938: &reset_hosts_ip_info();
1.892 albertel 9939: undef(%name_to_host);
1.864 albertel 9940: undef(%hostname);
9941: undef(%hostdom);
9942: undef(%libserv);
9943: undef($loaded);
9944: }
1.1 albertel 9945:
1.852 albertel 9946: sub load_hosts_tab {
1.869 albertel 9947: my ($ignore_cache) = @_;
9948: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9949: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9950: my @config = <$config>;
9951: &parse_hosts_tab(\@config);
9952: close($config);
9953: $loaded=1;
1.1 albertel 9954: }
1.852 albertel 9955:
1.838 albertel 9956: sub hostname {
1.852 albertel 9957: &load_hosts_tab() if (!$loaded);
9958:
1.838 albertel 9959: my ($lonid) = @_;
9960: return $hostname{$lonid};
9961: }
1.845 albertel 9962:
1.838 albertel 9963: sub all_hostnames {
1.852 albertel 9964: &load_hosts_tab() if (!$loaded);
9965:
1.838 albertel 9966: return %hostname;
9967: }
1.845 albertel 9968:
1.888 albertel 9969: sub all_names {
9970: &load_hosts_tab() if (!$loaded);
9971:
9972: return %name_to_host;
9973: }
9974:
1.974 raeburn 9975: sub all_host_domain {
9976: &load_hosts_tab() if (!$loaded);
9977: return %hostdom;
9978: }
9979:
1.845 albertel 9980: sub is_library {
1.852 albertel 9981: &load_hosts_tab() if (!$loaded);
9982:
1.845 albertel 9983: return exists($libserv{$_[0]});
9984: }
9985:
9986: sub all_library {
1.852 albertel 9987: &load_hosts_tab() if (!$loaded);
9988:
1.845 albertel 9989: return %libserv;
9990: }
9991:
1.1056.4.2 raeburn 9992: sub unique_library {
9993: #2x reverse removes all hostnames that appear more than once
9994: my %unique = reverse &all_library();
9995: return reverse %unique;
9996: }
9997:
1.841 albertel 9998: sub get_servers {
1.852 albertel 9999: &load_hosts_tab() if (!$loaded);
10000:
1.841 albertel 10001: my ($domain,$type) = @_;
10002: my %possible_hosts = ($type eq 'library') ? %libserv
10003: : %hostname;
10004: my %result;
1.842 albertel 10005: if (ref($domain) eq 'ARRAY') {
10006: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10007: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10008: $result{$host} = $hostname;
10009: }
10010: }
10011: } else {
10012: while ( my ($host,$hostname) = each(%possible_hosts)) {
10013: if ($hostdom{$host} eq $domain) {
10014: $result{$host} = $hostname;
10015: }
1.841 albertel 10016: }
10017: }
10018: return %result;
10019: }
1.845 albertel 10020:
1.1056.4.2 raeburn 10021: sub get_unique_servers {
10022: my %unique = reverse &get_servers(@_);
10023: return reverse %unique;
10024: }
10025:
1.844 albertel 10026: sub host_domain {
1.852 albertel 10027: &load_hosts_tab() if (!$loaded);
10028:
1.844 albertel 10029: my ($lonid) = @_;
10030: return $hostdom{$lonid};
10031: }
10032:
1.841 albertel 10033: sub all_domains {
1.852 albertel 10034: &load_hosts_tab() if (!$loaded);
10035:
1.841 albertel 10036: my %seen;
10037: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10038: return @uniq;
10039: }
1.1056.4.3 raeburn 10040:
10041: sub internet_dom {
10042: &load_hosts_tab() if (!$loaded);
10043:
10044: my ($lonid) = @_;
10045: return $internetdom{$lonid};
10046: }
10047:
1.1 albertel 10048: }
10049:
1.847 albertel 10050: {
10051: my %iphost;
1.856 albertel 10052: my %name_to_ip;
10053: my %lonid_to_ip;
1.869 albertel 10054:
1.847 albertel 10055: sub get_hosts_from_ip {
10056: my ($ip) = @_;
10057: my %iphosts = &get_iphost();
10058: if (ref($iphosts{$ip})) {
10059: return @{$iphosts{$ip}};
10060: }
10061: return;
1.839 albertel 10062: }
1.864 albertel 10063:
10064: sub reset_hosts_ip_info {
10065: undef(%iphost);
10066: undef(%name_to_ip);
10067: undef(%lonid_to_ip);
10068: }
1.856 albertel 10069:
10070: sub get_host_ip {
10071: my ($lonid) = @_;
10072: if (exists($lonid_to_ip{$lonid})) {
10073: return $lonid_to_ip{$lonid};
10074: }
10075: my $name=&hostname($lonid);
10076: my $ip = gethostbyname($name);
10077: return if (!$ip || length($ip) ne 4);
10078: $ip=inet_ntoa($ip);
10079: $name_to_ip{$name} = $ip;
10080: $lonid_to_ip{$lonid} = $ip;
10081: return $ip;
10082: }
1.847 albertel 10083:
10084: sub get_iphost {
1.869 albertel 10085: my ($ignore_cache) = @_;
1.894 albertel 10086:
1.869 albertel 10087: if (!$ignore_cache) {
10088: if (%iphost) {
10089: return %iphost;
10090: }
10091: my ($ip_info,$cached)=
10092: &Apache::lonnet::is_cached_new('iphost','iphost');
10093: if ($cached) {
10094: %iphost = %{$ip_info->[0]};
10095: %name_to_ip = %{$ip_info->[1]};
10096: %lonid_to_ip = %{$ip_info->[2]};
10097: return %iphost;
10098: }
10099: }
1.894 albertel 10100:
10101: # get yesterday's info for fallback
10102: my %old_name_to_ip;
10103: my ($ip_info,$cached)=
10104: &Apache::lonnet::is_cached_new('iphost','iphost');
10105: if ($cached) {
10106: %old_name_to_ip = %{$ip_info->[1]};
10107: }
10108:
1.888 albertel 10109: my %name_to_host = &all_names();
10110: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10111: my $ip;
10112: if (!exists($name_to_ip{$name})) {
10113: $ip = gethostbyname($name);
10114: if (!$ip || length($ip) ne 4) {
1.894 albertel 10115: if (defined($old_name_to_ip{$name})) {
10116: $ip = $old_name_to_ip{$name};
10117: &logthis("Can't find $name defaulting to old $ip");
10118: } else {
10119: &logthis("Name $name no IP found");
10120: next;
10121: }
10122: } else {
10123: $ip=inet_ntoa($ip);
1.847 albertel 10124: }
10125: $name_to_ip{$name} = $ip;
10126: } else {
10127: $ip = $name_to_ip{$name};
1.653 albertel 10128: }
1.888 albertel 10129: foreach my $id (@{ $name_to_host{$name} }) {
10130: $lonid_to_ip{$id} = $ip;
10131: }
10132: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10133: }
1.869 albertel 10134: &Apache::lonnet::do_cache_new('iphost','iphost',
10135: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10136: 48*60*60);
1.869 albertel 10137:
1.847 albertel 10138: return %iphost;
1.598 albertel 10139: }
10140:
1.992 raeburn 10141: #
10142: # Given a DNS returns the loncapa host name for that DNS
10143: #
10144: sub host_from_dns {
10145: my ($dns) = @_;
10146: my @hosts;
10147: my $ip;
10148:
1.993 raeburn 10149: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10150: $ip = $name_to_ip{$dns};
10151: }
10152: if (!$ip) {
10153: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10154: if (length($ip) == 4) {
10155: $ip = &IO::Socket::inet_ntoa($ip);
10156: }
10157: }
10158: if ($ip) {
10159: @hosts = get_hosts_from_ip($ip);
10160: return $hosts[0];
10161: }
10162: return undef;
1.986 foxr 10163: }
1.992 raeburn 10164:
1.1056.4.3 raeburn 10165: sub get_internet_names {
10166: my ($lonid) = @_;
10167: return if ($lonid eq '');
10168: my ($idnref,$cached)=
10169: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10170: if ($cached) {
10171: return $idnref;
10172: }
10173: my $ip = &get_host_ip($lonid);
10174: my @hosts = &get_hosts_from_ip($ip);
10175: my %iphost = &get_iphost();
10176: my (@idns,%seen);
10177: foreach my $id (@hosts) {
10178: my $dom = &host_domain($id);
10179: my $prim_id = &domain($dom,'primary');
10180: my $prim_ip = &get_host_ip($prim_id);
10181: next if ($seen{$prim_ip});
10182: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10183: foreach my $id (@{$iphost{$prim_ip}}) {
10184: my $intdom = &internet_dom($id);
10185: unless (grep(/^\Q$intdom\E$/,@idns)) {
10186: push(@idns,$intdom);
10187: }
10188: }
10189: }
10190: $seen{$prim_ip} = 1;
10191: }
10192: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10193: }
10194:
10195: }
10196:
10197: sub all_loncaparevs {
10198: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986 foxr 10199: }
10200:
1.862 albertel 10201: BEGIN {
10202:
10203: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10204: unless ($readit) {
10205: {
10206: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10207: %perlvar = (%perlvar,%{$configvars});
10208: }
10209:
10210:
1.1 albertel 10211: # ------------------------------------------------------ Read spare server file
10212: {
1.448 albertel 10213: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10214:
10215: while (my $configline=<$config>) {
10216: chomp($configline);
1.284 matthew 10217: if ($configline) {
1.784 albertel 10218: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10219: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10220: push(@{ $spareid{$type} }, $host);
1.1 albertel 10221: }
10222: }
1.448 albertel 10223: close($config);
1.1 albertel 10224: }
1.11 www 10225: # ------------------------------------------------------------ Read permissions
10226: {
1.448 albertel 10227: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10228:
10229: while (my $configline=<$config>) {
1.448 albertel 10230: chomp($configline);
10231: if ($configline) {
10232: my ($role,$perm)=split(/ /,$configline);
10233: if ($perm ne '') { $pr{$role}=$perm; }
10234: }
1.11 www 10235: }
1.448 albertel 10236: close($config);
1.11 www 10237: }
10238:
10239: # -------------------------------------------- Read plain texts for permissions
10240: {
1.448 albertel 10241: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10242:
10243: while (my $configline=<$config>) {
1.448 albertel 10244: chomp($configline);
10245: if ($configline) {
1.742 raeburn 10246: my ($short,@plain)=split(/:/,$configline);
10247: %{$prp{$short}} = ();
10248: if (@plain > 0) {
10249: $prp{$short}{'std'} = $plain[0];
10250: for (my $i=1; $i<@plain; $i++) {
10251: $prp{$short}{'alt'.$i} = $plain[$i];
10252: }
10253: }
1.448 albertel 10254: }
1.135 www 10255: }
1.448 albertel 10256: close($config);
1.135 www 10257: }
10258:
10259: # ---------------------------------------------------------- Read package table
10260: {
1.448 albertel 10261: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10262:
10263: while (my $configline=<$config>) {
1.483 albertel 10264: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10265: chomp($configline);
10266: my ($short,$plain)=split(/:/,$configline);
10267: my ($pack,$name)=split(/\&/,$short);
10268: if ($plain ne '') {
10269: $packagetab{$pack.'&'.$name.'&name'}=$name;
10270: $packagetab{$short}=$plain;
10271: }
1.11 www 10272: }
1.448 albertel 10273: close($config);
1.329 matthew 10274: }
10275:
1.1056.4.3 raeburn 10276: # ---------------------------------------------------------- Read loncaparev table
10277: {
10278: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10279: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10280: while (my $configline=<$config>) {
10281: chomp($configline);
10282: my ($hostid,$loncaparev)=split(/:/,$configline);
10283: $loncaparevs{$hostid}=$loncaparev;
10284: }
10285: close($config);
10286: }
10287: }
10288: }
10289:
10290: # ---------------------------------------------------------- Read serverhostID table
10291: {
10292: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10293: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10294: while (my $configline=<$config>) {
10295: chomp($configline);
10296: my ($name,$id)=split(/:/,$configline);
10297: $serverhomeIDs{$name}=$id;
10298: }
10299: close($config);
10300: }
10301: }
10302: }
10303:
1.329 matthew 10304: # ------------- set up temporary directory
10305: {
10306: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10307:
1.11 www 10308: }
10309:
1.794 albertel 10310: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10311: 'compress_threshold'=> 20_000,
10312: });
1.185 www 10313:
1.281 www 10314: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10315: $dumpcount=0;
1.958 www 10316: $locknum=0;
1.22 www 10317:
1.163 harris41 10318: &logtouch();
1.672 albertel 10319: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10320: $readit=1;
1.564 albertel 10321: {
10322: use integer;
10323: my $test=(2**32)+1;
1.568 albertel 10324: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10325: &logthis(" Detected 64bit platform ($_64bit)");
10326: }
1.195 www 10327: }
1.1 albertel 10328: }
1.179 www 10329:
1.1 albertel 10330: 1;
1.191 harris41 10331: __END__
10332:
1.243 albertel 10333: =pod
10334:
1.191 harris41 10335: =head1 NAME
10336:
1.243 albertel 10337: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10338:
10339: =head1 SYNOPSIS
10340:
1.243 albertel 10341: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10342:
10343: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10344:
1.243 albertel 10345: Common parameters:
10346:
10347: =over 4
10348:
10349: =item *
10350:
10351: $uname : an internal username (if $cname expecting a course Id specifically)
10352:
10353: =item *
10354:
10355: $udom : a domain (if $cdom expecting a course's domain specifically)
10356:
10357: =item *
10358:
10359: $symb : a resource instance identifier
10360:
10361: =item *
10362:
10363: $namespace : the name of a .db file that contains the data needed or
10364: being set.
10365:
10366: =back
10367:
1.394 bowersj2 10368: =head1 OVERVIEW
1.191 harris41 10369:
1.394 bowersj2 10370: lonnet provides subroutines which interact with the
10371: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10372: about classes, users, and resources.
1.243 albertel 10373:
10374: For many of these objects you can also use this to store data about
10375: them or modify them in various ways.
1.191 harris41 10376:
1.394 bowersj2 10377: =head2 Symbs
1.191 harris41 10378:
1.394 bowersj2 10379: To identify a specific instance of a resource, LON-CAPA uses symbols
10380: or "symbs"X<symb>. These identifiers are built from the URL of the
10381: map, the resource number of the resource in the map, and the URL of
10382: the resource itself. The latter is somewhat redundant, but might help
10383: if maps change.
10384:
10385: An example is
10386:
10387: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10388:
10389: The respective map entry is
10390:
10391: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10392: title="Problem 2">
10393: </resource>
10394:
10395: Symbs are used by the random number generator, as well as to store and
10396: restore data specific to a certain instance of for example a problem.
10397:
10398: =head2 Storing And Retrieving Data
10399:
10400: X<store()>X<cstore()>X<restore()>Three of the most important functions
10401: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10402: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10403: is is the non-critical message twin of cstore. These functions are for
10404: handlers to store a perl hash to a user's permanent data space in an
10405: easy manner, and to retrieve it again on another call. It is expected
10406: that a handler would use this once at the beginning to retrieve data,
10407: and then again once at the end to send only the new data back.
10408:
10409: The data is stored in the user's data directory on the user's
10410: homeserver under the ID of the course.
10411:
10412: The hash that is returned by restore will have all of the previous
10413: value for all of the elements of the hash.
10414:
10415: Example:
10416:
10417: #creating a hash
10418: my %hash;
10419: $hash{'foo'}='bar';
10420:
10421: #storing it
10422: &Apache::lonnet::cstore(\%hash);
10423:
10424: #changing a value
10425: $hash{'foo'}='notbar';
10426:
10427: #adding a new value
10428: $hash{'bar'}='foo';
10429: &Apache::lonnet::cstore(\%hash);
10430:
10431: #retrieving the hash
10432: my %history=&Apache::lonnet::restore();
10433:
10434: #print the hash
10435: foreach my $key (sort(keys(%history))) {
10436: print("\%history{$key} = $history{$key}");
10437: }
10438:
10439: Will print out:
1.191 harris41 10440:
1.394 bowersj2 10441: %history{1:foo} = bar
10442: %history{1:keys} = foo:timestamp
10443: %history{1:timestamp} = 990455579
10444: %history{2:bar} = foo
10445: %history{2:foo} = notbar
10446: %history{2:keys} = foo:bar:timestamp
10447: %history{2:timestamp} = 990455580
10448: %history{bar} = foo
10449: %history{foo} = notbar
10450: %history{timestamp} = 990455580
10451: %history{version} = 2
10452:
10453: Note that the special hash entries C<keys>, C<version> and
10454: C<timestamp> were added to the hash. C<version> will be equal to the
10455: total number of versions of the data that have been stored. The
10456: C<timestamp> attribute will be the UNIX time the hash was
10457: stored. C<keys> is available in every historical section to list which
10458: keys were added or changed at a specific historical revision of a
10459: hash.
10460:
10461: B<Warning>: do not store the hash that restore returns directly. This
10462: will cause a mess since it will restore the historical keys as if the
10463: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10464:
1.394 bowersj2 10465: Calling convention:
1.191 harris41 10466:
1.394 bowersj2 10467: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10468: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10469:
1.394 bowersj2 10470: For more detailed information, see lonnet specific documentation.
1.191 harris41 10471:
1.394 bowersj2 10472: =head1 RETURN MESSAGES
1.191 harris41 10473:
1.394 bowersj2 10474: =over 4
1.191 harris41 10475:
1.394 bowersj2 10476: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10477:
1.394 bowersj2 10478: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10479: when the connection is brought back up
1.191 harris41 10480:
1.394 bowersj2 10481: =item * B<con_failed>: unable to contact remote host and unable to save message
10482: for later delivery
1.191 harris41 10483:
1.967 bisitz 10484: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10485:
1.394 bowersj2 10486: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10487: that was requested
1.191 harris41 10488:
1.243 albertel 10489: =back
1.191 harris41 10490:
1.243 albertel 10491: =head1 PUBLIC SUBROUTINES
1.191 harris41 10492:
1.243 albertel 10493: =head2 Session Environment Functions
1.191 harris41 10494:
1.243 albertel 10495: =over 4
1.191 harris41 10496:
1.394 bowersj2 10497: =item *
10498: X<appenv()>
1.949 raeburn 10499: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10500: the user envirnoment file, and will be restored for each access this
1.620 albertel 10501: user makes during this session, also modifies the %env for the current
1.949 raeburn 10502: process. Optional rolesarrayref - if defined contains a reference to an array
10503: of roles which are exempt from the restriction on modifying user.role entries
10504: in the user's environment.db and in %env.
1.191 harris41 10505:
10506: =item *
1.394 bowersj2 10507: X<delenv()>
1.987 raeburn 10508: B<delenv($delthis,$regexp)>: removes all items from the session
10509: environment file that begin with $delthis. If the
10510: optional second arg - $regexp - is true, $delthis is treated as a
10511: regular expression, otherwise \Q$delthis\E is used.
10512: The values are also deleted from the current processes %env.
1.191 harris41 10513:
1.795 albertel 10514: =item * get_env_multiple($name)
10515:
10516: gets $name from the %env hash, it seemlessly handles the cases where multiple
10517: values may be defined and end up as an array ref.
10518:
10519: returns an array of values
10520:
1.243 albertel 10521: =back
10522:
10523: =head2 User Information
1.191 harris41 10524:
1.243 albertel 10525: =over 4
1.191 harris41 10526:
10527: =item *
1.394 bowersj2 10528: X<queryauthenticate()>
10529: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10530: authentication scheme
10531:
10532: =item *
1.394 bowersj2 10533: X<authenticate()>
1.1056.4.3 raeburn 10534: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10535: authenticate user from domain's lib servers (first use the current
10536: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10537: $checkdefauth is optional (value is 1 if a check should be made to
10538: authenticate user using default authentication method, and allow
10539: account creation if username does not have account in the domain).
10540: $clientcancheckhost is optional (value is 1 if checking whether the
10541: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10542:
10543: =item *
1.394 bowersj2 10544: X<homeserver()>
10545: B<homeserver($uname,$udom)>: find the server which has
10546: the user's directory and files (there must be only one), this caches
10547: the answer, and also caches if there is a borken connection.
1.191 harris41 10548:
10549: =item *
1.394 bowersj2 10550: X<idget()>
10551: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10552: (IDs are a unique resource in a domain, there must be only 1 ID per
10553: username, and only 1 username per ID in a specific domain) (returns
10554: hash: id=>name,id=>name)
1.191 harris41 10555:
10556: =item *
1.394 bowersj2 10557: X<idrget()>
10558: B<idrget($udom,@unames)>: find the IDs behind a list of
10559: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10560:
10561: =item *
1.394 bowersj2 10562: X<idput()>
10563: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10564:
10565: =item *
1.394 bowersj2 10566: X<rolesinit()>
10567: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10568:
10569: =item *
1.551 albertel 10570: X<getsection()>
10571: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10572: course $cname, return section name/number or '' for "not in course"
10573: and '-1' for "no section"
10574:
10575: =item *
1.394 bowersj2 10576: X<userenvironment()>
10577: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10578: passed in @what from the requested user's environment, returns a hash
10579:
1.858 raeburn 10580: =item *
10581: X<userlog_query()>
1.859 albertel 10582: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10583: activity.log file. %filters defines filters applied when parsing the
10584: log file. These can be start or end timestamps, or the type of action
10585: - log to look for Login or Logout events, check for Checkin or
10586: Checkout, role for role selection. The response is in the form
10587: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10588: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10589:
1.243 albertel 10590: =back
10591:
10592: =head2 User Roles
10593:
10594: =over 4
10595:
10596: =item *
10597:
1.810 raeburn 10598: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10599: F: full access
10600: U,I,K: authentication modes (cxx only)
10601: '': forbidden
10602: 1: user needs to choose course
10603: 2: browse allowed
1.766 albertel 10604: A: passphrase authentication needed
1.243 albertel 10605:
10606: =item *
10607:
10608: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10609: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10610: and course level
10611:
10612: =item *
10613:
1.988 raeburn 10614: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10615: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10616: $type is Course (default) or Community.
1.988 raeburn 10617: If $forcedefault evaluates to true, text returned will be default
10618: text for $type. Otherwise, if this is a course, the text returned
10619: will be a custom name for the role (if defined in the course's
10620: environment). If no custom name is defined the default is returned.
10621:
1.832 raeburn 10622: =item *
10623:
1.935 raeburn 10624: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10625: All arguments are optional. Returns a hash of a roles, either for
10626: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10627: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10628: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10629: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10630: For each key, value is set to colon-separated start and end times for
10631: the role. If no username and domain are specified, will default to
1.934 raeburn 10632: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10633: of role statuses (active, future or previous), roles
10634: (e.g., cc,in, st etc.) and domains of the roles which can be used
10635: to restrict the list of roles reported. If no array ref is
10636: provided for types, will default to return only active roles.
1.834 albertel 10637:
1.243 albertel 10638: =back
10639:
10640: =head2 User Modification
10641:
10642: =over 4
10643:
10644: =item *
10645:
1.957 raeburn 10646: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10647: user for the level given by URL. Optional start and end dates (leave empty
10648: string or zero for "no date")
1.191 harris41 10649:
10650: =item *
10651:
1.243 albertel 10652: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10653: change a users, password, possible return values are: ok,
10654: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10655: refused
1.191 harris41 10656:
10657: =item *
10658:
1.243 albertel 10659: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10660:
10661: =item *
10662:
1.1056.4.1 raeburn 10663: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10664: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10665:
10666: will update user information (firstname,middlename,lastname,generation,
10667: permanentemail), and if forceid is true, student/employee ID also.
10668: A user's institutional affiliation(s) can also be updated.
10669: User information fields will not be overwritten with empty entries
10670: unless the field is included in the $candelete array reference.
10671: This array is included when a single user is modified via "Manage Users",
10672: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10673:
10674: =item *
10675:
1.286 matthew 10676: modifystudent
10677:
1.957 raeburn 10678: modify a student's enrollment and identification information.
1.286 matthew 10679: The course id is resolved based on the current users environment.
10680: This means the envoking user must be a course coordinator or otherwise
10681: associated with a course.
10682:
1.297 matthew 10683: This call is essentially a wrapper for lonnet::modifyuser and
10684: lonnet::modify_student_enrollment
1.286 matthew 10685:
10686: Inputs:
10687:
10688: =over 4
10689:
1.957 raeburn 10690: =item B<$udom> Student's loncapa domain
1.286 matthew 10691:
1.957 raeburn 10692: =item B<$uname> Student's loncapa login name
1.286 matthew 10693:
1.964 bisitz 10694: =item B<$uid> Student/Employee ID
1.286 matthew 10695:
1.957 raeburn 10696: =item B<$umode> Student's authentication mode
1.286 matthew 10697:
1.957 raeburn 10698: =item B<$upass> Student's password
1.286 matthew 10699:
1.957 raeburn 10700: =item B<$first> Student's first name
1.286 matthew 10701:
1.957 raeburn 10702: =item B<$middle> Student's middle name
1.286 matthew 10703:
1.957 raeburn 10704: =item B<$last> Student's last name
1.286 matthew 10705:
1.957 raeburn 10706: =item B<$gene> Student's generation
1.286 matthew 10707:
1.957 raeburn 10708: =item B<$usec> Student's section in course
1.286 matthew 10709:
10710: =item B<$end> Unix time of the roles expiration
10711:
10712: =item B<$start> Unix time of the roles start date
10713:
10714: =item B<$forceid> If defined, allow $uid to be changed
10715:
10716: =item B<$desiredhome> server to use as home server for student
10717:
1.957 raeburn 10718: =item B<$email> Student's permanent e-mail address
10719:
10720: =item B<$type> Type of enrollment (auto or manual)
10721:
1.963 raeburn 10722: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10723:
10724: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10725:
1.963 raeburn 10726: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10727:
1.963 raeburn 10728: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10729:
1.963 raeburn 10730: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10731:
1.286 matthew 10732: =back
1.297 matthew 10733:
10734: =item *
10735:
10736: modify_student_enrollment
10737:
10738: Change a students enrollment status in a class. The environment variable
10739: 'role.request.course' must be defined for this function to proceed.
10740:
10741: Inputs:
10742:
10743: =over 4
10744:
10745: =item $udom, students domain
10746:
10747: =item $uname, students name
10748:
10749: =item $uid, students user id
10750:
10751: =item $first, students first name
10752:
10753: =item $middle
10754:
10755: =item $last
10756:
10757: =item $gene
10758:
10759: =item $usec
10760:
10761: =item $end
10762:
10763: =item $start
10764:
1.957 raeburn 10765: =item $type
10766:
10767: =item $locktype
10768:
10769: =item $cid
10770:
10771: =item $selfenroll
10772:
10773: =item $context
10774:
1.297 matthew 10775: =back
10776:
1.191 harris41 10777:
10778: =item *
10779:
1.243 albertel 10780: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10781: custom role; give a custom role to a user for the level given by URL. Specify
10782: name and domain of role author, and role name
1.191 harris41 10783:
10784: =item *
10785:
1.243 albertel 10786: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10787:
10788: =item *
10789:
1.243 albertel 10790: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10791:
10792: =back
10793:
10794: =head2 Course Infomation
10795:
10796: =over 4
1.191 harris41 10797:
10798: =item *
10799:
1.631 albertel 10800: coursedescription($courseid) : returns a hash of information about the
10801: specified course id, including all environment settings for the
10802: course, the description of the course will be in the hash under the
10803: key 'description'
1.191 harris41 10804:
10805: =item *
10806:
1.624 albertel 10807: resdata($name,$domain,$type,@which) : request for current parameter
10808: setting for a specific $type, where $type is either 'course' or 'user',
10809: @what should be a list of parameters to ask about. This routine caches
10810: answers for 5 minutes.
1.243 albertel 10811:
1.877 foxr 10812: =item *
10813:
10814: get_courseresdata($courseid, $domain) : dump the entire course resource
10815: data base, returning a hash that is keyed by the resource name and has
10816: values that are the resource value. I believe that the timestamps and
10817: versions are also returned.
10818:
10819:
1.243 albertel 10820: =back
10821:
10822: =head2 Course Modification
10823:
10824: =over 4
1.191 harris41 10825:
10826: =item *
10827:
1.243 albertel 10828: writecoursepref($courseid,%prefs) : write preferences (environment
10829: database) for a course
1.191 harris41 10830:
10831: =item *
10832:
1.1011 raeburn 10833: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10834:
10835: =item *
10836:
1.1038 raeburn 10837: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10838:
10839: =back
10840:
10841: =head2 Resource Subroutines
10842:
10843: =over 4
1.191 harris41 10844:
10845: =item *
10846:
1.243 albertel 10847: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10848:
10849: =item *
10850:
1.243 albertel 10851: repcopy($filename) : subscribes to the requested file, and attempts to
10852: replicate from the owning library server, Might return
1.607 raeburn 10853: 'unavailable', 'not_found', 'forbidden', 'ok', or
10854: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10855: resource. Expects the local filesystem pathname
10856: (/home/httpd/html/res/....)
10857:
10858: =back
10859:
10860: =head2 Resource Information
10861:
10862: =over 4
1.191 harris41 10863:
10864: =item *
10865:
1.243 albertel 10866: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10867: a vairety of different possible values, $varname should be a request
10868: string, and the other parameters can be used to specify who and what
10869: one is asking about.
10870:
10871: Possible values for $varname are environment.lastname (or other item
10872: from the envirnment hash), user.name (or someother aspect about the
10873: user), resource.0.maxtries (or some other part and parameter of a
10874: resource)
1.204 albertel 10875:
10876: =item *
10877:
1.243 albertel 10878: directcondval($number) : get current value of a condition; reads from a state
10879: string
1.204 albertel 10880:
10881: =item *
10882:
1.243 albertel 10883: condval($condidx) : value of condition index based on state
1.204 albertel 10884:
10885: =item *
10886:
1.243 albertel 10887: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10888: resource's metadata, $what should be either a specific key, or either
10889: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10890: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10891:
10892: this function automatically caches all requests
1.191 harris41 10893:
10894: =item *
10895:
1.243 albertel 10896: metadata_query($query,$custom,$customshow) : make a metadata query against the
10897: network of library servers; returns file handle of where SQL and regex results
10898: will be stored for query
1.191 harris41 10899:
10900: =item *
10901:
1.243 albertel 10902: symbread($filename) : return symbolic list entry (filename argument optional);
10903: returns the data handle
1.191 harris41 10904:
10905: =item *
10906:
1.243 albertel 10907: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10908: a possible symb for the URL in $thisfn, and if is an encryypted
10909: resource that the user accessed using /enc/ returns a 1 on success, 0
10910: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10911: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10912:
1.191 harris41 10913:
10914: =item *
10915:
1.243 albertel 10916: symbclean($symb) : removes versions numbers from a symb, returns the
10917: cleaned symb
1.191 harris41 10918:
10919: =item *
10920:
1.243 albertel 10921: is_on_map($uri) : checks if the $uri is somewhere on the current
10922: course map, user must be in a course for it to work.
1.191 harris41 10923:
10924: =item *
10925:
1.243 albertel 10926: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10927:
10928: =item *
10929:
1.243 albertel 10930: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10931: a random seed, all arguments are optional, if they aren't sent it uses the
10932: environment to derive them. Note: if symb isn't sent and it can't get one
10933: from &symbread it will use the current time as its return value
1.191 harris41 10934:
10935: =item *
10936:
1.243 albertel 10937: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10938: unfakeable, receipt
1.191 harris41 10939:
10940: =item *
10941:
1.620 albertel 10942: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10943:
10944: =item *
10945:
1.243 albertel 10946: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10947:
10948: =item *
10949:
1.243 albertel 10950: 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 10951:
10952: =item *
10953:
1.243 albertel 10954: 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 10955:
10956: =item *
10957:
1.243 albertel 10958: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10959:
10960: =item *
10961:
1.243 albertel 10962: devalidate($symb) : devalidate temporary spreadsheet calculations,
10963: forcing spreadsheet to reevaluate the resource scores next time.
10964:
10965: =back
10966:
10967: =head2 Storing/Retreiving Data
10968:
10969: =over 4
1.191 harris41 10970:
10971: =item *
10972:
1.243 albertel 10973: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10974: for this url; hashref needs to be given and should be a \%hashname; the
10975: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10976: be derived from the env
1.191 harris41 10977:
10978: =item *
10979:
1.243 albertel 10980: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10981: uses critical subroutine
1.191 harris41 10982:
10983: =item *
10984:
1.243 albertel 10985: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10986: all args are optional
1.191 harris41 10987:
10988: =item *
10989:
1.717 albertel 10990: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10991: dumps the complete (or key matching regexp) namespace into a hash
10992: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10993: normally &store()ed into
10994:
10995: $range should be either an integer '100' (give me the first 100
10996: matching records)
10997: or be two integers sperated by a - with no spaces
10998: '30-50' (give me the 30th through the 50th matching
10999: records)
11000:
11001:
11002: =item *
11003:
11004: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11005: replaces a &store() version of data with a replacement set of data
11006: for a particular resource in a namespace passed in the $storehash hash
11007: reference
11008:
11009: =item *
11010:
1.243 albertel 11011: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11012: works very similar to store/cstore, but all data is stored in a
11013: temporary location and can be reset using tmpreset, $storehash should
11014: be a hash reference, returns nothing on success
1.191 harris41 11015:
11016: =item *
11017:
1.243 albertel 11018: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11019: similar to restore, but all data is stored in a temporary location and
11020: can be reset using tmpreset. Returns a hash of values on success,
11021: error string otherwise.
1.191 harris41 11022:
11023: =item *
11024:
1.243 albertel 11025: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11026: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11027:
11028: =item *
11029:
1.243 albertel 11030: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11031: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11032:
11033: =item *
11034:
1.243 albertel 11035: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11036: namesp ($udom and $uname are optional)
1.191 harris41 11037:
11038: =item *
11039:
1.702 albertel 11040: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11041: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11042: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11043:
1.702 albertel 11044: $range should be either an integer '100' (give me the first 100
11045: matching records)
11046: or be two integers sperated by a - with no spaces
11047: '30-50' (give me the 30th through the 50th matching
11048: records)
1.449 matthew 11049: =item *
11050:
11051: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11052: $store can be a scalar, an array reference, or if the amount to be
11053: incremented is > 1, a hash reference.
11054:
11055: ($udom and $uname are optional)
1.191 harris41 11056:
11057: =item *
11058:
1.243 albertel 11059: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11060: ($udom and $uname are optional)
1.191 harris41 11061:
11062: =item *
11063:
1.243 albertel 11064: cput($namespace,$storehash,$udom,$uname) : critical put
11065: ($udom and $uname are optional)
1.191 harris41 11066:
11067: =item *
11068:
1.748 albertel 11069: newput($namespace,$storehash,$udom,$uname) :
11070:
11071: Attempts to store the items in the $storehash, but only if they don't
11072: currently exist, if this succeeds you can be certain that you have
11073: successfully created a new key value pair in the $namespace db.
11074:
11075:
11076: Args:
11077: $namespace: name of database to store values to
11078: $storehash: hashref to store to the db
11079: $udom: (optional) domain of user containing the db
11080: $uname: (optional) name of user caontaining the db
11081:
11082: Returns:
11083: 'ok' -> succeeded in storing all keys of $storehash
11084: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11085: least <key> already existed in the db (other
11086: requested keys may also already exist)
1.967 bisitz 11087: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11088: 'con_lost' -> unable to contact request server
11089: 'refused' -> action was not allowed by remote machine
11090:
11091:
11092: =item *
11093:
1.243 albertel 11094: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11095: reference filled in from namesp (encrypts the return communication)
11096: ($udom and $uname are optional)
1.191 harris41 11097:
11098: =item *
11099:
1.243 albertel 11100: log($udom,$name,$home,$message) : write to permanent log for user; use
11101: critical subroutine
11102:
1.806 raeburn 11103: =item *
11104:
1.860 raeburn 11105: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11106: array reference filled in from namespace found in domain level on either
11107: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11108:
11109: =item *
11110:
1.860 raeburn 11111: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11112: domain level either on specified domain server ($uhome) or primary domain
11113: server ($udom and $uhome are optional)
1.806 raeburn 11114:
1.943 raeburn 11115: =item *
11116:
11117: get_domain_defaults($target_domain) : returns hash with defaults for
11118: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11119: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11120: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11121: Values are retrieved from cache (if current), or from domain's configuration.db
11122: (if available), or lastly from values in lonTabs/dns_domain,tab,
11123: or lonTabs/domain.tab.
11124:
11125: %domdefaults = &get_auth_defaults($target_domain);
11126:
1.243 albertel 11127: =back
11128:
11129: =head2 Network Status Functions
11130:
11131: =over 4
1.191 harris41 11132:
11133: =item *
11134:
11135: dirlist($uri) : return directory list based on URI
11136:
11137: =item *
11138:
1.243 albertel 11139: spareserver() : find server with least workload from spare.tab
11140:
1.986 foxr 11141:
11142: =item *
11143:
11144: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11145: if there is no corresponding loncapa host.
11146:
1.243 albertel 11147: =back
11148:
1.986 foxr 11149:
1.243 albertel 11150: =head2 Apache Request
11151:
11152: =over 4
1.191 harris41 11153:
11154: =item *
11155:
1.243 albertel 11156: ssi($url,%hash) : server side include, does a complete request cycle on url to
11157: localhost, posts hash
11158:
11159: =back
11160:
11161: =head2 Data to String to Data
11162:
11163: =over 4
1.191 harris41 11164:
11165: =item *
11166:
1.243 albertel 11167: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11168: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11169:
11170: =item *
11171:
1.243 albertel 11172: hashref2str($hashref) : convert a hashref into a string complete with
11173: escaping and '=' and '&' separators, supports elements that are
11174: arrayrefs and hashrefs
1.191 harris41 11175:
11176: =item *
11177:
1.243 albertel 11178: arrayref2str($arrayref) : convert an arrayref into a string complete
11179: with escaping and '&' separators, supports elements that are arrayrefs
11180: and hashrefs
1.191 harris41 11181:
11182: =item *
11183:
1.243 albertel 11184: str2hash($string) : convert string to hash using unescaping and
11185: splitting on '=' and '&', supports elements that are arrayrefs and
11186: hashrefs
1.191 harris41 11187:
11188: =item *
11189:
1.243 albertel 11190: str2array($string) : convert string to hash using unescaping and
11191: splitting on '&', supports elements that are arrayrefs and hashrefs
11192:
11193: =back
11194:
11195: =head2 Logging Routines
11196:
11197: =over 4
11198:
11199: These routines allow one to make log messages in the lonnet.log and
11200: lonnet.perm logfiles.
1.191 harris41 11201:
11202: =item *
11203:
1.243 albertel 11204: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11205:
11206: =item *
11207:
1.243 albertel 11208: logthis() : append message to the normal lonnet.log file, it gets
11209: preiodically rolled over and deleted.
1.191 harris41 11210:
11211: =item *
11212:
1.243 albertel 11213: logperm() : append a permanent message to lonnet.perm.log, this log
11214: file never gets deleted by any automated portion of the system, only
11215: messages of critical importance should go in here.
11216:
11217: =back
11218:
11219: =head2 General File Helper Routines
11220:
11221: =over 4
1.191 harris41 11222:
11223: =item *
11224:
1.481 raeburn 11225: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11226: (a) files in /uploaded
11227: (i) If a local copy of the file exists -
11228: compares modification date of local copy with last-modified date for
11229: definitive version stored on home server for course. If local copy is
11230: stale, requests a new version from the home server and stores it.
11231: If the original has been removed from the home server, then local copy
11232: is unlinked.
11233: (ii) If local copy does not exist -
11234: requests the file from the home server and stores it.
11235:
11236: If $caller is 'uploadrep':
11237: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11238: for request for files originally uploaded via DOCS.
11239: - returns 'ok' if fresh local copy now available, -1 otherwise.
11240:
11241: Otherwise:
11242: This indicates a call from the content generation phase of the request.
11243: - returns the entire contents of the file or -1.
11244:
11245: (b) files in /res
11246: - returns the entire contents of a file or -1;
11247: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11248:
1.712 albertel 11249:
11250: =item *
11251:
11252: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11253: reference
11254:
11255: returns either a stat() list of data about the file or an empty list
11256: if the file doesn't exist or couldn't find out about it (connection
11257: problems or user unknown)
11258:
1.191 harris41 11259: =item *
11260:
1.243 albertel 11261: filelocation($dir,$file) : returns file system location of a file
11262: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11263: directory that relative $file lookups are to looked in ($dir of /a/dir
11264: and a file of ../bob will become /a/bob)
1.191 harris41 11265:
11266: =item *
11267:
11268: hreflocation($dir,$file) : returns file system location or a URL; same as
11269: filelocation except for hrefs
11270:
11271: =item *
11272:
11273: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11274:
1.243 albertel 11275: =back
11276:
1.608 albertel 11277: =head2 Usererfile file routines (/uploaded*)
11278:
11279: =over 4
11280:
11281: =item *
11282:
11283: userfileupload(): main rotine for putting a file in a user or course's
11284: filespace, arguments are,
11285:
1.620 albertel 11286: formname - required - this is the name of the element in $env where the
1.608 albertel 11287: filename, and the contents of the file to create/modifed exist
1.620 albertel 11288: the filename is in $env{'form.'.$formname.'.filename'} and the
11289: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11290: coursedoc - if true, store the file in the course of the active role
11291: of the current user
11292: subdir - required - subdirectory to put the file in under ../userfiles/
11293: if undefined, it will be placed in "unknown"
11294:
11295: (This routine calls clean_filename() to remove any dangerous
11296: characters from the filename, and then calls finuserfileupload() to
11297: complete the transaction)
11298:
11299: returns either the url of the uploaded file (/uploaded/....) if successful
11300: and /adm/notfound.html if unsuccessful
11301:
11302: =item *
11303:
11304: clean_filename(): routine for cleaing a filename up for storage in
11305: userfile space, argument is:
11306:
11307: filename - proposed filename
11308:
11309: returns: the new clean filename
11310:
11311: =item *
11312:
11313: finishuserfileupload(): routine that creaes and sends the file to
11314: userspace, probably shouldn't be called directly
11315:
11316: docuname: username or courseid of destination for the file
11317: docudom: domain of user/course of destination for the file
11318: formname: same as for userfileupload()
11319: fname: filename (inculding subdirectories) for the file
11320:
11321: returns either the url of the uploaded file (/uploaded/....) if successful
11322: and /adm/notfound.html if unsuccessful
11323:
11324: =item *
11325:
11326: renameuserfile(): renames an existing userfile to a new name
11327:
11328: Args:
11329: docuname: username or courseid of destination for the file
11330: docudom: domain of user/course of destination for the file
11331: old: current file name (including any subdirs under userfiles)
11332: new: desired file name (including any subdirs under userfiles)
11333:
11334: =item *
11335:
11336: mkdiruserfile(): creates a directory is a userfiles dir
11337:
11338: Args:
11339: docuname: username or courseid of destination for the file
11340: docudom: domain of user/course of destination for the file
11341: dir: dir to create (including any subdirs under userfiles)
11342:
11343: =item *
11344:
11345: removeuserfile(): removes a file that exists in userfiles
11346:
11347: Args:
11348: docuname: username or courseid of destination for the file
11349: docudom: domain of user/course of destination for the file
11350: fname: filname to delete (including any subdirs under userfiles)
11351:
11352: =item *
11353:
11354: removeuploadedurl(): convience function for removeuserfile()
11355:
11356: Args:
11357: url: a full /uploaded/... url to delete
11358:
1.747 albertel 11359: =item *
11360:
11361: get_portfile_permissions():
11362: Args:
11363: domain: domain of user or course contain the portfolio files
11364: user: name of user or num of course contain the portfolio files
11365: Returns:
11366: hashref of a dump of the proper file_permissions.db
11367:
11368:
11369: =item *
11370:
11371: get_access_controls():
11372:
11373: Args:
11374: current_permissions: the hash ref returned from get_portfile_permissions()
11375: group: (optional) the group you want the files associated with
11376: file: (optional) the file you want access info on
11377:
11378: Returns:
1.749 raeburn 11379: a hash (keys are file names) of hashes containing
11380: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11381: values are XML containing access control settings (see below)
1.747 albertel 11382:
11383: Internal notes:
11384:
1.749 raeburn 11385: access controls are stored in file_permissions.db as key=value pairs.
11386: key -> path to file/file_name\0uniqueID:scope_end_start
11387: where scope -> public,guest,course,group,domains or users.
11388: end -> UNIX time for end of access (0 -> no end date)
11389: start -> UNIX time for start of access
11390:
11391: value -> XML description of access control
11392: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11393: <start></start>
11394: <end></end>
11395:
11396: <password></password> for scope type = guest
11397:
11398: <domain></domain> for scope type = course or group
11399: <number></number>
11400: <roles id="">
11401: <role></role>
11402: <access></access>
11403: <section></section>
11404: <group></group>
11405: </roles>
11406:
11407: <dom></dom> for scope type = domains
11408:
11409: <users> for scope type = users
11410: <user>
11411: <uname></uname>
11412: <udom></udom>
11413: </user>
11414: </users>
11415: </scope>
11416:
11417: Access data is also aggregated for each file in an additional key=value pair:
11418: key -> path to file/file_name\0accesscontrol
11419: value -> reference to hash
11420: hash contains key = value pairs
11421: where key = uniqueID:scope_end_start
11422: value = UNIX time record was last updated
11423:
11424: Used to improve speed of look-ups of access controls for each file.
11425:
11426: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11427:
11428: modify_access_controls():
11429:
11430: Modifies access controls for a portfolio file
11431: Args
11432: 1. file name
11433: 2. reference to hash of required changes,
11434: 3. domain
11435: 4. username
11436: where domain,username are the domain of the portfolio owner
11437: (either a user or a course)
11438:
11439: Returns:
11440: 1. result of additions or updates ('ok' or 'error', with error message).
11441: 2. result of deletions ('ok' or 'error', with error message).
11442: 3. reference to hash of any new or updated access controls.
11443: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11444: key = integer (inbound ID)
11445: value = uniqueID
1.747 albertel 11446:
1.608 albertel 11447: =back
11448:
1.243 albertel 11449: =head2 HTTP Helper Routines
11450:
11451: =over 4
11452:
1.191 harris41 11453: =item *
11454:
11455: escape() : unpack non-word characters into CGI-compatible hex codes
11456:
11457: =item *
11458:
11459: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11460:
1.243 albertel 11461: =back
11462:
11463: =head1 PRIVATE SUBROUTINES
11464:
11465: =head2 Underlying communication routines (Shouldn't call)
11466:
11467: =over 4
11468:
11469: =item *
11470:
11471: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11472:
11473: =item *
11474:
11475: reply() : uses subreply to send a message to remote machine, logs all failures
11476:
11477: =item *
11478:
11479: critical() : passes a critical message to another server; if cannot
11480: get through then place message in connection buffer directory and
11481: returns con_delayed, if incapable of saving message, returns
11482: con_failed
11483:
11484: =item *
11485:
11486: reconlonc() : tries to reconnect lonc client processes.
11487:
11488: =back
11489:
11490: =head2 Resource Access Logging
11491:
11492: =over 4
11493:
11494: =item *
11495:
11496: flushcourselogs() : flush (save) buffer logs and access logs
11497:
11498: =item *
11499:
11500: courselog($what) : save message for course in hash
11501:
11502: =item *
11503:
11504: courseacclog($what) : save message for course using &courselog(). Perform
11505: special processing for specific resource types (problems, exams, quizzes, etc).
11506:
1.191 harris41 11507: =item *
11508:
11509: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11510: as a PerlChildExitHandler
1.243 albertel 11511:
11512: =back
11513:
11514: =head2 Other
11515:
11516: =over 4
11517:
11518: =item *
11519:
11520: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11521:
11522: =back
11523:
11524: =cut
1.877 foxr 11525:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>