Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1087
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1087 ! raeburn 4: # $Id: lonnet.pm,v 1.1086 2010/09/26 01:50:33 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.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
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.1073 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.1073 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'};
1.1081 raeburn 225: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 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;
1.1082 raeburn 233: $ua->timeout(4);
1.1073 raeburn 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;
1.1081 raeburn 241: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
1.1081 raeburn 248: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 249: $loncaparev = $1;
250: }
1.993 raeburn 251: }
1.1073 raeburn 252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 253: }
254: }
255:
1.1074 raeburn 256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
260: if (defined($cached)) {
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: }
274: }
275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
280: }
281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
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:
1.1 albertel 727: # ------------------------------ Find server with least workload from spare.tab
1.11 www 728:
1.1 albertel 729: sub spareserver {
1.1083 raeburn 730: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 731: my $spare_server;
1.370 albertel 732: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 733: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
734: : $userloadpercent;
1.1083 raeburn 735: my ($uint_dom,$remotesessions);
736: if (($udom ne '') && (&domain($udom) ne '')) {
737: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
738: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
739: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
740: $remotesessions = $udomdefaults{'remotesessions'};
741: }
1.784 albertel 742: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083 raeburn 743: if ($uint_dom) {
744: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
745: $try_server));
746: }
1.784 albertel 747: ($spare_server, $lowest_load) =
748: &compare_server_load($try_server, $spare_server, $lowest_load);
749: }
750:
751: my $found_server = ($spare_server ne '' && $lowest_load < 100);
752:
753: if (!$found_server) {
754: foreach my $try_server (@{ $spareid{'default'} }) {
1.1083 raeburn 755: if ($uint_dom) {
756: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
757: $try_server));
758: }
1.784 albertel 759: ($spare_server, $lowest_load) =
760: &compare_server_load($try_server, $spare_server, $lowest_load);
761: }
762: }
763:
764: if (!$want_server_name) {
1.968 raeburn 765: my $protocol = 'http';
766: if ($protocol{$spare_server} eq 'https') {
767: $protocol = $protocol{$spare_server};
768: }
1.1001 raeburn 769: if (defined($spare_server)) {
770: my $hostname = &hostname($spare_server);
1.1083 raeburn 771: if (defined($hostname)) {
1.1001 raeburn 772: $spare_server = $protocol.'://'.$hostname;
773: }
774: }
1.784 albertel 775: }
776: return $spare_server;
777: }
778:
779: sub compare_server_load {
780: my ($try_server, $spare_server, $lowest_load) = @_;
781:
782: my $loadans = &reply('load', $try_server);
783: my $userloadans = &reply('userload',$try_server);
784:
785: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 786: return; #didn't get a number from the server
1.784 albertel 787: }
788:
789: my $load;
790: if ($loadans =~ /\d/) {
791: if ($userloadans =~ /\d/) {
792: #both are numbers, pick the bigger one
793: $load = ($loadans > $userloadans) ? $loadans
794: : $userloadans;
1.411 albertel 795: } else {
1.784 albertel 796: $load = $loadans;
1.411 albertel 797: }
1.784 albertel 798: } else {
799: $load = $userloadans;
800: }
801:
802: if (($load =~ /\d/) && ($load < $lowest_load)) {
803: $spare_server = $try_server;
804: $lowest_load = $load;
1.370 albertel 805: }
1.784 albertel 806: return ($spare_server,$lowest_load);
1.202 matthew 807: }
1.914 albertel 808:
809: # --------------------------- ask offload servers if user already has a session
810: sub find_existing_session {
811: my ($udom,$uname) = @_;
812: foreach my $try_server (@{ $spareid{'primary'} },
813: @{ $spareid{'default'} }) {
814: return $try_server if (&has_user_session($try_server, $udom, $uname));
815: }
816: return;
817: }
818:
819: # -------------------------------- ask if server already has a session for user
820: sub has_user_session {
821: my ($lonid,$udom,$uname) = @_;
822: my $result = &reply(join(':','userhassession',
823: map {&escape($_)} ($udom,$uname)),$lonid);
824: return 1 if ($result eq 'ok');
825:
826: return 0;
827: }
828:
1.1076 raeburn 829: # --------- determine least loaded server in a user's domain which allows login
830:
831: sub choose_server {
832: my ($udom) = @_;
833: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 834: my %servers = &get_servers($udom);
1.1076 raeburn 835: my $lowest_load = 30000;
836: my ($login_host,$hostname);
837: foreach my $lonhost (keys(%servers)) {
838: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
839: if ($loginvia eq '') {
840: ($login_host, $lowest_load) =
841: &compare_server_load($lonhost, $login_host, $lowest_load);
842: }
843: }
844: if ($login_host ne '') {
845: $hostname = $servers{$login_host};
846: }
847: return ($login_host,$hostname);
848: }
849:
1.202 matthew 850: # --------------------------------------------- Try to change a user's password
851:
852: sub changepass {
1.799 raeburn 853: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 854: $currentpass = &escape($currentpass);
855: $newpass = &escape($newpass);
1.1030 raeburn 856: my $lonhost = $perlvar{'lonHostID'};
857: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 858: $server);
859: if (! $answer) {
860: &logthis("No reply on password change request to $server ".
861: "by $uname in domain $udom.");
862: } elsif ($answer =~ "^ok") {
863: &logthis("$uname in $udom successfully changed their password ".
864: "on $server.");
865: } elsif ($answer =~ "^pwchange_failure") {
866: &logthis("$uname in $udom was unable to change their password ".
867: "on $server. The action was blocked by either lcpasswd ".
868: "or pwchange");
869: } elsif ($answer =~ "^non_authorized") {
870: &logthis("$uname in $udom did not get their password correct when ".
871: "attempting to change it on $server.");
872: } elsif ($answer =~ "^auth_mode_error") {
873: &logthis("$uname in $udom attempted to change their password despite ".
874: "not being locally or internally authenticated on $server.");
875: } elsif ($answer =~ "^unknown_user") {
876: &logthis("$uname in $udom attempted to change their password ".
877: "on $server but were unable to because $server is not ".
878: "their home server.");
879: } elsif ($answer =~ "^refused") {
880: &logthis("$server refused to change $uname in $udom password because ".
881: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 882: } elsif ($answer =~ "invalid_client") {
883: &logthis("$server refused to change $uname in $udom password because ".
884: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 885: }
886: return $answer;
1.1 albertel 887: }
888:
1.169 harris41 889: # ----------------------- Try to determine user's current authentication scheme
890:
891: sub queryauthenticate {
892: my ($uname,$udom)=@_;
1.456 albertel 893: my $uhome=&homeserver($uname,$udom);
894: if (!$uhome) {
895: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
896: return 'no_host';
897: }
898: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
899: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
900: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 901: }
1.456 albertel 902: return $answer;
1.169 harris41 903: }
904:
1.1 albertel 905: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 906:
1.1 albertel 907: sub authenticate {
1.1073 raeburn 908: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 909: $upass=&escape($upass);
910: $uname= &LONCAPA::clean_username($uname);
1.836 www 911: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 912: my $newhome;
1.836 www 913: if ((!$uhome) || ($uhome eq 'no_host')) {
914: # Maybe the machine was offline and only re-appeared again recently?
915: &reconlonc();
916: # One more
1.952 raeburn 917: $uhome=&homeserver($uname,$udom,1);
918: if (($uhome eq 'no_host') && $checkdefauth) {
919: if (defined(&domain($udom,'primary'))) {
920: $newhome=&domain($udom,'primary');
921: }
922: if ($newhome ne '') {
923: $uhome = $newhome;
924: }
925: }
1.836 www 926: if ((!$uhome) || ($uhome eq 'no_host')) {
927: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 928: return 'no_host';
929: }
1.1 albertel 930: }
1.1073 raeburn 931: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 932: if ($answer eq 'authorized') {
1.952 raeburn 933: if ($newhome) {
934: &logthis("User $uname at $udom authorized by $uhome, but needs account");
935: return 'no_account_on_host';
936: } else {
937: &logthis("User $uname at $udom authorized by $uhome");
938: return $uhome;
939: }
1.471 albertel 940: }
941: if ($answer eq 'non_authorized') {
942: &logthis("User $uname at $udom rejected by $uhome");
943: return 'no_host';
1.9 www 944: }
1.471 albertel 945: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 946: return 'no_host';
947: }
948:
1.1073 raeburn 949: sub can_host_session {
1.1074 raeburn 950: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 951: my $canhost = 1;
1.1074 raeburn 952: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 953: if (ref($remotesessions) eq 'HASH') {
954: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 955: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 956: $canhost = 0;
957: } else {
958: $canhost = 1;
959: }
960: }
961: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 962: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 963: $canhost = 1;
964: } else {
965: $canhost = 0;
966: }
967: }
968: if ($canhost) {
969: if ($remotesessions->{'version'} ne '') {
970: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
971: if ($reqmajor ne '' && $reqminor ne '') {
972: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
973: my $major = $1;
974: my $minor = $2;
975: if (($major < $reqmajor ) ||
976: (($major == $reqmajor) && ($minor < $reqminor))) {
977: $canhost = 0;
978: }
979: } else {
980: $canhost = 0;
981: }
982: }
983: }
984: }
985: }
986: if ($canhost) {
987: if (ref($hostedsessions) eq 'HASH') {
988: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
989: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
990: $canhost = 0;
991: } else {
992: $canhost = 1;
993: }
994: }
995: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
996: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
997: $canhost = 1;
998: } else {
999: $canhost = 0;
1000: }
1001: }
1002: }
1003: }
1004: return $canhost;
1005: }
1006:
1.1083 raeburn 1007: sub spare_can_host {
1008: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1009: my $canhost=1;
1010: my @intdoms;
1011: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1012: if (ref($internet_names) eq 'ARRAY') {
1013: @intdoms = @{$internet_names};
1014: }
1015: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1016: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1017: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1018: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1019: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1020: $canhost = &can_host_session($udom,$try_server,$remoterev,
1021: $remotesessions,
1022: $defdomdefaults{'hostedsessions'});
1023: }
1024: return $canhost;
1025: }
1026:
1.1 albertel 1027: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1028:
1.599 albertel 1029: my %homecache;
1.1 albertel 1030: sub homeserver {
1.230 stredwic 1031: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1032: my $index="$uname:$udom";
1.426 albertel 1033:
1.599 albertel 1034: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1035:
1036: my %servers = &get_servers($udom,'library');
1037: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1038: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1039: exists($badServerCache{$tryserver}));
1.841 albertel 1040:
1041: my $answer=reply("home:$udom:$uname",$tryserver);
1042: if ($answer eq 'found') {
1043: delete($badServerCache{$tryserver});
1044: return $homecache{$index}=$tryserver;
1045: } elsif ($answer eq 'no_host') {
1046: $badServerCache{$tryserver}=1;
1047: }
1.1 albertel 1048: }
1049: return 'no_host';
1.70 www 1050: }
1051:
1052: # ------------------------------------- Find the usernames behind a list of IDs
1053:
1054: sub idget {
1055: my ($udom,@ids)=@_;
1056: my %returnhash=();
1057:
1.841 albertel 1058: my %servers = &get_servers($udom,'library');
1059: foreach my $tryserver (keys(%servers)) {
1060: my $idlist=join('&',@ids);
1061: $idlist=~tr/A-Z/a-z/;
1062: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1063: my @answer=();
1064: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1065: @answer=split(/\&/,$reply);
1066: } ;
1067: my $i;
1068: for ($i=0;$i<=$#ids;$i++) {
1069: if ($answer[$i]) {
1070: $returnhash{$ids[$i]}=$answer[$i];
1071: }
1072: }
1073: }
1.70 www 1074: return %returnhash;
1075: }
1076:
1077: # ------------------------------------- Find the IDs behind a list of usernames
1078:
1079: sub idrget {
1080: my ($udom,@unames)=@_;
1081: my %returnhash=();
1.800 albertel 1082: foreach my $uname (@unames) {
1083: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1084: }
1.70 www 1085: return %returnhash;
1086: }
1087:
1088: # ------------------------------- Store away a list of names and associated IDs
1089:
1090: sub idput {
1091: my ($udom,%ids)=@_;
1092: my %servers=();
1.800 albertel 1093: foreach my $uname (keys(%ids)) {
1094: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1095: my $uhom=&homeserver($uname,$udom);
1.70 www 1096: if ($uhom ne 'no_host') {
1.800 albertel 1097: my $id=&escape($ids{$uname});
1.70 www 1098: $id=~tr/A-Z/a-z/;
1.800 albertel 1099: my $esc_unam=&escape($uname);
1.70 www 1100: if ($servers{$uhom}) {
1.800 albertel 1101: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1102: } else {
1.800 albertel 1103: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1104: }
1105: }
1.191 harris41 1106: }
1.800 albertel 1107: foreach my $server (keys(%servers)) {
1108: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1109: }
1.344 www 1110: }
1111:
1.1023 raeburn 1112: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1113: sub dump_dom {
1.1023 raeburn 1114: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1115: if (!$udom) {
1116: $udom=$env{'user.domain'};
1117: }
1118: my %returnhash;
1.1023 raeburn 1119: if ($udom) {
1120: my $uname = &get_domainconfiguser($udom);
1121: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1122: }
1123: return %returnhash;
1124: }
1125:
1.1023 raeburn 1126: # ------------------------------------------ get items from domain db files
1.806 raeburn 1127:
1128: sub get_dom {
1.860 raeburn 1129: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1130: my $items='';
1131: foreach my $item (@$storearr) {
1132: $items.=&escape($item).'&';
1133: }
1134: $items=~s/\&$//;
1.860 raeburn 1135: if (!$udom) {
1136: $udom=$env{'user.domain'};
1137: if (defined(&domain($udom,'primary'))) {
1138: $uhome=&domain($udom,'primary');
1139: } else {
1.874 albertel 1140: undef($uhome);
1.860 raeburn 1141: }
1142: } else {
1143: if (!$uhome) {
1144: if (defined(&domain($udom,'primary'))) {
1145: $uhome=&domain($udom,'primary');
1146: }
1147: }
1148: }
1149: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1150: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1151: my %returnhash;
1.875 albertel 1152: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1153: return %returnhash;
1154: }
1.806 raeburn 1155: my @pairs=split(/\&/,$rep);
1156: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1157: return @pairs;
1158: }
1159: my $i=0;
1160: foreach my $item (@$storearr) {
1161: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1162: $i++;
1163: }
1164: return %returnhash;
1165: } else {
1.880 banghart 1166: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1167: }
1168: }
1169:
1170: # -------------------------------------------- put items in domain db files
1171:
1172: sub put_dom {
1.860 raeburn 1173: my ($namespace,$storehash,$udom,$uhome)=@_;
1174: if (!$udom) {
1175: $udom=$env{'user.domain'};
1176: if (defined(&domain($udom,'primary'))) {
1177: $uhome=&domain($udom,'primary');
1178: } else {
1.874 albertel 1179: undef($uhome);
1.860 raeburn 1180: }
1181: } else {
1182: if (!$uhome) {
1183: if (defined(&domain($udom,'primary'))) {
1184: $uhome=&domain($udom,'primary');
1185: }
1186: }
1187: }
1188: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1189: my $items='';
1190: foreach my $item (keys(%$storehash)) {
1191: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1192: }
1193: $items=~s/\&$//;
1194: return &reply("putdom:$udom:$namespace:$items",$uhome);
1195: } else {
1.860 raeburn 1196: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1197: }
1198: }
1199:
1.1023 raeburn 1200: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1201: sub newput_dom {
1.1023 raeburn 1202: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1203: my $result;
1204: if (!$udom) {
1205: $udom=$env{'user.domain'};
1206: }
1.1023 raeburn 1207: if ($udom) {
1208: my $uname = &get_domainconfiguser($udom);
1209: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1210: }
1211: return $result;
1212: }
1213:
1.1023 raeburn 1214: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1215: sub del_dom {
1.1023 raeburn 1216: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1217: if (ref($storearr) eq 'ARRAY') {
1218: if (!$udom) {
1219: $udom=$env{'user.domain'};
1220: }
1.1023 raeburn 1221: if ($udom) {
1222: my $uname = &get_domainconfiguser($udom);
1223: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1224: }
1225: }
1226: }
1227:
1.1023 raeburn 1228: # ----------------------------------construct domainconfig user for a domain
1229: sub get_domainconfiguser {
1230: my ($udom) = @_;
1231: return $udom.'-domainconfig';
1232: }
1233:
1.837 raeburn 1234: sub retrieve_inst_usertypes {
1235: my ($udom) = @_;
1236: my (%returnhash,@order);
1.989 raeburn 1237: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1238: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1239: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1240: %returnhash = %{$domdefs{'inststatustypes'}};
1241: @order = @{$domdefs{'inststatusorder'}};
1242: } else {
1243: if (defined(&domain($udom,'primary'))) {
1244: my $uhome=&domain($udom,'primary');
1245: my $rep=&reply("inst_usertypes:$udom",$uhome);
1246: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1247: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1248: return (\%returnhash,\@order);
1249: }
1250: my ($hashitems,$orderitems) = split(/:/,$rep);
1251: my @pairs=split(/\&/,$hashitems);
1252: foreach my $item (@pairs) {
1253: my ($key,$value)=split(/=/,$item,2);
1254: $key = &unescape($key);
1255: next if ($key =~ /^error: 2 /);
1256: $returnhash{$key}=&thaw_unescape($value);
1257: }
1258: my @esc_order = split(/\&/,$orderitems);
1259: foreach my $item (@esc_order) {
1260: push(@order,&unescape($item));
1261: }
1262: } else {
1263: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1264: }
1265: }
1266: return (\%returnhash,\@order);
1267: }
1268:
1.868 raeburn 1269: sub is_domainimage {
1270: my ($url) = @_;
1271: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1272: if (&domain($1) ne '') {
1273: return '1';
1274: }
1275: }
1276: return;
1277: }
1278:
1.899 raeburn 1279: sub inst_directory_query {
1280: my ($srch) = @_;
1281: my $udom = $srch->{'srchdomain'};
1282: my %results;
1283: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1284: my $outcome;
1.899 raeburn 1285: if ($homeserver ne '') {
1.904 albertel 1286: my $queryid=&reply("querysend:instdirsearch:".
1287: &escape($srch->{'srchby'}).':'.
1288: &escape($srch->{'srchterm'}).':'.
1289: &escape($srch->{'srchtype'}),$homeserver);
1290: my $host=&hostname($homeserver);
1291: if ($queryid !~/^\Q$host\E\_/) {
1292: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1293: return;
1294: }
1295: my $response = &get_query_reply($queryid);
1296: my $maxtries = 5;
1297: my $tries = 1;
1298: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1299: $response = &get_query_reply($queryid);
1300: $tries ++;
1301: }
1302:
1303: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1304: if ($response eq 'unavailable') {
1305: $outcome = $response;
1306: } else {
1307: $outcome = 'ok';
1308: my @matches = split(/\n/,$response);
1309: foreach my $match (@matches) {
1310: my ($key,$value) = split(/=/,$match);
1311: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1312: }
1.899 raeburn 1313: }
1314: }
1315: }
1.909 raeburn 1316: return ($outcome,%results);
1.899 raeburn 1317: }
1318:
1319: sub usersearch {
1320: my ($srch) = @_;
1321: my $dom = $srch->{'srchdomain'};
1322: my %results;
1323: my %libserv = &all_library();
1324: my $query = 'usersearch';
1325: foreach my $tryserver (keys(%libserv)) {
1326: if (&host_domain($tryserver) eq $dom) {
1327: my $host=&hostname($tryserver);
1328: my $queryid=
1.911 raeburn 1329: &reply("querysend:".&escape($query).':'.
1330: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1331: &escape($srch->{'srchtype'}).':'.
1332: &escape($srch->{'srchterm'}),$tryserver);
1333: if ($queryid !~/^\Q$host\E\_/) {
1334: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1335: next;
1.899 raeburn 1336: }
1337: my $reply = &get_query_reply($queryid);
1338: my $maxtries = 1;
1339: my $tries = 1;
1340: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1341: $reply = &get_query_reply($queryid);
1342: $tries ++;
1343: }
1344: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1345: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1346: } else {
1.911 raeburn 1347: my @matches;
1348: if ($reply =~ /\n/) {
1349: @matches = split(/\n/,$reply);
1350: } else {
1351: @matches = split(/\&/,$reply);
1352: }
1.899 raeburn 1353: foreach my $match (@matches) {
1354: my ($uname,$udom,%userhash);
1.911 raeburn 1355: foreach my $entry (split(/:/,$match)) {
1356: my ($key,$value) =
1357: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1358: $userhash{$key} = $value;
1359: if ($key eq 'username') {
1360: $uname = $value;
1361: } elsif ($key eq 'domain') {
1362: $udom = $value;
1.911 raeburn 1363: }
1.899 raeburn 1364: }
1365: $results{$uname.':'.$udom} = \%userhash;
1366: }
1367: }
1368: }
1369: }
1370: return %results;
1371: }
1372:
1.912 raeburn 1373: sub get_instuser {
1374: my ($udom,$uname,$id) = @_;
1375: my $homeserver = &domain($udom,'primary');
1376: my ($outcome,%results);
1377: if ($homeserver ne '') {
1378: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1379: &escape($id).':'.&escape($udom),$homeserver);
1380: my $host=&hostname($homeserver);
1381: if ($queryid !~/^\Q$host\E\_/) {
1382: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1383: return;
1384: }
1385: my $response = &get_query_reply($queryid);
1386: my $maxtries = 5;
1387: my $tries = 1;
1388: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1389: $response = &get_query_reply($queryid);
1390: $tries ++;
1391: }
1392: if (!&error($response) && $response ne 'refused') {
1393: if ($response eq 'unavailable') {
1394: $outcome = $response;
1395: } else {
1396: $outcome = 'ok';
1397: my @matches = split(/\n/,$response);
1398: foreach my $match (@matches) {
1399: my ($key,$value) = split(/=/,$match);
1400: $results{&unescape($key)} = &thaw_unescape($value);
1401: }
1402: }
1403: }
1404: }
1405: my %userinfo;
1406: if (ref($results{$uname}) eq 'HASH') {
1407: %userinfo = %{$results{$uname}};
1408: }
1409: return ($outcome,%userinfo);
1410: }
1411:
1412: sub inst_rulecheck {
1.923 raeburn 1413: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1414: my %returnhash;
1415: if ($udom ne '') {
1416: if (ref($rules) eq 'ARRAY') {
1417: @{$rules} = map {&escape($_);} (@{$rules});
1418: my $rulestr = join(':',@{$rules});
1419: my $homeserver=&domain($udom,'primary');
1420: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1421: my $response;
1422: if ($item eq 'username') {
1423: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1424: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1425: $homeserver));
1.923 raeburn 1426: } elsif ($item eq 'id') {
1427: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1428: ':'.&escape($id).':'.$rulestr,
1429: $homeserver));
1.945 raeburn 1430: } elsif ($item eq 'selfcreate') {
1431: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1432: &escape($udom).':'.&escape($uname).
1433: ':'.$rulestr,$homeserver));
1.923 raeburn 1434: }
1.912 raeburn 1435: if ($response ne 'refused') {
1436: my @pairs=split(/\&/,$response);
1437: foreach my $item (@pairs) {
1438: my ($key,$value)=split(/=/,$item,2);
1439: $key = &unescape($key);
1440: next if ($key =~ /^error: 2 /);
1441: $returnhash{$key}=&thaw_unescape($value);
1442: }
1443: }
1444: }
1445: }
1446: }
1447: return %returnhash;
1448: }
1449:
1450: sub inst_userrules {
1.923 raeburn 1451: my ($udom,$check) = @_;
1.912 raeburn 1452: my (%ruleshash,@ruleorder);
1453: if ($udom ne '') {
1454: my $homeserver=&domain($udom,'primary');
1455: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1456: my $response;
1457: if ($check eq 'id') {
1458: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1459: $homeserver);
1.943 raeburn 1460: } elsif ($check eq 'email') {
1461: $response=&reply('instemailrules:'.&escape($udom),
1462: $homeserver);
1.923 raeburn 1463: } else {
1464: $response=&reply('instuserrules:'.&escape($udom),
1465: $homeserver);
1466: }
1.912 raeburn 1467: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1468: ($response ne 'unknown_cmd') &&
1.912 raeburn 1469: ($response ne 'no_such_host')) {
1470: my ($hashitems,$orderitems) = split(/:/,$response);
1471: my @pairs=split(/\&/,$hashitems);
1472: foreach my $item (@pairs) {
1473: my ($key,$value)=split(/=/,$item,2);
1474: $key = &unescape($key);
1475: next if ($key =~ /^error: 2 /);
1476: $ruleshash{$key}=&thaw_unescape($value);
1477: }
1478: my @esc_order = split(/\&/,$orderitems);
1479: foreach my $item (@esc_order) {
1480: push(@ruleorder,&unescape($item));
1481: }
1482: }
1483: }
1484: }
1485: return (\%ruleshash,\@ruleorder);
1486: }
1487:
1.976 raeburn 1488: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1489:
1490: sub get_domain_defaults {
1491: my ($domain) = @_;
1492: my $cachetime = 60*60*24;
1493: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1494: if (defined($cached)) {
1495: if (ref($result) eq 'HASH') {
1496: return %{$result};
1497: }
1498: }
1499: my %domdefaults;
1500: my %domconfig =
1.989 raeburn 1501: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1502: 'requestcourses','inststatus',
1.1073 raeburn 1503: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1504: if (ref($domconfig{'defaults'}) eq 'HASH') {
1505: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1506: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1507: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1508: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1509: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1510: } else {
1511: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1512: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1513: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1514: }
1.976 raeburn 1515: if (ref($domconfig{'quotas'}) eq 'HASH') {
1516: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1517: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1518: } else {
1519: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1520: }
1521: my @usertools = ('aboutme','blog','portfolio');
1522: foreach my $item (@usertools) {
1523: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1524: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1525: }
1526: }
1527: }
1.985 raeburn 1528: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1529: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1530: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1531: }
1532: }
1.989 raeburn 1533: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1534: foreach my $item ('inststatustypes','inststatusorder') {
1535: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1536: }
1537: }
1.1047 raeburn 1538: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1539: foreach my $item ('canuse_pdfforms') {
1540: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1541: }
1542: }
1.1073 raeburn 1543: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1544: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1545: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1546: }
1547: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1548: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1549: }
1550: }
1.943 raeburn 1551: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1552: $cachetime);
1553: return %domdefaults;
1554: }
1555:
1.344 www 1556: # --------------------------------------------------- Assign a key to a student
1557:
1558: sub assign_access_key {
1.364 www 1559: #
1560: # a valid key looks like uname:udom#comments
1561: # comments are being appended
1562: #
1.498 www 1563: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1564: $kdom=
1.620 albertel 1565: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1566: $knum=
1.620 albertel 1567: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1568: $cdom=
1.620 albertel 1569: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1570: $cnum=
1.620 albertel 1571: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1572: $udom=$env{'user.name'} unless (defined($udom));
1573: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1574: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1575: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1576: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1577: # assigned to this person
1578: # - this should not happen,
1.345 www 1579: # unless something went wrong
1580: # the first time around
1581: # ready to assign
1.364 www 1582: $logentry=$1.'; '.$logentry;
1.496 www 1583: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1584: $kdom,$knum) eq 'ok') {
1.345 www 1585: # key now belongs to user
1.346 www 1586: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1587: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1588: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1589: return 'ok';
1590: } else {
1591: return
1592: 'error: Count not permanently assign key, will need to be re-entered later.';
1593: }
1594: } else {
1595: return 'error: Could not assign key, try again later.';
1596: }
1.364 www 1597: } elsif (!$existing{$ckey}) {
1.345 www 1598: # the key does not exist
1599: return 'error: The key does not exist';
1600: } else {
1601: # the key is somebody else's
1602: return 'error: The key is already in use';
1603: }
1.344 www 1604: }
1605:
1.364 www 1606: # ------------------------------------------ put an additional comment on a key
1607:
1608: sub comment_access_key {
1609: #
1610: # a valid key looks like uname:udom#comments
1611: # comments are being appended
1612: #
1613: my ($ckey,$cdom,$cnum,$logentry)=@_;
1614: $cdom=
1.620 albertel 1615: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1616: $cnum=
1.620 albertel 1617: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1618: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1619: if ($existing{$ckey}) {
1620: $existing{$ckey}.='; '.$logentry;
1621: # ready to assign
1.367 www 1622: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1623: $cdom,$cnum) eq 'ok') {
1624: return 'ok';
1625: } else {
1626: return 'error: Count not store comment.';
1627: }
1628: } else {
1629: # the key does not exist
1630: return 'error: The key does not exist';
1631: }
1632: }
1633:
1.344 www 1634: # ------------------------------------------------------ Generate a set of keys
1635:
1636: sub generate_access_keys {
1.364 www 1637: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1638: $cdom=
1.620 albertel 1639: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1640: $cnum=
1.620 albertel 1641: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1642: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1643: unless (($cdom) && ($cnum)) { return 0; }
1644: if ($number>10000) { return 0; }
1645: sleep(2); # make sure don't get same seed twice
1646: srand(time()^($$+($$<<15))); # from "Programming Perl"
1647: my $total=0;
1648: for (my $i=1;$i<=$number;$i++) {
1649: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1650: sprintf("%lx",int(100000*rand)).'-'.
1651: sprintf("%lx",int(100000*rand));
1652: $newkey=~s/1/g/g; # folks mix up 1 and l
1653: $newkey=~s/0/h/g; # and also 0 and O
1654: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1655: if ($existing{$newkey}) {
1656: $i--;
1657: } else {
1.364 www 1658: if (&put('accesskeys',
1659: { $newkey => '# generated '.localtime().
1.620 albertel 1660: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1661: '; '.$logentry },
1662: $cdom,$cnum) eq 'ok') {
1.344 www 1663: $total++;
1664: }
1665: }
1666: }
1.620 albertel 1667: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1668: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1669: return $total;
1670: }
1671:
1672: # ------------------------------------------------------- Validate an accesskey
1673:
1674: sub validate_access_key {
1675: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1676: $cdom=
1.620 albertel 1677: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1678: $cnum=
1.620 albertel 1679: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1680: $udom=$env{'user.domain'} unless (defined($udom));
1681: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1682: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1683: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1684: }
1685:
1686: # ------------------------------------- Find the section of student in a course
1.652 albertel 1687: sub devalidate_getsection_cache {
1688: my ($udom,$unam,$courseid)=@_;
1689: my $hashid="$udom:$unam:$courseid";
1690: &devalidate_cache_new('getsection',$hashid);
1691: }
1.298 matthew 1692:
1.815 albertel 1693: sub courseid_to_courseurl {
1694: my ($courseid) = @_;
1695: #already url style courseid
1696: return $courseid if ($courseid =~ m{^/});
1697:
1698: if (exists($env{'course.'.$courseid.'.num'})) {
1699: my $cnum = $env{'course.'.$courseid.'.num'};
1700: my $cdom = $env{'course.'.$courseid.'.domain'};
1701: return "/$cdom/$cnum";
1702: }
1703:
1704: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1705: if (exists($courseinfo{'num'})) {
1706: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1707: }
1708:
1709: return undef;
1710: }
1711:
1.298 matthew 1712: sub getsection {
1713: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1714: my $cachetime=1800;
1.551 albertel 1715:
1716: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1717: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1718: if (defined($cached)) { return $result; }
1719:
1.298 matthew 1720: my %Pending;
1721: my %Expired;
1722: #
1723: # Each role can either have not started yet (pending), be active,
1724: # or have expired.
1725: #
1726: # If there is an active role, we are done.
1727: #
1728: # If there is more than one role which has not started yet,
1729: # choose the one which will start sooner
1730: # If there is one role which has not started yet, return it.
1731: #
1732: # If there is more than one expired role, choose the one which ended last.
1733: # If there is a role which has expired, return it.
1734: #
1.815 albertel 1735: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1736: my $extra = &freeze_escape({'skipcheck' => 1});
1737: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1738: foreach my $key (keys(%roleshash)) {
1.479 albertel 1739: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1740: my $section=$1;
1741: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1742: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1743: my $now=time;
1.548 albertel 1744: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1745: $Expired{$end}=$section;
1746: next;
1747: }
1.548 albertel 1748: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1749: $Pending{$start}=$section;
1750: next;
1751: }
1.599 albertel 1752: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1753: }
1754: #
1755: # Presumedly there will be few matching roles from the above
1756: # loop and the sorting time will be negligible.
1757: if (scalar(keys(%Pending))) {
1758: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1759: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1760: }
1761: if (scalar(keys(%Expired))) {
1762: my @sorted = sort {$a <=> $b} keys(%Expired);
1763: my $time = pop(@sorted);
1.599 albertel 1764: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1765: }
1.599 albertel 1766: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1767: }
1.70 www 1768:
1.599 albertel 1769: sub save_cache {
1770: &purge_remembered();
1.722 albertel 1771: #&Apache::loncommon::validate_page();
1.620 albertel 1772: undef(%env);
1.780 albertel 1773: undef($env_loaded);
1.599 albertel 1774: }
1.452 albertel 1775:
1.599 albertel 1776: my $to_remember=-1;
1777: my %remembered;
1778: my %accessed;
1779: my $kicks=0;
1780: my $hits=0;
1.849 albertel 1781: sub make_key {
1782: my ($name,$id) = @_;
1.872 albertel 1783: if (length($id) > 65
1784: && length(&escape($id)) > 200) {
1785: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1786: }
1.849 albertel 1787: return &escape($name.':'.$id);
1788: }
1789:
1.599 albertel 1790: sub devalidate_cache_new {
1791: my ($name,$id,$debug) = @_;
1792: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1793: $id=&make_key($name,$id);
1.599 albertel 1794: $memcache->delete($id);
1795: delete($remembered{$id});
1796: delete($accessed{$id});
1797: }
1798:
1799: sub is_cached_new {
1800: my ($name,$id,$debug) = @_;
1.849 albertel 1801: $id=&make_key($name,$id);
1.599 albertel 1802: if (exists($remembered{$id})) {
1803: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1804: $accessed{$id}=[&gettimeofday()];
1805: $hits++;
1806: return ($remembered{$id},1);
1807: }
1808: my $value = $memcache->get($id);
1809: if (!(defined($value))) {
1810: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1811: return (undef,undef);
1.416 albertel 1812: }
1.599 albertel 1813: if ($value eq '__undef__') {
1814: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1815: $value=undef;
1816: }
1817: &make_room($id,$value,$debug);
1818: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1819: return ($value,1);
1820: }
1821:
1822: sub do_cache_new {
1823: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1824: $id=&make_key($name,$id);
1.599 albertel 1825: my $setvalue=$value;
1826: if (!defined($setvalue)) {
1827: $setvalue='__undef__';
1828: }
1.623 albertel 1829: if (!defined($time) ) {
1830: $time=600;
1831: }
1.599 albertel 1832: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1833: my $result = $memcache->set($id,$setvalue,$time);
1834: if (! $result) {
1.872 albertel 1835: &logthis("caching of id -> $id failed");
1.910 albertel 1836: $memcache->disconnect_all();
1.872 albertel 1837: }
1.600 albertel 1838: # need to make a copy of $value
1.919 albertel 1839: &make_room($id,$value,$debug);
1.599 albertel 1840: return $value;
1841: }
1842:
1843: sub make_room {
1844: my ($id,$value,$debug)=@_;
1.919 albertel 1845:
1846: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1847: : $value;
1.599 albertel 1848: if ($to_remember<0) { return; }
1849: $accessed{$id}=[&gettimeofday()];
1850: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1851: my $to_kick;
1852: my $max_time=0;
1853: foreach my $other (keys(%accessed)) {
1854: if (&tv_interval($accessed{$other}) > $max_time) {
1855: $to_kick=$other;
1856: $max_time=&tv_interval($accessed{$other});
1857: }
1858: }
1859: delete($remembered{$to_kick});
1860: delete($accessed{$to_kick});
1861: $kicks++;
1862: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1863: return;
1864: }
1865:
1.599 albertel 1866: sub purge_remembered {
1.604 albertel 1867: #&logthis("Tossing ".scalar(keys(%remembered)));
1868: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1869: undef(%remembered);
1870: undef(%accessed);
1.428 albertel 1871: }
1.70 www 1872: # ------------------------------------- Read an entry from a user's environment
1873:
1874: sub userenvironment {
1875: my ($udom,$unam,@what)=@_;
1.976 raeburn 1876: my $items;
1877: foreach my $item (@what) {
1878: $items.=&escape($item).'&';
1879: }
1880: $items=~s/\&$//;
1.70 www 1881: my %returnhash=();
1.1009 raeburn 1882: my $uhome = &homeserver($unam,$udom);
1883: unless ($uhome eq 'no_host') {
1884: my @answer=split(/\&/,
1885: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1886: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1887: return %returnhash;
1888: }
1.1009 raeburn 1889: my $i;
1890: for ($i=0;$i<=$#what;$i++) {
1891: $returnhash{$what[$i]}=&unescape($answer[$i]);
1892: }
1.70 www 1893: }
1894: return %returnhash;
1.1 albertel 1895: }
1896:
1.617 albertel 1897: # ---------------------------------------------------------- Get a studentphoto
1898: sub studentphoto {
1899: my ($udom,$unam,$ext) = @_;
1900: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1901: if (defined($env{'request.course.id'})) {
1.708 raeburn 1902: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1903: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1904: return(&retrievestudentphoto($udom,$unam,$ext));
1905: } else {
1906: my ($result,$perm_reqd)=
1.707 albertel 1907: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1908: if ($result eq 'ok') {
1909: if (!($perm_reqd eq 'yes')) {
1910: return(&retrievestudentphoto($udom,$unam,$ext));
1911: }
1912: }
1913: }
1914: }
1915: } else {
1916: my ($result,$perm_reqd) =
1.707 albertel 1917: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1918: if ($result eq 'ok') {
1919: if (!($perm_reqd eq 'yes')) {
1920: return(&retrievestudentphoto($udom,$unam,$ext));
1921: }
1922: }
1923: }
1924: return '/adm/lonKaputt/lonlogo_broken.gif';
1925: }
1926:
1927: sub retrievestudentphoto {
1928: my ($udom,$unam,$ext,$type) = @_;
1929: my $home=&Apache::lonnet::homeserver($unam,$udom);
1930: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1931: if ($ret eq 'ok') {
1932: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1933: if ($type eq 'thumbnail') {
1934: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1935: }
1936: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1937: return $tokenurl;
1938: } else {
1939: if ($type eq 'thumbnail') {
1940: return '/adm/lonKaputt/genericstudent_tn.gif';
1941: } else {
1942: return '/adm/lonKaputt/lonlogo_broken.gif';
1943: }
1.617 albertel 1944: }
1945: }
1946:
1.263 www 1947: # -------------------------------------------------------------------- New chat
1948:
1949: sub chatsend {
1.724 raeburn 1950: my ($newentry,$anon,$group)=@_;
1.620 albertel 1951: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1952: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1953: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1954: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1955: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1956: &escape($newentry)).':'.$group,$chome);
1.292 www 1957: }
1958:
1959: # ------------------------------------------ Find current version of a resource
1960:
1961: sub getversion {
1962: my $fname=&clutter(shift);
1963: unless ($fname=~/^\/res\//) { return -1; }
1964: return ¤tversion(&filelocation('',$fname));
1965: }
1966:
1967: sub currentversion {
1968: my $fname=shift;
1.599 albertel 1969: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1970: if (defined($cached)) { return $result; }
1.292 www 1971: my $author=$fname;
1972: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1973: my ($udom,$uname)=split(/\//,$author);
1974: my $home=homeserver($uname,$udom);
1975: if ($home eq 'no_host') {
1976: return -1;
1977: }
1978: my $answer=reply("currentversion:$fname",$home);
1979: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1980: return -1;
1981: }
1.599 albertel 1982: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1983: }
1984:
1.1 albertel 1985: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1986:
1.1 albertel 1987: sub subscribe {
1988: my $fname=shift;
1.761 raeburn 1989: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1990: $fname=~s/[\n\r]//g;
1.1 albertel 1991: my $author=$fname;
1992: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1993: my ($udom,$uname)=split(/\//,$author);
1994: my $home=homeserver($uname,$udom);
1.335 albertel 1995: if ($home eq 'no_host') {
1996: return 'not_found';
1.1 albertel 1997: }
1998: my $answer=reply("sub:$fname",$home);
1.64 www 1999: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2000: $answer.=' by '.$home;
2001: }
1.1 albertel 2002: return $answer;
2003: }
2004:
1.8 www 2005: # -------------------------------------------------------------- Replicate file
2006:
2007: sub repcopy {
2008: my $filename=shift;
1.23 www 2009: $filename=~s/\/+/\//g;
1.607 raeburn 2010: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2011: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2012: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2013: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2014: return &repcopy_userfile($filename);
2015: }
1.532 albertel 2016: $filename=~s/[\n\r]//g;
1.8 www 2017: my $transname="$filename.in.transfer";
1.828 www 2018: # FIXME: this should flock
1.607 raeburn 2019: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2020: my $remoteurl=subscribe($filename);
1.64 www 2021: if ($remoteurl =~ /^con_lost by/) {
2022: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2023: return 'unavailable';
1.8 www 2024: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2025: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2026: return 'not_found';
1.64 www 2027: } elsif ($remoteurl =~ /^rejected by/) {
2028: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2029: return 'forbidden';
1.20 www 2030: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2031: return 'ok';
1.8 www 2032: } else {
1.290 www 2033: my $author=$filename;
2034: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2035: my ($udom,$uname)=split(/\//,$author);
2036: my $home=homeserver($uname,$udom);
2037: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2038: my @parts=split(/\//,$filename);
2039: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2040: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2041: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2042: return 'bad_request';
1.8 www 2043: }
2044: my $count;
2045: for ($count=5;$count<$#parts;$count++) {
2046: $path.="/$parts[$count]";
2047: if ((-e $path)!=1) {
2048: mkdir($path,0777);
2049: }
2050: }
2051: my $ua=new LWP::UserAgent;
2052: my $request=new HTTP::Request('GET',"$remoteurl");
2053: my $response=$ua->request($request,$transname);
2054: if ($response->is_error()) {
2055: unlink($transname);
2056: my $message=$response->status_line;
1.672 albertel 2057: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2058: ." LWP get: $message: $filename</font>");
1.607 raeburn 2059: return 'unavailable';
1.8 www 2060: } else {
1.16 www 2061: if ($remoteurl!~/\.meta$/) {
2062: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2063: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2064: if ($mresponse->is_error()) {
2065: unlink($filename.'.meta');
2066: &logthis(
1.672 albertel 2067: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2068: }
2069: }
1.8 www 2070: rename($transname,$filename);
1.607 raeburn 2071: return 'ok';
1.8 www 2072: }
1.290 www 2073: }
1.8 www 2074: }
1.330 www 2075: }
2076:
2077: # ------------------------------------------------ Get server side include body
2078: sub ssi_body {
1.381 albertel 2079: my ($filelink,%form)=@_;
1.606 matthew 2080: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2081: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2082: }
1.953 www 2083: my $output='';
2084: my $response;
1.980 raeburn 2085: if ($filelink=~/^https?\:/) {
1.954 raeburn 2086: ($output,$response)=&externalssi($filelink);
1.953 www 2087: } else {
1.1004 droeschl 2088: $filelink .= $filelink=~/\?/ ? '&' : '?';
2089: $filelink .= 'inhibitmenu=yes';
1.953 www 2090: ($output,$response)=&ssi($filelink,%form);
2091: }
1.778 albertel 2092: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2093: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2094: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2095: if (wantarray) {
2096: return ($output, $response);
2097: } else {
2098: return $output;
2099: }
1.8 www 2100: }
2101:
1.15 www 2102: # --------------------------------------------------------- Server Side Include
2103:
1.782 albertel 2104: sub absolute_url {
2105: my ($host_name) = @_;
2106: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2107: if ($host_name eq '') {
2108: $host_name = $ENV{'SERVER_NAME'};
2109: }
2110: return $protocol.$host_name;
2111: }
2112:
1.942 foxr 2113: #
2114: # Server side include.
2115: # Parameters:
2116: # fn Possibly encrypted resource name/id.
2117: # form Hash that describes how the rendering should be done
2118: # and other things.
1.944 foxr 2119: # Returns:
1.950 raeburn 2120: # Scalar context: The content of the response.
2121: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2122: #
1.15 www 2123: sub ssi {
2124:
1.944 foxr 2125: my ($fn,%form)=@_;
1.15 www 2126: my $ua=new LWP::UserAgent;
1.23 www 2127: my $request;
1.711 albertel 2128:
2129: $form{'no_update_last_known'}=1;
1.895 albertel 2130: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2131: if (%form) {
1.782 albertel 2132: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2133: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2134: } else {
1.782 albertel 2135: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2136: }
2137:
1.15 www 2138: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2139: my $response=$ua->request($request);
2140:
1.944 foxr 2141: if (wantarray) {
2142: return ($response->content, $response);
2143: } else {
2144: return $response->content;
1.942 foxr 2145: }
1.324 www 2146: }
2147:
2148: sub externalssi {
2149: my ($url)=@_;
2150: my $ua=new LWP::UserAgent;
2151: my $request=new HTTP::Request('GET',$url);
2152: my $response=$ua->request($request);
1.954 raeburn 2153: if (wantarray) {
2154: return ($response->content, $response);
2155: } else {
2156: return $response->content;
2157: }
1.15 www 2158: }
1.254 www 2159:
1.492 albertel 2160: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2161:
2162: sub allowuploaded {
2163: my ($srcurl,$url)=@_;
2164: $url=&clutter(&declutter($url));
2165: my $dir=$url;
2166: $dir=~s/\/[^\/]+$//;
2167: my %httpref=();
2168: my $httpurl=&hreflocation('',$url);
2169: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2170: &Apache::lonnet::appenv(\%httpref);
1.254 www 2171: }
1.477 raeburn 2172:
1.478 albertel 2173: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2174: # input: action, courseID, current domain, intended
1.637 raeburn 2175: # path to file, source of file, instruction to parse file for objects,
2176: # ref to hash for embedded objects,
2177: # ref to hash for codebase of java objects.
2178: #
1.485 raeburn 2179: # output: url to file (if action was uploaddoc),
2180: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2181: #
1.478 albertel 2182: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2183: # course.
1.477 raeburn 2184: #
1.478 albertel 2185: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2186: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2187: # course's home server.
1.477 raeburn 2188: #
1.478 albertel 2189: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2190: # be copied from $source (current location) to
2191: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2192: # and will then be copied to
2193: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2194: # course's home server.
1.485 raeburn 2195: #
1.481 raeburn 2196: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2197: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2198: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2199: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2200: # in course's home server.
1.637 raeburn 2201: #
1.477 raeburn 2202:
2203: sub process_coursefile {
1.638 albertel 2204: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2205: my $fetchresult;
1.638 albertel 2206: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2207: if ($action eq 'propagate') {
1.638 albertel 2208: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2209: $home);
1.481 raeburn 2210: } else {
1.477 raeburn 2211: my $fpath = '';
2212: my $fname = $file;
1.478 albertel 2213: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2214: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2215: my $filepath = &build_filepath($fpath);
1.481 raeburn 2216: if ($action eq 'copy') {
2217: if ($source eq '') {
2218: $fetchresult = 'no source file';
2219: return $fetchresult;
2220: } else {
2221: my $destination = $filepath.'/'.$fname;
2222: rename($source,$destination);
2223: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2224: $home);
1.481 raeburn 2225: }
2226: } elsif ($action eq 'uploaddoc') {
2227: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2228: print $fh $env{'form.'.$source};
1.481 raeburn 2229: close($fh);
1.637 raeburn 2230: if ($parser eq 'parse') {
1.1024 raeburn 2231: my $mm = new File::MMagic;
2232: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2233: if ($mime_type eq 'text/html') {
2234: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2235: unless ($parse_result eq 'ok') {
2236: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2237: }
1.637 raeburn 2238: }
2239: }
1.477 raeburn 2240: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2241: $home);
1.481 raeburn 2242: if ($fetchresult eq 'ok') {
2243: return '/uploaded/'.$fpath.'/'.$fname;
2244: } else {
2245: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2246: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2247: return '/adm/notfound.html';
2248: }
1.477 raeburn 2249: }
2250: }
1.485 raeburn 2251: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2252: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2253: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2254: }
2255: return $fetchresult;
2256: }
2257:
1.637 raeburn 2258: sub build_filepath {
2259: my ($fpath) = @_;
2260: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2261: unless ($fpath eq '') {
2262: my @parts=split('/',$fpath);
2263: foreach my $part (@parts) {
2264: $filepath.= '/'.$part;
2265: if ((-e $filepath)!=1) {
2266: mkdir($filepath,0777);
2267: }
2268: }
2269: }
2270: return $filepath;
2271: }
2272:
2273: sub store_edited_file {
1.638 albertel 2274: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2275: my $file = $primary_url;
2276: $file =~ s#^/uploaded/$docudom/$docuname/##;
2277: my $fpath = '';
2278: my $fname = $file;
2279: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2280: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2281: my $filepath = &build_filepath($fpath);
2282: open(my $fh,'>'.$filepath.'/'.$fname);
2283: print $fh $content;
2284: close($fh);
1.638 albertel 2285: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2286: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2287: $home);
1.637 raeburn 2288: if ($$fetchresult eq 'ok') {
2289: return '/uploaded/'.$fpath.'/'.$fname;
2290: } else {
1.638 albertel 2291: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2292: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2293: return '/adm/notfound.html';
2294: }
2295: }
2296:
1.531 albertel 2297: sub clean_filename {
1.831 albertel 2298: my ($fname,$args)=@_;
1.315 www 2299: # Replace Windows backslashes by forward slashes
1.257 www 2300: $fname=~s/\\/\//g;
1.831 albertel 2301: if (!$args->{'keep_path'}) {
2302: # Get rid of everything but the actual filename
2303: $fname=~s/^.*\/([^\/]+)$/$1/;
2304: }
1.315 www 2305: # Replace spaces by underscores
2306: $fname=~s/\s+/\_/g;
2307: # Replace all other weird characters by nothing
1.831 albertel 2308: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2309: # Replace all .\d. sequences with _\d. so they no longer look like version
2310: # numbers
2311: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2312: return $fname;
2313: }
1.1051 raeburn 2314: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2315: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2316: # image with the same aspect ratio as the original, but with dimensions which do
2317: # not exceed $resizewidth and $resizeheight.
2318:
1.984 neumanie 2319: sub resizeImage {
1.1051 raeburn 2320: my ($img_path,$resizewidth,$resizeheight) = @_;
2321: my $ima = Image::Magick->new;
2322: my $resized;
2323: if (-e $img_path) {
2324: $ima->Read($img_path);
2325: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2326: my $width = $ima->Get('width');
2327: my $height = $ima->Get('height');
2328: if ($width > $resizewidth) {
2329: my $factor = $width/$resizewidth;
2330: my $newheight = $height/$factor;
2331: $ima->Scale(width=>$resizewidth,height=>$newheight);
2332: $resized = 1;
2333: }
2334: }
2335: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2336: my $width = $ima->Get('width');
2337: my $height = $ima->Get('height');
2338: if ($height > $resizeheight) {
2339: my $factor = $height/$resizeheight;
2340: my $newwidth = $width/$factor;
2341: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2342: $resized = 1;
2343: }
2344: }
2345: if ($resized) {
2346: $ima->Write($img_path);
2347: }
2348: }
2349: return;
1.977 amueller 2350: }
2351:
1.608 albertel 2352: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2353: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2354: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2355: # $coursedoc - if true up to the current course
2356: # if false
2357: # $subdir - directory in userfile to store the file into
1.858 raeburn 2358: # $parser - instruction to parse file for objects ($parser = parse)
2359: # $allfiles - reference to hash for embedded objects
2360: # $codebase - reference to hash for codebase of java objects
2361: # $desuname - username for permanent storage of uploaded file
2362: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2363: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2364: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2365: # $resizewidth - width (pixels) to which to resize uploaded image
2366: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2367: #
1.686 albertel 2368: # output: url of file in userspace, or error: <message>
2369: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2370:
1.531 albertel 2371: sub userfileupload {
1.860 raeburn 2372: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2373: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2374: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2375: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2376: $fname=&clean_filename($fname);
1.315 www 2377: # See if there is anything left
1.257 www 2378: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2379: chop($env{'form.'.$formname});
1.523 raeburn 2380: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2381: my $now = time;
2382: my $filepath = 'tmp/helprequests/'.$now;
2383: my @parts=split(/\//,$filepath);
2384: my $fullpath = $perlvar{'lonDaemons'};
2385: for (my $i=0;$i<@parts;$i++) {
2386: $fullpath .= '/'.$parts[$i];
2387: if ((-e $fullpath)!=1) {
2388: mkdir($fullpath,0777);
2389: }
2390: }
2391: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2392: print $fh $env{'form.'.$formname};
1.523 raeburn 2393: close($fh);
1.741 raeburn 2394: return $fullpath.'/'.$fname;
2395: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2396: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2397: '_'.$env{'user.domain'}.'/pending';
2398: my @parts=split(/\//,$filepath);
2399: my $fullpath = $perlvar{'lonDaemons'};
2400: for (my $i=0;$i<@parts;$i++) {
2401: $fullpath .= '/'.$parts[$i];
2402: if ((-e $fullpath)!=1) {
2403: mkdir($fullpath,0777);
2404: }
2405: }
2406: open(my $fh,'>'.$fullpath.'/'.$fname);
2407: print $fh $env{'form.'.$formname};
2408: close($fh);
2409: return $fullpath.'/'.$fname;
1.523 raeburn 2410: }
1.995 raeburn 2411: if ($subdir eq 'scantron') {
2412: $fname = 'scantron_orig_'.$fname;
2413: } else {
1.258 www 2414: # Create the directory if not present
1.995 raeburn 2415: $fname="$subdir/$fname";
2416: }
1.259 www 2417: if ($coursedoc) {
1.638 albertel 2418: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2419: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2420: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2421: return &finishuserfileupload($docuname,$docudom,
2422: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2423: $codebase,$thumbwidth,$thumbheight,
2424: $resizewidth,$resizeheight);
1.481 raeburn 2425: } else {
1.620 albertel 2426: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2427: return &process_coursefile('uploaddoc',$docuname,$docudom,
2428: $fname,$formname,$parser,
2429: $allfiles,$codebase);
1.481 raeburn 2430: }
1.719 banghart 2431: } elsif (defined($destuname)) {
2432: my $docuname=$destuname;
2433: my $docudom=$destudom;
1.860 raeburn 2434: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2435: $parser,$allfiles,$codebase,
1.1051 raeburn 2436: $thumbwidth,$thumbheight,
2437: $resizewidth,$resizeheight);
1.719 banghart 2438:
1.259 www 2439: } else {
1.638 albertel 2440: my $docuname=$env{'user.name'};
2441: my $docudom=$env{'user.domain'};
1.714 raeburn 2442: if (exists($env{'form.group'})) {
2443: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2444: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2445: }
1.860 raeburn 2446: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2447: $parser,$allfiles,$codebase,
1.1051 raeburn 2448: $thumbwidth,$thumbheight,
2449: $resizewidth,$resizeheight);
1.259 www 2450: }
1.271 www 2451: }
2452:
2453: sub finishuserfileupload {
1.860 raeburn 2454: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2455: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2456: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2457: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2458:
1.860 raeburn 2459: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2460: $file=$fname;
2461: if ($fname=~m|/|) {
2462: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2463: $path.=$fnamepath.'/';
2464: }
1.259 www 2465: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2466: my $count;
2467: for ($count=4;$count<=$#parts;$count++) {
2468: $filepath.="/$parts[$count]";
2469: if ((-e $filepath)!=1) {
2470: mkdir($filepath,0777);
2471: }
2472: }
1.984 neumanie 2473:
1.258 www 2474: # Save the file
2475: {
1.701 albertel 2476: if (!open(FH,'>'.$filepath.'/'.$file)) {
2477: &logthis('Failed to create '.$filepath.'/'.$file);
2478: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2479: return '/adm/notfound.html';
2480: }
2481: if (!print FH ($env{'form.'.$formname})) {
2482: &logthis('Failed to write to '.$filepath.'/'.$file);
2483: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2484: return '/adm/notfound.html';
2485: }
1.570 albertel 2486: close(FH);
1.1051 raeburn 2487: if ($resizewidth && $resizeheight) {
2488: my $mm = new File::MMagic;
2489: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2490: if ($mime_type =~ m{^image/}) {
2491: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2492: }
1.977 amueller 2493: }
1.258 www 2494: }
1.637 raeburn 2495: if ($parser eq 'parse') {
1.1024 raeburn 2496: my $mm = new File::MMagic;
2497: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2498: if ($mime_type eq 'text/html') {
2499: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2500: $allfiles,$codebase);
2501: unless ($parse_result eq 'ok') {
2502: &logthis('Failed to parse '.$filepath.$file.
2503: ' for embedded media: '.$parse_result);
2504: }
1.637 raeburn 2505: }
2506: }
1.860 raeburn 2507: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2508: my $input = $filepath.'/'.$file;
2509: my $output = $filepath.'/'.'tn-'.$file;
2510: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2511: system("convert -sample $thumbsize $input $output");
2512: if (-e $filepath.'/'.'tn-'.$file) {
2513: $fetchthumb = 1;
2514: }
2515: }
1.858 raeburn 2516:
1.259 www 2517: # Notify homeserver to grep it
2518: #
1.984 neumanie 2519: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2520: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2521: if ($fetchresult eq 'ok') {
1.860 raeburn 2522: if ($fetchthumb) {
2523: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2524: if ($thumbresult ne 'ok') {
2525: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2526: $docuhome.': '.$thumbresult);
2527: }
2528: }
1.259 www 2529: #
1.258 www 2530: # Return the URL to it
1.494 albertel 2531: return '/uploaded/'.$path.$file;
1.263 www 2532: } else {
1.494 albertel 2533: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2534: ': '.$fetchresult);
1.263 www 2535: return '/adm/notfound.html';
1.858 raeburn 2536: }
1.493 albertel 2537: }
2538:
1.637 raeburn 2539: sub extract_embedded_items {
1.961 raeburn 2540: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2541: my @state = ();
2542: my %javafiles = (
2543: codebase => '',
2544: code => '',
2545: archive => ''
2546: );
2547: my %mediafiles = (
2548: src => '',
2549: movie => '',
2550: );
1.648 raeburn 2551: my $p;
2552: if ($content) {
2553: $p = HTML::LCParser->new($content);
2554: } else {
1.961 raeburn 2555: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2556: }
1.641 albertel 2557: while (my $t=$p->get_token()) {
1.640 albertel 2558: if ($t->[0] eq 'S') {
2559: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2560: push(@state, $tagname);
1.648 raeburn 2561: if (lc($tagname) eq 'allow') {
2562: &add_filetype($allfiles,$attr->{'src'},'src');
2563: }
1.640 albertel 2564: if (lc($tagname) eq 'img') {
2565: &add_filetype($allfiles,$attr->{'src'},'src');
2566: }
1.886 albertel 2567: if (lc($tagname) eq 'a') {
2568: &add_filetype($allfiles,$attr->{'href'},'href');
2569: }
1.645 raeburn 2570: if (lc($tagname) eq 'script') {
2571: if ($attr->{'archive'} =~ /\.jar$/i) {
2572: &add_filetype($allfiles,$attr->{'archive'},'archive');
2573: } else {
2574: &add_filetype($allfiles,$attr->{'src'},'src');
2575: }
2576: }
2577: if (lc($tagname) eq 'link') {
2578: if (lc($attr->{'rel'}) eq 'stylesheet') {
2579: &add_filetype($allfiles,$attr->{'href'},'href');
2580: }
2581: }
1.640 albertel 2582: if (lc($tagname) eq 'object' ||
2583: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2584: foreach my $item (keys(%javafiles)) {
2585: $javafiles{$item} = '';
2586: }
2587: }
2588: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2589: my $name = lc($attr->{'name'});
2590: foreach my $item (keys(%javafiles)) {
2591: if ($name eq $item) {
2592: $javafiles{$item} = $attr->{'value'};
2593: last;
2594: }
2595: }
2596: foreach my $item (keys(%mediafiles)) {
2597: if ($name eq $item) {
2598: &add_filetype($allfiles, $attr->{'value'}, 'value');
2599: last;
2600: }
2601: }
2602: }
2603: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2604: foreach my $item (keys(%javafiles)) {
2605: if ($attr->{$item}) {
2606: $javafiles{$item} = $attr->{$item};
2607: last;
2608: }
2609: }
2610: foreach my $item (keys(%mediafiles)) {
2611: if ($attr->{$item}) {
2612: &add_filetype($allfiles,$attr->{$item},$item);
2613: last;
2614: }
2615: }
2616: }
2617: } elsif ($t->[0] eq 'E') {
2618: my ($tagname) = ($t->[1]);
2619: if ($javafiles{'codebase'} ne '') {
2620: $javafiles{'codebase'} .= '/';
2621: }
2622: if (lc($tagname) eq 'applet' ||
2623: lc($tagname) eq 'object' ||
2624: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2625: ) {
2626: foreach my $item (keys(%javafiles)) {
2627: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2628: my $file=$javafiles{'codebase'}.$javafiles{$item};
2629: &add_filetype($allfiles,$file,$item);
2630: }
2631: }
2632: }
2633: pop @state;
2634: }
2635: }
1.637 raeburn 2636: return 'ok';
2637: }
2638:
1.639 albertel 2639: sub add_filetype {
2640: my ($allfiles,$file,$type)=@_;
2641: if (exists($allfiles->{$file})) {
2642: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2643: push(@{$allfiles->{$file}}, &escape($type));
2644: }
2645: } else {
2646: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2647: }
2648: }
2649:
1.493 albertel 2650: sub removeuploadedurl {
1.984 neumanie 2651: my ($url)=@_;
2652: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2653: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2654: }
2655:
2656: sub removeuserfile {
2657: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2658: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2659: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2660: if ($result eq 'ok') {
1.798 raeburn 2661: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2662: my $metafile = $fname.'.meta';
2663: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2664: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2665: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2666: my $sqlresult =
1.823 albertel 2667: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2668: 'portfolio_metadata',$group,
2669: 'delete');
1.798 raeburn 2670: }
2671: }
2672: return $result;
1.257 www 2673: }
1.15 www 2674:
1.530 albertel 2675: sub mkdiruserfile {
2676: my ($docuname,$docudom,$dir)=@_;
2677: my $home=&homeserver($docuname,$docudom);
2678: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2679: }
2680:
1.531 albertel 2681: sub renameuserfile {
2682: my ($docuname,$docudom,$old,$new)=@_;
2683: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2684: my $result = &reply("renameuserfile:$docudom:$docuname:".
2685: &escape("$old").':'.&escape("$new"),$home);
2686: if ($result eq 'ok') {
2687: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2688: my $oldmeta = $old.'.meta';
2689: my $newmeta = $new.'.meta';
2690: my $metaresult =
2691: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2692: my $url = "/uploaded/$docudom/$docuname/$old";
2693: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2694: my $sqlresult =
1.823 albertel 2695: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2696: 'portfolio_metadata',$group,
2697: 'delete');
1.798 raeburn 2698: }
2699: }
2700: return $result;
1.531 albertel 2701: }
2702:
1.14 www 2703: # ------------------------------------------------------------------------- Log
2704:
2705: sub log {
2706: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2707: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2708: }
2709:
2710: # ------------------------------------------------------------------ Course Log
1.352 www 2711: #
2712: # This routine flushes several buffers of non-mission-critical nature
2713: #
1.157 www 2714:
2715: sub flushcourselogs {
1.352 www 2716: &logthis('Flushing log buffers');
2717: #
2718: # course logs
2719: # This is a log of all transactions in a course, which can be used
2720: # for data mining purposes
2721: #
2722: # It also collects the courseid database, which lists last transaction
2723: # times and course titles for all courseids
2724: #
2725: my %courseidbuffer=();
1.921 raeburn 2726: foreach my $crsid (keys(%courselogs)) {
1.352 www 2727: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2728: &escape($courselogs{$crsid}),
2729: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2730: delete $courselogs{$crsid};
2731: } else {
2732: &logthis('Failed to flush log buffer for '.$crsid);
2733: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2734: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2735: " exceeded maximum size, deleting.</font>");
2736: delete $courselogs{$crsid};
2737: }
1.352 www 2738: }
1.920 raeburn 2739: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2740: 'description' => $coursedescrbuf{$crsid},
2741: 'inst_code' => $courseinstcodebuf{$crsid},
2742: 'type' => $coursetypebuf{$crsid},
2743: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2744: };
1.191 harris41 2745: }
1.352 www 2746: #
2747: # Write course id database (reverse lookup) to homeserver of courses
2748: # Is used in pickcourse
2749: #
1.840 albertel 2750: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2751: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2752: $courseidbuffer{$crs_home},
2753: $crs_home,'timeonly');
1.352 www 2754: }
2755: #
2756: # File accesses
2757: # Writes to the dynamic metadata of resources to get hit counts, etc.
2758: #
1.449 matthew 2759: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2760: if ($entry =~ /___count$/) {
2761: my ($dom,$name);
1.807 albertel 2762: ($dom,$name,undef)=
1.811 albertel 2763: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2764: if (! defined($dom) || $dom eq '' ||
2765: ! defined($name) || $name eq '') {
1.620 albertel 2766: my $cid = $env{'request.course.id'};
2767: $dom = $env{'request.'.$cid.'.domain'};
2768: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2769: }
1.450 matthew 2770: my $value = $accesshash{$entry};
2771: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2772: my %temphash=($url => $value);
1.449 matthew 2773: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2774: if ($result eq 'ok') {
2775: delete $accesshash{$entry};
2776: } elsif ($result eq 'unknown_cmd') {
2777: # Target server has old code running on it.
1.450 matthew 2778: my %temphash=($entry => $value);
1.449 matthew 2779: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2780: delete $accesshash{$entry};
2781: }
2782: }
2783: } else {
1.811 albertel 2784: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2785: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2786: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2787: delete $accesshash{$entry};
2788: }
1.185 www 2789: }
1.191 harris41 2790: }
1.352 www 2791: #
2792: # Roles
2793: # Reverse lookup of user roles for course faculty/staff and co-authorship
2794: #
1.800 albertel 2795: foreach my $entry (keys(%userrolehash)) {
1.351 www 2796: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2797: split(/\:/,$entry);
2798: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2799: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2800: $rudom,$runame) eq 'ok') {
2801: delete $userrolehash{$entry};
2802: }
2803: }
1.662 raeburn 2804: #
2805: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2806: #
2807: my %domrolebuffer = ();
1.1000 raeburn 2808: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2809: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2810: if ($domrolebuffer{$rudom}) {
2811: $domrolebuffer{$rudom}.='&'.&escape($entry).
2812: '='.&escape($domainrolehash{$entry});
2813: } else {
2814: $domrolebuffer{$rudom}.=&escape($entry).
2815: '='.&escape($domainrolehash{$entry});
2816: }
2817: delete $domainrolehash{$entry};
2818: }
2819: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2820: my %servers = &get_servers($dom,'library');
2821: foreach my $tryserver (keys(%servers)) {
2822: unless (&reply('domroleput:'.$dom.':'.
2823: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2824: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2825: }
1.662 raeburn 2826: }
2827: }
1.186 www 2828: $dumpcount++;
1.157 www 2829: }
2830:
2831: sub courselog {
2832: my $what=shift;
1.158 www 2833: $what=time.':'.$what;
1.620 albertel 2834: unless ($env{'request.course.id'}) { return ''; }
2835: $coursedombuf{$env{'request.course.id'}}=
2836: $env{'course.'.$env{'request.course.id'}.'.domain'};
2837: $coursenumbuf{$env{'request.course.id'}}=
2838: $env{'course.'.$env{'request.course.id'}.'.num'};
2839: $coursehombuf{$env{'request.course.id'}}=
2840: $env{'course.'.$env{'request.course.id'}.'.home'};
2841: $coursedescrbuf{$env{'request.course.id'}}=
2842: $env{'course.'.$env{'request.course.id'}.'.description'};
2843: $courseinstcodebuf{$env{'request.course.id'}}=
2844: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2845: $courseownerbuf{$env{'request.course.id'}}=
2846: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2847: $coursetypebuf{$env{'request.course.id'}}=
2848: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2849: if (defined $courselogs{$env{'request.course.id'}}) {
2850: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2851: } else {
1.620 albertel 2852: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2853: }
1.620 albertel 2854: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2855: &flushcourselogs();
2856: }
1.158 www 2857: }
2858:
2859: sub courseacclog {
2860: my $fnsymb=shift;
1.620 albertel 2861: unless ($env{'request.course.id'}) { return ''; }
2862: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2863: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2864: $what.=':POST';
1.583 matthew 2865: # FIXME: Probably ought to escape things....
1.800 albertel 2866: foreach my $key (keys(%env)) {
2867: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2868: my $formitem = $1;
2869: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2870: $what.=':'.$formitem.'='.$env{$key};
2871: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2872: $what.=':'.$formitem.'='.$env{$key};
2873: }
1.158 www 2874: }
1.191 harris41 2875: }
1.583 matthew 2876: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2877: # FIXME: We should not be depending on a form parameter that someone
2878: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2879: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2880: $what.= ':POST';
2881: # FIXME: Probably ought to escape things....
2882: foreach my $element ('courseexp','crsfulltext','crsrelated',
2883: 'crsdiscuss') {
1.620 albertel 2884: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2885: }
2886: }
1.158 www 2887: }
2888: &courselog($what);
1.149 www 2889: }
2890:
1.185 www 2891: sub countacc {
2892: my $url=&declutter(shift);
1.458 matthew 2893: return if (! defined($url) || $url eq '');
1.620 albertel 2894: unless ($env{'request.course.id'}) { return ''; }
2895: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2896: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2897: $accesshash{$key}++;
1.185 www 2898: }
1.349 www 2899:
1.361 www 2900: sub linklog {
2901: my ($from,$to)=@_;
2902: $from=&declutter($from);
2903: $to=&declutter($to);
2904: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2905: $accesshash{$to.'___'.$from.'___goto'}=1;
2906: }
2907:
1.349 www 2908: sub userrolelog {
2909: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2910: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2911: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2912: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2913: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2914: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2915: $userrolehash
2916: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2917: =$tend.':'.$tstart;
1.662 raeburn 2918: }
1.898 albertel 2919: if (($env{'request.role'} =~ /dc\./) &&
2920: (($trole=~/^au/) || ($trole=~/^in/) ||
2921: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2922: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2923: ($trole=~/^co/))) {
1.898 albertel 2924: $userrolehash
2925: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2926: =$tend.':'.$tstart;
2927: }
1.662 raeburn 2928: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2929: ($trole=~/^li/) || ($trole=~/^li/) ||
2930: ($trole=~/^au/) || ($trole=~/^dg/) ||
2931: ($trole=~/^sc/)) {
2932: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2933: $domainrolehash
2934: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2935: = $tend.':'.$tstart;
2936: }
1.351 www 2937: }
2938:
1.957 raeburn 2939: sub courserolelog {
2940: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2941: if (($trole eq 'cc') || ($trole eq 'in') ||
2942: ($trole eq 'ep') || ($trole eq 'ad') ||
2943: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2944: ($trole=~/^cr/) || ($trole eq 'gr') ||
2945: ($trole eq 'co')) {
1.957 raeburn 2946: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2947: my $cdom = $1;
2948: my $cnum = $2;
2949: my $sec = $3;
2950: my $namespace = 'rolelog';
2951: my %storehash = (
2952: role => $trole,
2953: start => $tstart,
2954: end => $tend,
2955: selfenroll => $selfenroll,
2956: context => $context,
2957: );
2958: if ($trole eq 'gr') {
2959: $namespace = 'groupslog';
2960: $storehash{'group'} = $sec;
2961: } else {
2962: $storehash{'section'} = $sec;
2963: }
2964: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2965: if (($trole ne 'st') || ($sec ne '')) {
2966: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2967: }
1.957 raeburn 2968: }
2969: }
2970: return;
2971: }
2972:
1.351 www 2973: sub get_course_adv_roles {
1.948 raeburn 2974: my ($cid,$codes) = @_;
1.620 albertel 2975: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2976: my %coursehash=&coursedescription($cid);
1.988 raeburn 2977: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2978: my %nothide=();
1.800 albertel 2979: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2980: if ($user !~ /:/) {
2981: $nothide{join(':',split(/[\@]/,$user))}=1;
2982: } else {
2983: $nothide{$user}=1;
2984: }
1.470 www 2985: }
1.351 www 2986: my %returnhash=();
2987: my %dumphash=
2988: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2989: my $now=time;
1.997 raeburn 2990: my %privileged;
1.1000 raeburn 2991: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2992: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2993: if (($tstart) && ($tstart<0)) { next; }
2994: if (($tend) && ($tend<$now)) { next; }
2995: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2996: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2997: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2998: unless (ref($privileged{$domain}) eq 'HASH') {
2999: my %dompersonnel =
1.998 raeburn 3000: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3001: $privileged{$domain} = {};
3002: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3003: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3004: foreach my $user (keys(%{$dompersonnel{$server}})) {
3005: my ($trole,$uname,$udom) = split(/:/,$user);
3006: $privileged{$udom}{$uname} = 1;
3007: }
3008: }
3009: }
3010: }
3011: if ((exists($privileged{$domain}{$username})) &&
3012: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3013: if ($role eq 'cr') { next; }
1.948 raeburn 3014: if ($codes) {
3015: if ($section) { $role .= ':'.$section; }
3016: if ($returnhash{$role}) {
3017: $returnhash{$role}.=','.$username.':'.$domain;
3018: } else {
3019: $returnhash{$role}=$username.':'.$domain;
3020: }
1.351 www 3021: } else {
1.988 raeburn 3022: my $key=&plaintext($role,$crstype);
1.973 bisitz 3023: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3024: if ($returnhash{$key}) {
3025: $returnhash{$key}.=','.$username.':'.$domain;
3026: } else {
3027: $returnhash{$key}=$username.':'.$domain;
3028: }
1.351 www 3029: }
1.948 raeburn 3030: }
1.400 www 3031: return %returnhash;
3032: }
3033:
3034: sub get_my_roles {
1.937 raeburn 3035: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3036: unless (defined($uname)) { $uname=$env{'user.name'}; }
3037: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3038: my (%dumphash,%nothide);
1.1086 raeburn 3039: if ($context eq 'userroles') {
3040: my $extra = &freeze_escape({'skipcheck' => 1});
3041: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3042: } else {
3043: %dumphash=
1.400 www 3044: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3045: if ($hidepriv) {
3046: my %coursehash=&coursedescription($udom.'_'.$uname);
3047: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3048: if ($user !~ /:/) {
3049: $nothide{join(':',split(/[\@]/,$user))} = 1;
3050: } else {
3051: $nothide{$user} = 1;
3052: }
3053: }
3054: }
1.858 raeburn 3055: }
1.400 www 3056: my %returnhash=();
3057: my $now=time;
1.999 raeburn 3058: my %privileged;
1.800 albertel 3059: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3060: my ($role,$tend,$tstart);
3061: if ($context eq 'userroles') {
3062: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3063: } else {
3064: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3065: }
1.400 www 3066: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3067: my $status = 'active';
1.939 raeburn 3068: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3069: $status = 'previous';
3070: }
3071: if (($tstart) && ($now<$tstart)) {
3072: $status = 'future';
3073: }
3074: if (ref($types) eq 'ARRAY') {
3075: if (!grep(/^\Q$status\E$/,@{$types})) {
3076: next;
3077: }
3078: } else {
3079: if ($status ne 'active') {
3080: next;
3081: }
3082: }
1.867 raeburn 3083: my ($rolecode,$username,$domain,$section,$area);
3084: if ($context eq 'userroles') {
3085: ($area,$rolecode) = split(/_/,$entry);
3086: (undef,$domain,$username,$section) = split(/\//,$area);
3087: } else {
3088: ($role,$username,$domain,$section) = split(/\:/,$entry);
3089: }
1.832 raeburn 3090: if (ref($roledoms) eq 'ARRAY') {
3091: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3092: next;
3093: }
3094: }
3095: if (ref($roles) eq 'ARRAY') {
3096: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3097: if ($role =~ /^cr\//) {
3098: if (!grep(/^cr$/,@{$roles})) {
3099: next;
3100: }
3101: } else {
3102: next;
3103: }
1.832 raeburn 3104: }
1.867 raeburn 3105: }
1.937 raeburn 3106: if ($hidepriv) {
1.999 raeburn 3107: if ($context eq 'userroles') {
3108: if ((&privileged($username,$domain)) &&
3109: (!$nothide{$username.':'.$domain})) {
3110: next;
3111: }
3112: } else {
3113: unless (ref($privileged{$domain}) eq 'HASH') {
3114: my %dompersonnel =
3115: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3116: $privileged{$domain} = {};
3117: if (keys(%dompersonnel)) {
3118: foreach my $server (keys(%dompersonnel)) {
3119: if (ref($dompersonnel{$server}) eq 'HASH') {
3120: foreach my $user (keys(%{$dompersonnel{$server}})) {
3121: my ($trole,$uname,$udom) = split(/:/,$user);
3122: $privileged{$udom}{$uname} = $trole;
3123: }
3124: }
3125: }
3126: }
3127: }
3128: if (exists($privileged{$domain}{$username})) {
3129: if (!$nothide{$username.':'.$domain}) {
3130: next;
3131: }
3132: }
1.937 raeburn 3133: }
3134: }
1.933 raeburn 3135: if ($withsec) {
3136: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3137: $tstart.':'.$tend;
3138: } else {
3139: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3140: }
1.832 raeburn 3141: }
1.373 www 3142: return %returnhash;
1.399 www 3143: }
3144:
3145: # ----------------------------------------------------- Frontpage Announcements
3146: #
3147: #
3148:
3149: sub postannounce {
3150: my ($server,$text)=@_;
1.844 albertel 3151: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3152: unless ($text=~/\w/) { $text=''; }
3153: return &reply('setannounce:'.&escape($text),$server);
3154: }
3155:
3156: sub getannounce {
1.448 albertel 3157:
3158: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3159: my $announcement='';
1.800 albertel 3160: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3161: close($fh);
1.399 www 3162: if ($announcement=~/\w/) {
3163: return
3164: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3165: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3166: } else {
3167: return '';
3168: }
3169: } else {
3170: return '';
3171: }
1.351 www 3172: }
1.353 www 3173:
3174: # ---------------------------------------------------------- Course ID routines
3175: # Deal with domain's nohist_courseid.db files
3176: #
3177:
3178: sub courseidput {
1.921 raeburn 3179: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3180: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3181: my $outcome;
3182: if ($caller eq 'timeonly') {
3183: my $cids = '';
3184: foreach my $item (keys(%$storehash)) {
3185: $cids.=&escape($item).'&';
3186: }
3187: $cids=~s/\&$//;
3188: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3189: $coursehome);
3190: } else {
3191: my $items = '';
3192: foreach my $item (keys(%$storehash)) {
3193: $items.= &escape($item).'='.
3194: &freeze_escape($$storehash{$item}).'&';
3195: }
3196: $items=~s/\&$//;
3197: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3198: $coursehome);
1.918 raeburn 3199: }
3200: if ($outcome eq 'unknown_cmd') {
3201: my $what;
3202: foreach my $cid (keys(%$storehash)) {
3203: $what .= &escape($cid).'=';
1.921 raeburn 3204: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3205: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3206: }
3207: $what =~ s/\:$/&/;
3208: }
3209: $what =~ s/\&$//;
3210: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3211: } else {
3212: return $outcome;
3213: }
1.353 www 3214: }
3215:
3216: sub courseiddump {
1.921 raeburn 3217: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3218: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3219: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3220: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3221: my $as_hash = 1;
3222: my %returnhash;
3223: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3224: my %libserv = &all_library();
3225: foreach my $tryserver (keys(%libserv)) {
3226: if ( ( $hostidflag == 1
3227: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3228: || (!defined($hostidflag)) ) {
3229:
1.918 raeburn 3230: if (($domfilter eq '') ||
3231: (&host_domain($tryserver) eq $domfilter)) {
3232: my $rep =
3233: &reply('courseiddump:'.&host_domain($tryserver).':'.
3234: $sincefilter.':'.&escape($descfilter).':'.
3235: &escape($instcodefilter).':'.&escape($ownerfilter).
3236: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3237: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3238: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3239: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3240: &escape($cc_clone).':'.$cloneonly.':'.
3241: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3242: &escape($creationcontext).':'.$domcloner,
3243: $tryserver);
1.918 raeburn 3244: my @pairs=split(/\&/,$rep);
3245: foreach my $item (@pairs) {
3246: my ($key,$value)=split(/\=/,$item,2);
3247: $key = &unescape($key);
3248: next if ($key =~ /^error: 2 /);
3249: my $result = &thaw_unescape($value);
3250: if (ref($result) eq 'HASH') {
3251: $returnhash{$key}=$result;
3252: } else {
1.921 raeburn 3253: my @responses = split(/:/,$value);
3254: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3255: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3256: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3257: }
1.1008 raeburn 3258: }
1.353 www 3259: }
3260: }
3261: }
3262: }
3263: return %returnhash;
3264: }
3265:
1.1055 raeburn 3266: sub courselastaccess {
3267: my ($cdom,$cnum,$hostidref) = @_;
3268: my %returnhash;
3269: if ($cdom && $cnum) {
3270: my $chome = &homeserver($cnum,$cdom);
3271: if ($chome ne 'no_host') {
3272: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3273: &extract_lastaccess(\%returnhash,$rep);
3274: }
3275: } else {
3276: if (!$cdom) { $cdom=''; }
3277: my %libserv = &all_library();
3278: foreach my $tryserver (keys(%libserv)) {
3279: if (ref($hostidref) eq 'ARRAY') {
3280: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3281: }
3282: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3283: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3284: &extract_lastaccess(\%returnhash,$rep);
3285: }
3286: }
3287: }
3288: return %returnhash;
3289: }
3290:
3291: sub extract_lastaccess {
3292: my ($returnhash,$rep) = @_;
3293: if (ref($returnhash) eq 'HASH') {
3294: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3295: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3296: $rep eq '') {
3297: my @pairs=split(/\&/,$rep);
3298: foreach my $item (@pairs) {
3299: my ($key,$value)=split(/\=/,$item,2);
3300: $key = &unescape($key);
3301: next if ($key =~ /^error: 2 /);
3302: $returnhash->{$key} = &thaw_unescape($value);
3303: }
3304: }
3305: }
3306: return;
3307: }
3308:
1.658 raeburn 3309: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3310:
3311: sub dcmailput {
1.685 raeburn 3312: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3313: my $status = &Apache::lonnet::critical(
1.740 www 3314: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3315: &escape($message),$server);
1.662 raeburn 3316: return $status;
3317: }
3318:
1.658 raeburn 3319: sub dcmaildump {
3320: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3321: my %returnhash=();
1.846 albertel 3322:
3323: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3324: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3325: &escape($enddate).':';
3326: my @esc_senders=map { &escape($_)} @$senders;
3327: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3328: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3329: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3330: if (($key) && ($value)) {
3331: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3332: }
3333: }
3334: }
3335: return %returnhash;
3336: }
1.662 raeburn 3337: # ---------------------------------------------------------- Domain roles
3338:
3339: sub get_domain_roles {
3340: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3341: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3342: $startdate = '.';
3343: }
1.1018 raeburn 3344: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3345: $enddate = '.';
3346: }
1.922 raeburn 3347: my $rolelist;
3348: if (ref($roles) eq 'ARRAY') {
3349: $rolelist = join(':',@{$roles});
3350: }
1.662 raeburn 3351: my %personnel = ();
1.841 albertel 3352:
3353: my %servers = &get_servers($dom,'library');
3354: foreach my $tryserver (keys(%servers)) {
3355: %{$personnel{$tryserver}}=();
3356: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3357: &escape($startdate).':'.
3358: &escape($enddate).':'.
3359: &escape($rolelist), $tryserver))) {
3360: my ($key,$value) = split(/\=/,$line,2);
3361: if (($key) && ($value)) {
3362: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3363: }
3364: }
1.662 raeburn 3365: }
3366: return %personnel;
3367: }
1.658 raeburn 3368:
1.1057 www 3369: # ----------------------------------------------------------- Interval timing
1.149 www 3370:
1.504 albertel 3371: sub get_first_access {
3372: my ($type,$argsymb)=@_;
1.790 albertel 3373: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3374: if ($argsymb) { $symb=$argsymb; }
3375: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3376: if ($type eq 'course') {
3377: $res='course';
3378: } elsif ($type eq 'map') {
1.588 albertel 3379: $res=&symbread($map);
3380: } else {
3381: $res=$symb;
3382: }
3383: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3384: return $times{"$courseid\0$res"};
1.504 albertel 3385: }
3386:
3387: sub set_first_access {
3388: my ($type)=@_;
1.790 albertel 3389: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3390: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3391: if ($type eq 'course') {
3392: $res='course';
3393: } elsif ($type eq 'map') {
1.588 albertel 3394: $res=&symbread($map);
3395: } else {
3396: $res=$symb;
3397: }
3398: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3399: if (!$firstaccess) {
1.588 albertel 3400: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3401: }
3402: return 'already_set';
1.504 albertel 3403: }
3404:
1.110 www 3405: # --------------------------------------------- Set Expire Date for Spreadsheet
3406:
3407: sub expirespread {
3408: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3409: my $cid=$env{'request.course.id'};
1.110 www 3410: if ($cid) {
3411: my $now=time;
3412: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3413: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3414: $env{'course.'.$cid.'.num'}.
1.110 www 3415: ':nohist_expirationdates:'.
3416: &escape($key).'='.$now,
1.620 albertel 3417: $env{'course.'.$cid.'.home'})
1.110 www 3418: }
3419: return 'ok';
1.14 www 3420: }
3421:
1.109 www 3422: # ----------------------------------------------------- Devalidate Spreadsheets
3423:
3424: sub devalidate {
1.325 www 3425: my ($symb,$uname,$udom)=@_;
1.620 albertel 3426: my $cid=$env{'request.course.id'};
1.109 www 3427: if ($cid) {
1.391 matthew 3428: # delete the stored spreadsheets for
3429: # - the student level sheet of this user in course's homespace
3430: # - the assessment level sheet for this resource
3431: # for this user in user's homespace
1.553 albertel 3432: # - current conditional state info
1.325 www 3433: my $key=$uname.':'.$udom.':';
1.109 www 3434: my $status=
1.299 matthew 3435: &del('nohist_calculatedsheets',
1.391 matthew 3436: [$key.'studentcalc:'],
1.620 albertel 3437: $env{'course.'.$cid.'.domain'},
3438: $env{'course.'.$cid.'.num'})
1.133 albertel 3439: .' '.
3440: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3441: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3442: unless ($status eq 'ok ok') {
3443: &logthis('Could not devalidate spreadsheet '.
1.325 www 3444: $uname.' at '.$udom.' for '.
1.109 www 3445: $symb.': '.$status);
1.133 albertel 3446: }
1.553 albertel 3447: &delenv('user.state.'.$cid);
1.109 www 3448: }
3449: }
3450:
1.265 albertel 3451: sub get_scalar {
3452: my ($string,$end) = @_;
3453: my $value;
3454: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3455: $value = $1;
3456: } elsif ($$string =~ s/^([^&]*?)&//) {
3457: $value = $1;
3458: }
3459: return &unescape($value);
3460: }
3461:
3462: sub array2str {
3463: my (@array) = @_;
3464: my $result=&arrayref2str(\@array);
3465: $result=~s/^__ARRAY_REF__//;
3466: $result=~s/__END_ARRAY_REF__$//;
3467: return $result;
3468: }
3469:
1.204 albertel 3470: sub arrayref2str {
3471: my ($arrayref) = @_;
1.265 albertel 3472: my $result='__ARRAY_REF__';
1.204 albertel 3473: foreach my $elem (@$arrayref) {
1.265 albertel 3474: if(ref($elem) eq 'ARRAY') {
3475: $result.=&arrayref2str($elem).'&';
3476: } elsif(ref($elem) eq 'HASH') {
3477: $result.=&hashref2str($elem).'&';
3478: } elsif(ref($elem)) {
3479: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3480: } else {
3481: $result.=&escape($elem).'&';
3482: }
3483: }
3484: $result=~s/\&$//;
1.265 albertel 3485: $result .= '__END_ARRAY_REF__';
1.204 albertel 3486: return $result;
3487: }
3488:
1.168 albertel 3489: sub hash2str {
1.204 albertel 3490: my (%hash) = @_;
3491: my $result=&hashref2str(\%hash);
1.265 albertel 3492: $result=~s/^__HASH_REF__//;
3493: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3494: return $result;
3495: }
3496:
3497: sub hashref2str {
3498: my ($hashref)=@_;
1.265 albertel 3499: my $result='__HASH_REF__';
1.800 albertel 3500: foreach my $key (sort(keys(%$hashref))) {
3501: if (ref($key) eq 'ARRAY') {
3502: $result.=&arrayref2str($key).'=';
3503: } elsif (ref($key) eq 'HASH') {
3504: $result.=&hashref2str($key).'=';
3505: } elsif (ref($key)) {
1.265 albertel 3506: $result.='=';
1.800 albertel 3507: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3508: } else {
1.800 albertel 3509: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3510: }
3511:
1.800 albertel 3512: if(ref($hashref->{$key}) eq 'ARRAY') {
3513: $result.=&arrayref2str($hashref->{$key}).'&';
3514: } elsif(ref($hashref->{$key}) eq 'HASH') {
3515: $result.=&hashref2str($hashref->{$key}).'&';
3516: } elsif(ref($hashref->{$key})) {
1.265 albertel 3517: $result.='&';
1.800 albertel 3518: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3519: } else {
1.800 albertel 3520: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3521: }
3522: }
1.168 albertel 3523: $result=~s/\&$//;
1.265 albertel 3524: $result .= '__END_HASH_REF__';
1.168 albertel 3525: return $result;
3526: }
3527:
3528: sub str2hash {
1.265 albertel 3529: my ($string)=@_;
3530: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3531: return %$hash;
3532: }
3533:
3534: sub str2hashref {
1.168 albertel 3535: my ($string) = @_;
1.265 albertel 3536:
3537: my %hash;
3538:
3539: if($string !~ /^__HASH_REF__/) {
3540: if (! ($string eq '' || !defined($string))) {
3541: $hash{'error'}='Not hash reference';
3542: }
3543: return (\%hash, $string);
3544: }
3545:
3546: $string =~ s/^__HASH_REF__//;
3547:
3548: while($string !~ /^__END_HASH_REF__/) {
3549: #key
3550: my $key='';
3551: if($string =~ /^__HASH_REF__/) {
3552: ($key, $string)=&str2hashref($string);
3553: if(defined($key->{'error'})) {
3554: $hash{'error'}='Bad data';
3555: return (\%hash, $string);
3556: }
3557: } elsif($string =~ /^__ARRAY_REF__/) {
3558: ($key, $string)=&str2arrayref($string);
3559: if($key->[0] eq 'Array reference error') {
3560: $hash{'error'}='Bad data';
3561: return (\%hash, $string);
3562: }
3563: } else {
3564: $string =~ s/^(.*?)=//;
1.267 albertel 3565: $key=&unescape($1);
1.265 albertel 3566: }
3567: $string =~ s/^=//;
3568:
3569: #value
3570: my $value='';
3571: if($string =~ /^__HASH_REF__/) {
3572: ($value, $string)=&str2hashref($string);
3573: if(defined($value->{'error'})) {
3574: $hash{'error'}='Bad data';
3575: return (\%hash, $string);
3576: }
3577: } elsif($string =~ /^__ARRAY_REF__/) {
3578: ($value, $string)=&str2arrayref($string);
3579: if($value->[0] eq 'Array reference error') {
3580: $hash{'error'}='Bad data';
3581: return (\%hash, $string);
3582: }
3583: } else {
3584: $value=&get_scalar(\$string,'__END_HASH_REF__');
3585: }
3586: $string =~ s/^&//;
3587:
3588: $hash{$key}=$value;
1.204 albertel 3589: }
1.265 albertel 3590:
3591: $string =~ s/^__END_HASH_REF__//;
3592:
3593: return (\%hash, $string);
1.204 albertel 3594: }
3595:
3596: sub str2array {
1.265 albertel 3597: my ($string)=@_;
3598: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3599: return @$array;
3600: }
3601:
3602: sub str2arrayref {
1.204 albertel 3603: my ($string) = @_;
1.265 albertel 3604: my @array;
3605:
3606: if($string !~ /^__ARRAY_REF__/) {
3607: if (! ($string eq '' || !defined($string))) {
3608: $array[0]='Array reference error';
3609: }
3610: return (\@array, $string);
3611: }
3612:
3613: $string =~ s/^__ARRAY_REF__//;
3614:
3615: while($string !~ /^__END_ARRAY_REF__/) {
3616: my $value='';
3617: if($string =~ /^__HASH_REF__/) {
3618: ($value, $string)=&str2hashref($string);
3619: if(defined($value->{'error'})) {
3620: $array[0] ='Array reference error';
3621: return (\@array, $string);
3622: }
3623: } elsif($string =~ /^__ARRAY_REF__/) {
3624: ($value, $string)=&str2arrayref($string);
3625: if($value->[0] eq 'Array reference error') {
3626: $array[0] ='Array reference error';
3627: return (\@array, $string);
3628: }
3629: } else {
3630: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3631: }
3632: $string =~ s/^&//;
3633:
3634: push(@array, $value);
1.191 harris41 3635: }
1.265 albertel 3636:
3637: $string =~ s/^__END_ARRAY_REF__//;
3638:
3639: return (\@array, $string);
1.168 albertel 3640: }
3641:
1.167 albertel 3642: # -------------------------------------------------------------------Temp Store
3643:
1.168 albertel 3644: sub tmpreset {
3645: my ($symb,$namespace,$domain,$stuname) = @_;
3646: if (!$symb) {
3647: $symb=&symbread();
1.620 albertel 3648: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3649: }
3650: $symb=escape($symb);
3651:
1.620 albertel 3652: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3653: $namespace=~s/\//\_/g;
3654: $namespace=~s/\W//g;
3655:
1.620 albertel 3656: if (!$domain) { $domain=$env{'user.domain'}; }
3657: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3658: if ($domain eq 'public' && $stuname eq 'public') {
3659: $stuname=$ENV{'REMOTE_ADDR'};
3660: }
1.168 albertel 3661: my $path=$perlvar{'lonDaemons'}.'/tmp';
3662: my %hash;
3663: if (tie(%hash,'GDBM_File',
3664: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3665: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3666: foreach my $key (keys(%hash)) {
1.180 albertel 3667: if ($key=~ /:$symb/) {
1.168 albertel 3668: delete($hash{$key});
3669: }
3670: }
3671: }
3672: }
3673:
1.167 albertel 3674: sub tmpstore {
1.168 albertel 3675: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3676:
3677: if (!$symb) {
3678: $symb=&symbread();
1.620 albertel 3679: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3680: }
3681: $symb=escape($symb);
3682:
3683: if (!$namespace) {
3684: # I don't think we would ever want to store this for a course.
3685: # it seems this will only be used if we don't have a course.
1.620 albertel 3686: #$namespace=$env{'request.course.id'};
1.168 albertel 3687: #if (!$namespace) {
1.620 albertel 3688: $namespace=$env{'request.state'};
1.168 albertel 3689: #}
3690: }
3691: $namespace=~s/\//\_/g;
3692: $namespace=~s/\W//g;
1.620 albertel 3693: if (!$domain) { $domain=$env{'user.domain'}; }
3694: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3695: if ($domain eq 'public' && $stuname eq 'public') {
3696: $stuname=$ENV{'REMOTE_ADDR'};
3697: }
1.168 albertel 3698: my $now=time;
3699: my %hash;
3700: my $path=$perlvar{'lonDaemons'}.'/tmp';
3701: if (tie(%hash,'GDBM_File',
3702: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3703: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3704: $hash{"version:$symb"}++;
3705: my $version=$hash{"version:$symb"};
3706: my $allkeys='';
3707: foreach my $key (keys(%$storehash)) {
3708: $allkeys.=$key.':';
1.591 albertel 3709: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3710: }
3711: $hash{"$version:$symb:timestamp"}=$now;
3712: $allkeys.='timestamp';
3713: $hash{"$version:keys:$symb"}=$allkeys;
3714: if (untie(%hash)) {
3715: return 'ok';
3716: } else {
3717: return "error:$!";
3718: }
3719: } else {
3720: return "error:$!";
3721: }
3722: }
1.167 albertel 3723:
1.168 albertel 3724: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3725:
1.168 albertel 3726: sub tmprestore {
3727: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3728:
1.168 albertel 3729: if (!$symb) {
3730: $symb=&symbread();
1.620 albertel 3731: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3732: }
3733: $symb=escape($symb);
3734:
1.620 albertel 3735: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3736:
1.620 albertel 3737: if (!$domain) { $domain=$env{'user.domain'}; }
3738: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3739: if ($domain eq 'public' && $stuname eq 'public') {
3740: $stuname=$ENV{'REMOTE_ADDR'};
3741: }
1.168 albertel 3742: my %returnhash;
3743: $namespace=~s/\//\_/g;
3744: $namespace=~s/\W//g;
3745: my %hash;
3746: my $path=$perlvar{'lonDaemons'}.'/tmp';
3747: if (tie(%hash,'GDBM_File',
3748: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3749: &GDBM_READER(),0640)) {
1.168 albertel 3750: my $version=$hash{"version:$symb"};
3751: $returnhash{'version'}=$version;
3752: my $scope;
3753: for ($scope=1;$scope<=$version;$scope++) {
3754: my $vkeys=$hash{"$scope:keys:$symb"};
3755: my @keys=split(/:/,$vkeys);
3756: my $key;
3757: $returnhash{"$scope:keys"}=$vkeys;
3758: foreach $key (@keys) {
1.591 albertel 3759: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3760: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3761: }
3762: }
1.168 albertel 3763: if (!(untie(%hash))) {
3764: return "error:$!";
3765: }
3766: } else {
3767: return "error:$!";
3768: }
3769: return %returnhash;
1.167 albertel 3770: }
3771:
1.9 www 3772: # ----------------------------------------------------------------------- Store
3773:
3774: sub store {
1.124 www 3775: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3776: my $home='';
3777:
1.168 albertel 3778: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3779:
1.213 www 3780: $symb=&symbclean($symb);
1.122 albertel 3781: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3782:
1.620 albertel 3783: if (!$domain) { $domain=$env{'user.domain'}; }
3784: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3785:
3786: &devalidate($symb,$stuname,$domain);
1.109 www 3787:
3788: $symb=escape($symb);
1.187 www 3789: if (!$namespace) {
1.620 albertel 3790: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3791: return '';
3792: }
3793: }
1.620 albertel 3794: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3795:
3796: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3797: $$storehash{'host'}=$perlvar{'lonHostID'};
3798:
1.12 www 3799: my $namevalue='';
1.800 albertel 3800: foreach my $key (keys(%$storehash)) {
3801: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3802: }
1.12 www 3803: $namevalue=~s/\&$//;
1.187 www 3804: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3805: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3806: }
3807:
1.47 www 3808: # -------------------------------------------------------------- Critical Store
3809:
3810: sub cstore {
1.124 www 3811: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3812: my $home='';
3813:
1.168 albertel 3814: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3815:
1.213 www 3816: $symb=&symbclean($symb);
1.122 albertel 3817: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3818:
1.620 albertel 3819: if (!$domain) { $domain=$env{'user.domain'}; }
3820: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3821:
3822: &devalidate($symb,$stuname,$domain);
1.109 www 3823:
3824: $symb=escape($symb);
1.187 www 3825: if (!$namespace) {
1.620 albertel 3826: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3827: return '';
3828: }
3829: }
1.620 albertel 3830: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3831:
3832: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3833: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3834:
1.47 www 3835: my $namevalue='';
1.800 albertel 3836: foreach my $key (keys(%$storehash)) {
3837: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3838: }
1.47 www 3839: $namevalue=~s/\&$//;
1.187 www 3840: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3841: return critical
3842: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3843: }
3844:
1.9 www 3845: # --------------------------------------------------------------------- Restore
3846:
3847: sub restore {
1.124 www 3848: my ($symb,$namespace,$domain,$stuname) = @_;
3849: my $home='';
3850:
1.168 albertel 3851: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3852:
1.122 albertel 3853: if (!$symb) {
3854: unless ($symb=escape(&symbread())) { return ''; }
3855: } else {
1.213 www 3856: $symb=&escape(&symbclean($symb));
1.122 albertel 3857: }
1.188 www 3858: if (!$namespace) {
1.620 albertel 3859: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3860: return '';
3861: }
3862: }
1.620 albertel 3863: if (!$domain) { $domain=$env{'user.domain'}; }
3864: if (!$stuname) { $stuname=$env{'user.name'}; }
3865: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3866: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3867:
1.12 www 3868: my %returnhash=();
1.800 albertel 3869: foreach my $line (split(/\&/,$answer)) {
3870: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3871: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3872: }
1.75 www 3873: my $version;
3874: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3875: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3876: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3877: }
1.75 www 3878: }
1.13 www 3879: return %returnhash;
1.34 www 3880: }
3881:
3882: # ---------------------------------------------------------- Course Description
3883:
3884: sub coursedescription {
1.731 albertel 3885: my ($courseid,$args)=@_;
1.34 www 3886: $courseid=~s/^\///;
1.49 www 3887: $courseid=~s/\_/\//g;
1.34 www 3888: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3889: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3890: my $normalid=$cdomain.'_'.$cnum;
3891: # need to always cache even if we get errors otherwise we keep
3892: # trying and trying and trying to get the course description.
3893: my %envhash=();
3894: my %returnhash=();
1.731 albertel 3895:
3896: my $expiretime=600;
3897: if ($env{'request.course.id'} eq $normalid) {
3898: $expiretime=120;
3899: }
3900:
3901: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3902: if (!$args->{'freshen_cache'}
3903: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3904: foreach my $key (keys(%env)) {
3905: next if ($key !~ /^\Q$prefix\E(.*)/);
3906: my ($setting) = $1;
3907: $returnhash{$setting} = $env{$key};
3908: }
3909: return %returnhash;
3910: }
3911:
3912: # get the data agin
3913: if (!$args->{'one_time'}) {
3914: $envhash{'course.'.$normalid.'.last_cache'}=time;
3915: }
1.811 albertel 3916:
1.34 www 3917: if ($chome ne 'no_host') {
1.302 albertel 3918: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3919: if (!exists($returnhash{'con_lost'})) {
3920: $returnhash{'home'}= $chome;
3921: $returnhash{'domain'} = $cdomain;
3922: $returnhash{'num'} = $cnum;
1.741 raeburn 3923: if (!defined($returnhash{'type'})) {
3924: $returnhash{'type'} = 'Course';
3925: }
1.130 albertel 3926: while (my ($name,$value) = each %returnhash) {
1.53 www 3927: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3928: }
1.270 www 3929: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3930: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3931: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3932: $envhash{'course.'.$normalid.'.home'}=$chome;
3933: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3934: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3935: }
3936: }
1.731 albertel 3937: if (!$args->{'one_time'}) {
1.949 raeburn 3938: &appenv(\%envhash);
1.731 albertel 3939: }
1.302 albertel 3940: return %returnhash;
1.461 www 3941: }
3942:
1.1080 raeburn 3943: sub update_released_required {
3944: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
3945: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
3946: $cid = $env{'request.course.id'};
3947: $cdom = $env{'course.'.$cid.'.domain'};
3948: $cnum = $env{'course.'.$cid.'.num'};
3949: $chome = $env{'course.'.$cid.'.home'};
3950: }
3951: if ($needsrelease) {
3952: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
3953: my $needsupdate;
3954: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
3955: $needsupdate = 1;
3956: } else {
3957: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
3958: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
3959: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
3960: $needsupdate = 1;
3961: }
3962: }
3963: if ($needsupdate) {
3964: my %needshash = (
3965: 'internal.releaserequired' => $needsrelease,
3966: );
3967: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
3968: if ($putresult eq 'ok') {
3969: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
3970: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
3971: if (ref($crsinfo{$cid}) eq 'HASH') {
3972: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
3973: &courseidput($cdom,\%crsinfo,$chome,'notime');
3974: }
3975: }
3976: }
3977: }
3978: return;
3979: }
3980:
1.461 www 3981: # -------------------------------------------------See if a user is privileged
3982:
3983: sub privileged {
3984: my ($username,$domain)=@_;
3985: my $rolesdump=&reply("dump:$domain:$username:roles",
3986: &homeserver($username,$domain));
1.1033 raeburn 3987: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3988: ($rolesdump =~ /^error:/)) {
3989: return 0;
3990: }
1.461 www 3991: my $now=time;
3992: if ($rolesdump ne '') {
1.800 albertel 3993: foreach my $entry (split(/&/,$rolesdump)) {
3994: if ($entry!~/^rolesdef_/) {
3995: my ($area,$role)=split(/=/,$entry);
1.461 www 3996: $area=~s/\_\w\w$//;
3997: my ($trole,$tend,$tstart)=split(/_/,$role);
3998: if (($trole eq 'dc') || ($trole eq 'su')) {
3999: my $active=1;
4000: if ($tend) {
4001: if ($tend<$now) { $active=0; }
4002: }
4003: if ($tstart) {
4004: if ($tstart>$now) { $active=0; }
4005: }
4006: if ($active) { return 1; }
4007: }
4008: }
4009: }
4010: }
4011: return 0;
1.9 www 4012: }
1.1 albertel 4013:
1.103 harris41 4014: # -------------------------------------------------------- Get user privileges
1.11 www 4015:
4016: sub rolesinit {
4017: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4018: my $now=time;
4019: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4020: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4021: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4022: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4023: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4024: return \%userroles;
4025: }
1.11 www 4026: my %allroles=();
1.678 raeburn 4027: my %allgroups=();
4028: my $group_privs;
1.11 www 4029:
4030: if ($rolesdump ne '') {
1.800 albertel 4031: foreach my $entry (split(/&/,$rolesdump)) {
4032: if ($entry!~/^rolesdef_/) {
4033: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4034: $area=~s/\_\w\w$//;
1.678 raeburn 4035: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4036: if ($role=~/^cr/) {
1.807 albertel 4037: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4038: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4039: ($tend,$tstart)=split('_',$trest);
4040: } else {
4041: $trole=$role;
4042: }
1.678 raeburn 4043: } elsif ($role =~ m|^gr/|) {
4044: ($trole,$tend,$tstart) = split(/_/,$role);
4045: ($trole,$group_privs) = split(/\//,$trole);
4046: $group_privs = &unescape($group_privs);
1.587 albertel 4047: } else {
4048: ($trole,$tend,$tstart)=split(/_/,$role);
4049: }
1.743 albertel 4050: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4051: $username);
4052: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4053: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4054: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4055: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4056: my $spec=$trole.'.'.$area;
4057: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4058: if ($trole =~ /^cr\//) {
1.567 raeburn 4059: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4060: } elsif ($trole eq 'gr') {
4061: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4062: } else {
1.567 raeburn 4063: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4064: }
1.12 www 4065: }
1.662 raeburn 4066: }
1.191 harris41 4067: }
1.743 albertel 4068: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4069: $userroles{'user.adv'} = $adv;
4070: $userroles{'user.author'} = $author;
1.620 albertel 4071: $env{'user.adv'}=$adv;
1.11 www 4072: }
1.743 albertel 4073: return \%userroles;
1.11 www 4074: }
4075:
1.567 raeburn 4076: sub set_arearole {
4077: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4078: # log the associated role with the area
4079: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4080: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4081: }
4082:
4083: sub custom_roleprivs {
4084: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4085: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4086: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4087: if (&hostname($homsvr) ne '') {
1.567 raeburn 4088: my ($rdummy,$roledef)=
4089: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4090: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4091: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4092: if (defined($syspriv)) {
1.1043 raeburn 4093: if ($trest =~ /^$match_community$/) {
4094: $syspriv =~ s/bre\&S//;
4095: }
1.567 raeburn 4096: $$allroles{'cm./'}.=':'.$syspriv;
4097: $$allroles{$spec.'./'}.=':'.$syspriv;
4098: }
4099: if ($tdomain ne '') {
4100: if (defined($dompriv)) {
4101: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4102: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4103: }
4104: if (($trest ne '') && (defined($coursepriv))) {
4105: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4106: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4107: }
4108: }
4109: }
4110: }
4111: }
4112:
1.678 raeburn 4113: sub group_roleprivs {
4114: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4115: my $access = 1;
4116: my $now = time;
4117: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4118: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4119: if ($access) {
1.811 albertel 4120: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4121: $$allgroups{$course}{$group} .=':'.$group_privs;
4122: }
4123: }
1.567 raeburn 4124:
4125: sub standard_roleprivs {
4126: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4127: if (defined($pr{$trole.':s'})) {
4128: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4129: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4130: }
4131: if ($tdomain ne '') {
4132: if (defined($pr{$trole.':d'})) {
4133: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4134: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4135: }
4136: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4137: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4138: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4139: }
4140: }
4141: }
4142:
4143: sub set_userprivs {
1.1064 raeburn 4144: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4145: my $author=0;
4146: my $adv=0;
1.678 raeburn 4147: my %grouproles = ();
4148: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4149: my @groupkeys;
1.1000 raeburn 4150: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4151: push(@groupkeys,$role);
4152: }
4153: if (ref($groups_roles) eq 'HASH') {
4154: foreach my $key (keys(%{$groups_roles})) {
4155: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4156: push(@groupkeys,$key);
4157: }
4158: }
4159: }
4160: if (@groupkeys > 0) {
4161: foreach my $role (@groupkeys) {
4162: my ($trole,$area,$sec,$extendedarea);
4163: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4164: $trole = $1;
4165: $area = $2;
4166: $sec = $3;
4167: $extendedarea = $area.$sec;
4168: if (exists($$allgroups{$area})) {
4169: foreach my $group (keys(%{$$allgroups{$area}})) {
4170: my $spec = $trole.'.'.$extendedarea;
4171: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4172: $$allgroups{$area}{$group};
1.1064 raeburn 4173: }
1.678 raeburn 4174: }
4175: }
4176: }
4177: }
4178: }
1.800 albertel 4179: foreach my $group (keys(%grouproles)) {
4180: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4181: }
1.800 albertel 4182: foreach my $role (keys(%{$allroles})) {
4183: my %thesepriv;
1.941 raeburn 4184: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4185: foreach my $item (split(/:/,$$allroles{$role})) {
4186: if ($item ne '') {
4187: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4188: if ($restrictions eq '') {
4189: $thesepriv{$privilege}='F';
4190: } elsif ($thesepriv{$privilege} ne 'F') {
4191: $thesepriv{$privilege}.=$restrictions;
4192: }
4193: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4194: }
4195: }
4196: my $thesestr='';
1.800 albertel 4197: foreach my $priv (keys(%thesepriv)) {
4198: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4199: }
4200: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4201: }
4202: return ($author,$adv);
4203: }
4204:
1.994 raeburn 4205: sub role_status {
1.1002 raeburn 4206: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4207: my @pwhere = ();
4208: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4209: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4210: unless (!defined($$role) || $$role eq '') {
4211: $$where=join('.',@pwhere);
4212: $$trolecode=$$role.'.'.$$where;
4213: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4214: $$tstatus='is';
4215: if ($$tstart && $$tstart>$then) {
4216: $$tstatus='future';
1.1034 raeburn 4217: if ($$tstart<$now) {
4218: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4219: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4220: my (%allroles,%allgroups,$group_privs,
4221: %groups_roles,@rolecodes);
1.1002 raeburn 4222: my %userroles = (
4223: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4224: );
1.1064 raeburn 4225: @rolecodes = ('cm');
1.1002 raeburn 4226: my $spec=$$role.'.'.$$where;
4227: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4228: if ($$role =~ /^cr\//) {
4229: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4230: push(@rolecodes,'cr');
1.1002 raeburn 4231: } elsif ($$role eq 'gr') {
1.1064 raeburn 4232: push(@rolecodes,$$role);
1.1002 raeburn 4233: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4234: $env{'user.name'});
1.1064 raeburn 4235: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4236: (undef,my $group_privs) = split(/\//,$trole);
4237: $group_privs = &unescape($group_privs);
4238: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4239: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4240: if (keys(%course_roles) > 0) {
4241: my ($tnum) = ($trest =~ /^($match_courseid)/);
4242: if ($tdomain ne '' && $tnum ne '') {
4243: foreach my $key (keys(%course_roles)) {
4244: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4245: my $crsrole = $1;
4246: my $crssec = $2;
4247: if ($crsrole =~ /^cr/) {
4248: unless (grep(/^cr$/,@rolecodes)) {
4249: push(@rolecodes,'cr');
4250: }
4251: } else {
4252: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4253: push(@rolecodes,$crsrole);
4254: }
4255: }
4256: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4257: if ($crssec ne '') {
4258: $rolekey .= '/'.$crssec;
4259: }
4260: $rolekey .= './';
4261: $groups_roles{$rolekey} = \@rolecodes;
4262: }
4263: }
4264: }
4265: }
1.1002 raeburn 4266: } else {
1.1064 raeburn 4267: push(@rolecodes,$$role);
1.1002 raeburn 4268: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4269: }
1.1064 raeburn 4270: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4271: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4272: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4273: }
4274: }
1.1034 raeburn 4275: $$tstatus = 'is';
1.1002 raeburn 4276: }
1.994 raeburn 4277: }
4278: if ($$tend) {
4279: if ($$tend<$then) {
4280: $$tstatus='expired';
4281: } elsif ($$tend<$now) {
4282: $$tstatus='will_not';
4283: }
4284: }
4285: }
4286: }
4287: }
4288:
4289: sub check_adhoc_privs {
1.1002 raeburn 4290: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4291: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4292: if ($env{$cckey}) {
4293: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4294: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4295: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4296: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4297: }
4298: } else {
4299: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4300: }
4301: }
4302:
4303: sub set_adhoc_privileges {
4304: # role can be cc or ca
4305: my ($dcdom,$pickedcourse,$role) = @_;
4306: my $area = '/'.$dcdom.'/'.$pickedcourse;
4307: my $spec = $role.'.'.$area;
4308: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4309: $env{'user.name'});
4310: my %ccrole = ();
4311: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4312: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4313: &appenv(\%userroles,[$role,'cm']);
4314: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4315: &appenv( {'request.role' => $spec,
4316: 'request.role.domain' => $dcdom,
4317: 'request.course.sec' => ''
4318: }
4319: );
4320: my $tadv=0;
4321: if (&allowed('adv') eq 'F') { $tadv=1; }
4322: &appenv({'request.role.adv' => $tadv});
4323: }
4324:
1.12 www 4325: # --------------------------------------------------------------- get interface
4326:
4327: sub get {
1.131 albertel 4328: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4329: my $items='';
1.800 albertel 4330: foreach my $item (@$storearr) {
4331: $items.=&escape($item).'&';
1.191 harris41 4332: }
1.12 www 4333: $items=~s/\&$//;
1.620 albertel 4334: if (!$udomain) { $udomain=$env{'user.domain'}; }
4335: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4336: my $uhome=&homeserver($uname,$udomain);
4337:
1.133 albertel 4338: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4339: my @pairs=split(/\&/,$rep);
1.273 albertel 4340: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4341: return @pairs;
4342: }
1.15 www 4343: my %returnhash=();
1.42 www 4344: my $i=0;
1.800 albertel 4345: foreach my $item (@$storearr) {
4346: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4347: $i++;
1.191 harris41 4348: }
1.15 www 4349: return %returnhash;
1.27 www 4350: }
4351:
4352: # --------------------------------------------------------------- del interface
4353:
4354: sub del {
1.133 albertel 4355: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4356: my $items='';
1.800 albertel 4357: foreach my $item (@$storearr) {
4358: $items.=&escape($item).'&';
1.191 harris41 4359: }
1.984 neumanie 4360:
1.27 www 4361: $items=~s/\&$//;
1.620 albertel 4362: if (!$udomain) { $udomain=$env{'user.domain'}; }
4363: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4364: my $uhome=&homeserver($uname,$udomain);
4365: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4366: }
4367:
4368: # -------------------------------------------------------------- dump interface
4369:
4370: sub dump {
1.1086 raeburn 4371: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4372: if (!$udomain) { $udomain=$env{'user.domain'}; }
4373: if (!$uname) { $uname=$env{'user.name'}; }
4374: my $uhome=&homeserver($uname,$udomain);
4375: if ($regexp) {
4376: $regexp=&escape($regexp);
4377: } else {
4378: $regexp='.';
4379: }
1.1086 raeburn 4380: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4381: my @pairs=split(/\&/,$rep);
4382: my %returnhash=();
4383: foreach my $item (@pairs) {
4384: my ($key,$value)=split(/=/,$item,2);
4385: $key = &unescape($key);
4386: next if ($key =~ /^error: 2 /);
4387: $returnhash{$key}=&thaw_unescape($value);
4388: }
4389: return %returnhash;
1.407 www 4390: }
4391:
1.717 albertel 4392: # --------------------------------------------------------- dumpstore interface
4393:
4394: sub dumpstore {
4395: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4396: if (!$udomain) { $udomain=$env{'user.domain'}; }
4397: if (!$uname) { $uname=$env{'user.name'}; }
4398: my $uhome=&homeserver($uname,$udomain);
4399: if ($regexp) {
4400: $regexp=&escape($regexp);
4401: } else {
4402: $regexp='.';
4403: }
4404: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4405: my @pairs=split(/\&/,$rep);
4406: my %returnhash=();
4407: foreach my $item (@pairs) {
4408: my ($key,$value)=split(/=/,$item,2);
4409: next if ($key =~ /^error: 2 /);
4410: $returnhash{$key}=&thaw_unescape($value);
4411: }
4412: return %returnhash;
1.717 albertel 4413: }
4414:
1.407 www 4415: # -------------------------------------------------------------- keys interface
4416:
4417: sub getkeys {
4418: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4419: if (!$udomain) { $udomain=$env{'user.domain'}; }
4420: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4421: my $uhome=&homeserver($uname,$udomain);
4422: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4423: my @keyarray=();
1.800 albertel 4424: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4425: next if ($key =~ /^error: 2 /);
1.800 albertel 4426: push(@keyarray,&unescape($key));
1.407 www 4427: }
4428: return @keyarray;
1.318 matthew 4429: }
4430:
1.319 matthew 4431: # --------------------------------------------------------------- currentdump
4432: sub currentdump {
1.328 matthew 4433: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4434: $courseid = $env{'request.course.id'} if (! defined($courseid));
4435: $sdom = $env{'user.domain'} if (! defined($sdom));
4436: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4437: my $uhome = &homeserver($sname,$sdom);
4438: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4439: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4440: #
1.318 matthew 4441: my %returnhash=();
1.319 matthew 4442: #
4443: if ($rep eq "unknown_cmd") {
4444: # an old lond will not know currentdump
4445: # Do a dump and make it look like a currentdump
1.822 albertel 4446: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4447: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4448: my %hash = @tmp;
4449: @tmp=();
1.424 matthew 4450: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4451: } else {
4452: my @pairs=split(/\&/,$rep);
1.800 albertel 4453: foreach my $pair (@pairs) {
4454: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4455: my ($symb,$param) = split(/:/,$key);
4456: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4457: &thaw_unescape($value);
1.319 matthew 4458: }
1.191 harris41 4459: }
1.12 www 4460: return %returnhash;
1.424 matthew 4461: }
4462:
4463: sub convert_dump_to_currentdump{
4464: my %hash = %{shift()};
4465: my %returnhash;
4466: # Code ripped from lond, essentially. The only difference
4467: # here is the unescaping done by lonnet::dump(). Conceivably
4468: # we might run in to problems with parameter names =~ /^v\./
4469: while (my ($key,$value) = each(%hash)) {
4470: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4471: $symb = &unescape($symb);
4472: $param = &unescape($param);
1.424 matthew 4473: next if ($v eq 'version' || $symb eq 'keys');
4474: next if (exists($returnhash{$symb}) &&
4475: exists($returnhash{$symb}->{$param}) &&
4476: $returnhash{$symb}->{'v.'.$param} > $v);
4477: $returnhash{$symb}->{$param}=$value;
4478: $returnhash{$symb}->{'v.'.$param}=$v;
4479: }
4480: #
4481: # Remove all of the keys in the hashes which keep track of
4482: # the version of the parameter.
4483: while (my ($symb,$param_hash) = each(%returnhash)) {
4484: # use a foreach because we are going to delete from the hash.
4485: foreach my $key (keys(%$param_hash)) {
4486: delete($param_hash->{$key}) if ($key =~ /^v\./);
4487: }
4488: }
4489: return \%returnhash;
1.12 www 4490: }
4491:
1.627 albertel 4492: # ------------------------------------------------------ critical inc interface
4493:
4494: sub cinc {
4495: return &inc(@_,'critical');
4496: }
4497:
1.449 matthew 4498: # --------------------------------------------------------------- inc interface
4499:
4500: sub inc {
1.627 albertel 4501: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4502: if (!$udomain) { $udomain=$env{'user.domain'}; }
4503: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4504: my $uhome=&homeserver($uname,$udomain);
4505: my $items='';
4506: if (! ref($store)) {
4507: # got a single value, so use that instead
4508: $items = &escape($store).'=&';
4509: } elsif (ref($store) eq 'SCALAR') {
4510: $items = &escape($$store).'=&';
4511: } elsif (ref($store) eq 'ARRAY') {
4512: $items = join('=&',map {&escape($_);} @{$store});
4513: } elsif (ref($store) eq 'HASH') {
4514: while (my($key,$value) = each(%{$store})) {
4515: $items.= &escape($key).'='.&escape($value).'&';
4516: }
4517: }
4518: $items=~s/\&$//;
1.627 albertel 4519: if ($critical) {
4520: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4521: } else {
4522: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4523: }
1.449 matthew 4524: }
4525:
1.12 www 4526: # --------------------------------------------------------------- put interface
4527:
4528: sub put {
1.134 albertel 4529: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4530: if (!$udomain) { $udomain=$env{'user.domain'}; }
4531: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4532: my $uhome=&homeserver($uname,$udomain);
1.12 www 4533: my $items='';
1.800 albertel 4534: foreach my $item (keys(%$storehash)) {
4535: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4536: }
1.12 www 4537: $items=~s/\&$//;
1.134 albertel 4538: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4539: }
4540:
1.631 albertel 4541: # ------------------------------------------------------------ newput interface
4542:
4543: sub newput {
4544: my ($namespace,$storehash,$udomain,$uname)=@_;
4545: if (!$udomain) { $udomain=$env{'user.domain'}; }
4546: if (!$uname) { $uname=$env{'user.name'}; }
4547: my $uhome=&homeserver($uname,$udomain);
4548: my $items='';
4549: foreach my $key (keys(%$storehash)) {
4550: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4551: }
4552: $items=~s/\&$//;
4553: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4554: }
4555:
4556: # --------------------------------------------------------- putstore interface
4557:
1.524 raeburn 4558: sub putstore {
1.715 albertel 4559: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4560: if (!$udomain) { $udomain=$env{'user.domain'}; }
4561: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4562: my $uhome=&homeserver($uname,$udomain);
4563: my $items='';
1.715 albertel 4564: foreach my $key (keys(%$storehash)) {
4565: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4566: }
1.715 albertel 4567: $items=~s/\&$//;
1.716 albertel 4568: my $esc_symb=&escape($symb);
4569: my $esc_v=&escape($version);
1.715 albertel 4570: my $reply =
1.716 albertel 4571: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4572: $uhome);
4573: if ($reply eq 'unknown_cmd') {
1.716 albertel 4574: # gfall back to way things use to be done
1.715 albertel 4575: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4576: $uname);
1.524 raeburn 4577: }
1.715 albertel 4578: return $reply;
4579: }
4580:
4581: sub old_putstore {
1.716 albertel 4582: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4583: if (!$udomain) { $udomain=$env{'user.domain'}; }
4584: if (!$uname) { $uname=$env{'user.name'}; }
4585: my $uhome=&homeserver($uname,$udomain);
4586: my %newstorehash;
1.800 albertel 4587: foreach my $item (keys(%$storehash)) {
4588: my $key = $version.':'.&escape($symb).':'.$item;
4589: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4590: }
4591: my $items='';
4592: my %allitems = ();
1.800 albertel 4593: foreach my $item (keys(%newstorehash)) {
4594: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4595: my $key = $1.':keys:'.$2;
4596: $allitems{$key} .= $3.':';
4597: }
1.800 albertel 4598: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4599: }
1.800 albertel 4600: foreach my $item (keys(%allitems)) {
4601: $allitems{$item} =~ s/\:$//;
4602: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4603: }
4604: $items=~s/\&$//;
4605: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4606: }
4607:
1.47 www 4608: # ------------------------------------------------------ critical put interface
4609:
4610: sub cput {
1.134 albertel 4611: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4612: if (!$udomain) { $udomain=$env{'user.domain'}; }
4613: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4614: my $uhome=&homeserver($uname,$udomain);
1.47 www 4615: my $items='';
1.800 albertel 4616: foreach my $item (keys(%$storehash)) {
4617: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4618: }
1.47 www 4619: $items=~s/\&$//;
1.134 albertel 4620: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4621: }
4622:
4623: # -------------------------------------------------------------- eget interface
4624:
4625: sub eget {
1.133 albertel 4626: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4627: my $items='';
1.800 albertel 4628: foreach my $item (@$storearr) {
4629: $items.=&escape($item).'&';
1.191 harris41 4630: }
1.12 www 4631: $items=~s/\&$//;
1.620 albertel 4632: if (!$udomain) { $udomain=$env{'user.domain'}; }
4633: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4634: my $uhome=&homeserver($uname,$udomain);
4635: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4636: my @pairs=split(/\&/,$rep);
4637: my %returnhash=();
1.42 www 4638: my $i=0;
1.800 albertel 4639: foreach my $item (@$storearr) {
4640: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4641: $i++;
1.191 harris41 4642: }
1.12 www 4643: return %returnhash;
4644: }
4645:
1.667 albertel 4646: # ------------------------------------------------------------ tmpput interface
4647: sub tmpput {
1.802 raeburn 4648: my ($storehash,$server,$context)=@_;
1.667 albertel 4649: my $items='';
1.800 albertel 4650: foreach my $item (keys(%$storehash)) {
4651: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4652: }
4653: $items=~s/\&$//;
1.802 raeburn 4654: if (defined($context)) {
4655: $items .= ':'.&escape($context);
4656: }
1.667 albertel 4657: return &reply("tmpput:$items",$server);
4658: }
4659:
4660: # ------------------------------------------------------------ tmpget interface
4661: sub tmpget {
1.688 albertel 4662: my ($token,$server)=@_;
4663: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4664: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4665: my %returnhash;
4666: foreach my $item (split(/\&/,$rep)) {
4667: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4668: next if ($key =~ /^error: 2 /);
1.667 albertel 4669: $returnhash{&unescape($key)}=&thaw_unescape($value);
4670: }
4671: return %returnhash;
4672: }
4673:
1.688 albertel 4674: # ------------------------------------------------------------ tmpget interface
4675: sub tmpdel {
4676: my ($token,$server)=@_;
4677: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4678: return &reply("tmpdel:$token",$server);
4679: }
4680:
1.765 albertel 4681: # -------------------------------------------------- portfolio access checking
4682:
4683: sub portfolio_access {
1.766 albertel 4684: my ($requrl) = @_;
1.765 albertel 4685: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4686: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4687: if ($result) {
4688: my %setters;
4689: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4690: my ($startblock,$endblock) =
4691: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4692: if ($startblock && $endblock) {
4693: return 'B';
4694: }
4695: } else {
4696: my ($startblock,$endblock) =
4697: &Apache::loncommon::blockcheck(\%setters,'port');
4698: if ($startblock && $endblock) {
4699: return 'B';
4700: }
4701: }
4702: }
1.765 albertel 4703: if ($result eq 'ok') {
1.766 albertel 4704: return 'F';
1.765 albertel 4705: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4706: return 'A';
1.765 albertel 4707: }
1.766 albertel 4708: return '';
1.765 albertel 4709: }
4710:
4711: sub get_portfolio_access {
1.767 albertel 4712: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4713:
4714: if (!ref($access_hash)) {
4715: my $current_perms = &get_portfile_permissions($udom,$unum);
4716: my %access_controls = &get_access_controls($current_perms,$group,
4717: $file_name);
4718: $access_hash = $access_controls{$file_name};
4719: }
4720:
1.765 albertel 4721: my ($public,$guest,@domains,@users,@courses,@groups);
4722: my $now = time;
4723: if (ref($access_hash) eq 'HASH') {
4724: foreach my $key (keys(%{$access_hash})) {
4725: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4726: if ($start > $now) {
4727: next;
4728: }
4729: if ($end && $end<$now) {
4730: next;
4731: }
4732: if ($scope eq 'public') {
4733: $public = $key;
4734: last;
4735: } elsif ($scope eq 'guest') {
4736: $guest = $key;
4737: } elsif ($scope eq 'domains') {
4738: push(@domains,$key);
4739: } elsif ($scope eq 'users') {
4740: push(@users,$key);
4741: } elsif ($scope eq 'course') {
4742: push(@courses,$key);
4743: } elsif ($scope eq 'group') {
4744: push(@groups,$key);
4745: }
4746: }
4747: if ($public) {
4748: return 'ok';
4749: }
4750: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4751: if ($guest) {
4752: return $guest;
4753: }
4754: } else {
4755: if (@domains > 0) {
4756: foreach my $domkey (@domains) {
4757: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4758: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4759: return 'ok';
4760: }
4761: }
4762: }
4763: }
4764: if (@users > 0) {
4765: foreach my $userkey (@users) {
1.865 raeburn 4766: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4767: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4768: if (ref($item) eq 'HASH') {
4769: if (($item->{'uname'} eq $env{'user.name'}) &&
4770: ($item->{'udom'} eq $env{'user.domain'})) {
4771: return 'ok';
4772: }
4773: }
4774: }
4775: }
1.765 albertel 4776: }
4777: }
4778: my %roleshash;
4779: my @courses_and_groups = @courses;
4780: push(@courses_and_groups,@groups);
4781: if (@courses_and_groups > 0) {
4782: my (%allgroups,%allroles);
4783: my ($start,$end,$role,$sec,$group);
4784: foreach my $envkey (%env) {
1.1060 raeburn 4785: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4786: my $cid = $2.'_'.$3;
4787: if ($1 eq 'gr') {
4788: $group = $4;
4789: $allgroups{$cid}{$group} = $env{$envkey};
4790: } else {
4791: if ($4 eq '') {
4792: $sec = 'none';
4793: } else {
4794: $sec = $4;
4795: }
4796: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4797: }
1.811 albertel 4798: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4799: my $cid = $2.'_'.$3;
4800: if ($4 eq '') {
4801: $sec = 'none';
4802: } else {
4803: $sec = $4;
4804: }
4805: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4806: }
4807: }
4808: if (keys(%allroles) == 0) {
4809: return;
4810: }
4811: foreach my $key (@courses_and_groups) {
4812: my %content = %{$$access_hash{$key}};
4813: my $cnum = $content{'number'};
4814: my $cdom = $content{'domain'};
4815: my $cid = $cdom.'_'.$cnum;
4816: if (!exists($allroles{$cid})) {
4817: next;
4818: }
4819: foreach my $role_id (keys(%{$content{'roles'}})) {
4820: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4821: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4822: my @status = @{$content{'roles'}{$role_id}{'access'}};
4823: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4824: foreach my $role (keys(%{$allroles{$cid}})) {
4825: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4826: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4827: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4828: if (grep/^all$/,@sections) {
4829: return 'ok';
4830: } else {
4831: if (grep/^$sec$/,@sections) {
4832: return 'ok';
4833: }
4834: }
4835: }
4836: }
4837: if (keys(%{$allgroups{$cid}}) == 0) {
4838: if (grep/^none$/,@groups) {
4839: return 'ok';
4840: }
4841: } else {
4842: if (grep/^all$/,@groups) {
4843: return 'ok';
4844: }
4845: foreach my $group (keys(%{$allgroups{$cid}})) {
4846: if (grep/^$group$/,@groups) {
4847: return 'ok';
4848: }
4849: }
4850: }
4851: }
4852: }
4853: }
4854: }
4855: }
4856: if ($guest) {
4857: return $guest;
4858: }
4859: }
4860: }
4861: return;
4862: }
4863:
4864: sub course_group_datechecker {
4865: my ($dates,$now,$status) = @_;
4866: my ($start,$end) = split(/\./,$dates);
4867: if (!$start && !$end) {
4868: return 'ok';
4869: }
4870: if (grep/^active$/,@{$status}) {
4871: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4872: return 'ok';
4873: }
4874: }
4875: if (grep/^previous$/,@{$status}) {
4876: if ($end > $now ) {
4877: return 'ok';
4878: }
4879: }
4880: if (grep/^future$/,@{$status}) {
4881: if ($start > $now) {
4882: return 'ok';
4883: }
4884: }
4885: return;
4886: }
4887:
4888: sub parse_portfolio_url {
4889: my ($url) = @_;
4890:
4891: my ($type,$udom,$unum,$group,$file_name);
4892:
1.823 albertel 4893: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4894: $type = 1;
4895: $udom = $1;
4896: $unum = $2;
4897: $file_name = $3;
1.823 albertel 4898: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4899: $type = 2;
4900: $udom = $1;
4901: $unum = $2;
4902: $group = $3;
4903: $file_name = $3.'/'.$4;
4904: }
4905: if (wantarray) {
4906: return ($type,$udom,$unum,$file_name,$group);
4907: }
4908: return $type;
4909: }
4910:
4911: sub is_portfolio_url {
4912: my ($url) = @_;
4913: return scalar(&parse_portfolio_url($url));
4914: }
4915:
1.798 raeburn 4916: sub is_portfolio_file {
4917: my ($file) = @_;
1.820 raeburn 4918: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4919: return 1;
4920: }
4921: return;
4922: }
4923:
1.976 raeburn 4924: sub usertools_access {
1.1084 raeburn 4925: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 4926: my ($access,%tools);
4927: if ($context eq '') {
4928: $context = 'tools';
4929: }
4930: if ($context eq 'requestcourses') {
4931: %tools = (
4932: official => 1,
4933: unofficial => 1,
1.1006 raeburn 4934: community => 1,
1.985 raeburn 4935: );
4936: } else {
4937: %tools = (
4938: aboutme => 1,
4939: blog => 1,
4940: portfolio => 1,
4941: );
4942: }
1.976 raeburn 4943: return if (!defined($tools{$tool}));
4944:
4945: if ((!defined($udom)) || (!defined($uname))) {
4946: $udom = $env{'user.domain'};
4947: $uname = $env{'user.name'};
4948: }
4949:
1.978 raeburn 4950: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4951: if ($action ne 'reload') {
1.985 raeburn 4952: if ($context eq 'requestcourses') {
4953: return $env{'environment.canrequest.'.$tool};
4954: } else {
4955: return $env{'environment.availabletools.'.$tool};
4956: }
4957: }
1.976 raeburn 4958: }
4959:
4960: my ($toolstatus,$inststatus);
4961:
1.985 raeburn 4962: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4963: ($action ne 'reload')) {
4964: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4965: $inststatus = $env{'environment.inststatus'};
4966: } else {
1.1084 raeburn 4967: if (ref($userenvref) eq 'HASH') {
4968: $toolstatus = $userenvref->{$context.'.'.$tool};
4969: $inststatus = $userenvref->{'inststatus'};
4970: } else {
4971: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
4972: $toolstatus = $userenv{$context.'.'.$tool};
4973: $inststatus = $userenv{'inststatus'};
4974: }
1.976 raeburn 4975: }
4976:
4977: if ($toolstatus ne '') {
4978: if ($toolstatus) {
4979: $access = 1;
4980: } else {
4981: $access = 0;
4982: }
4983: return $access;
4984: }
4985:
1.1084 raeburn 4986: my ($is_adv,%domdef);
4987: if (ref($is_advref) eq 'HASH') {
4988: $is_adv = $is_advref->{'is_adv'};
4989: } else {
4990: $is_adv = &is_advanced_user($udom,$uname);
4991: }
4992: if (ref($domdefref) eq 'HASH') {
4993: %domdef = %{$domdefref};
4994: } else {
4995: %domdef = &get_domain_defaults($udom);
4996: }
1.976 raeburn 4997: if (ref($domdef{$tool}) eq 'HASH') {
4998: if ($is_adv) {
4999: if ($domdef{$tool}{'_LC_adv'} ne '') {
5000: if ($domdef{$tool}{'_LC_adv'}) {
5001: $access = 1;
5002: } else {
5003: $access = 0;
5004: }
5005: return $access;
5006: }
5007: }
5008: if ($inststatus ne '') {
5009: my ($hasaccess,$hasnoaccess);
5010: foreach my $affiliation (split(/:/,$inststatus)) {
5011: if ($domdef{$tool}{$affiliation} ne '') {
5012: if ($domdef{$tool}{$affiliation}) {
5013: $hasaccess = 1;
5014: } else {
5015: $hasnoaccess = 1;
5016: }
5017: }
5018: }
5019: if ($hasaccess || $hasnoaccess) {
5020: if ($hasaccess) {
5021: $access = 1;
5022: } elsif ($hasnoaccess) {
5023: $access = 0;
5024: }
5025: return $access;
5026: }
5027: } else {
5028: if ($domdef{$tool}{'default'} ne '') {
5029: if ($domdef{$tool}{'default'}) {
5030: $access = 1;
5031: } elsif ($domdef{$tool}{'default'} == 0) {
5032: $access = 0;
5033: }
5034: return $access;
5035: }
5036: }
5037: } else {
1.985 raeburn 5038: if ($context eq 'tools') {
5039: $access = 1;
5040: } else {
5041: $access = 0;
5042: }
1.976 raeburn 5043: return $access;
5044: }
5045: }
5046:
1.1050 raeburn 5047: sub is_course_owner {
5048: my ($cdom,$cnum,$udom,$uname) = @_;
5049: if (($udom eq '') || ($uname eq '')) {
5050: $udom = $env{'user.domain'};
5051: $uname = $env{'user.name'};
5052: }
5053: unless (($udom eq '') || ($uname eq '')) {
5054: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5055: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5056: return 1;
5057: } else {
5058: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5059: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5060: return 1;
5061: }
5062: }
5063: }
5064: }
5065: return;
5066: }
5067:
1.976 raeburn 5068: sub is_advanced_user {
5069: my ($udom,$uname) = @_;
1.1085 raeburn 5070: if ($udom ne '' && $uname ne '') {
5071: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5072: return $env{'user.adv'};
5073: }
5074: }
1.976 raeburn 5075: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5076: my %allroles;
5077: my $is_adv;
5078: foreach my $role (keys(%roleshash)) {
5079: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5080: my $area = '/'.$tdomain.'/'.$trest;
5081: if ($sec ne '') {
5082: $area .= '/'.$sec;
5083: }
5084: if (($area ne '') && ($trole ne '')) {
5085: my $spec=$trole.'.'.$area;
5086: if ($trole =~ /^cr\//) {
5087: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5088: } elsif ($trole ne 'gr') {
5089: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5090: }
5091: }
5092: }
5093: foreach my $role (keys(%allroles)) {
5094: last if ($is_adv);
5095: foreach my $item (split(/:/,$allroles{$role})) {
5096: if ($item ne '') {
5097: my ($privilege,$restrictions)=split(/&/,$item);
5098: if ($privilege eq 'adv') {
5099: $is_adv = 1;
5100: last;
5101: }
5102: }
5103: }
5104: }
5105: return $is_adv;
5106: }
1.798 raeburn 5107:
1.1035 raeburn 5108: sub check_can_request {
1.1036 raeburn 5109: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5110: my $canreq = 0;
5111: my ($types,$typename) = &Apache::loncommon::course_types();
5112: my @options = ('approval','validate','autolimit');
5113: my $optregex = join('|',@options);
5114: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5115: foreach my $type (@{$types}) {
5116: if (&usertools_access($env{'user.name'},
5117: $env{'user.domain'},
5118: $type,undef,'requestcourses')) {
5119: $canreq ++;
1.1036 raeburn 5120: if (ref($request_domains) eq 'HASH') {
5121: push(@{$request_domains->{$type}},$env{'user.domain'});
5122: }
1.1035 raeburn 5123: if ($dom eq $env{'user.domain'}) {
5124: $can_request->{$type} = 1;
5125: }
5126: }
5127: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5128: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5129: if (@curr > 0) {
1.1036 raeburn 5130: foreach my $item (@curr) {
5131: if (ref($request_domains) eq 'HASH') {
5132: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5133: if ($otherdom ne '') {
5134: if (ref($request_domains->{$type}) eq 'ARRAY') {
5135: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5136: push(@{$request_domains->{$type}},$otherdom);
5137: }
5138: } else {
5139: push(@{$request_domains->{$type}},$otherdom);
5140: }
5141: }
5142: }
5143: }
5144: unless($dom eq $env{'user.domain'}) {
5145: $canreq ++;
1.1035 raeburn 5146: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5147: $can_request->{$type} = 1;
5148: }
5149: }
5150: }
5151: }
5152: }
5153: }
5154: return $canreq;
5155: }
5156:
1.341 www 5157: # ---------------------------------------------- Custom access rule evaluation
5158:
5159: sub customaccess {
5160: my ($priv,$uri)=@_;
1.807 albertel 5161: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5162: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5163: $udom = &LONCAPA::clean_domain($udom);
5164: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5165: my $access=0;
1.800 albertel 5166: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5167: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5168: if ($type eq 'user') {
5169: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5170: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5171: if ($tdom) {
5172: if ($tdom ne $env{'user.domain'}) { next; }
5173: }
1.896 albertel 5174: if ($tuname) {
5175: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5176: }
5177: $access=($effect eq 'allow');
5178: last;
5179: }
5180: } else {
5181: if ($role) {
5182: if ($role ne $urole) { next; }
5183: }
5184: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5185: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5186: if ($tdom) {
5187: if ($tdom ne $udom) { next; }
5188: }
5189: if ($tcrs) {
5190: if ($tcrs ne $ucrs) { next; }
5191: }
5192: if ($tsec) {
5193: if ($tsec ne $usec) { next; }
5194: }
5195: $access=($effect eq 'allow');
5196: last;
5197: }
5198: if ($realm eq '' && $role eq '') {
5199: $access=($effect eq 'allow');
5200: }
1.402 bowersj2 5201: }
1.341 www 5202: }
5203: return $access;
5204: }
5205:
1.103 harris41 5206: # ------------------------------------------------- Check for a user privilege
1.12 www 5207:
5208: sub allowed {
1.810 raeburn 5209: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5210: my $ver_orguri=$uri;
1.439 www 5211: $uri=&deversion($uri);
1.152 www 5212: my $orguri=$uri;
1.52 www 5213: $uri=&declutter($uri);
1.809 raeburn 5214:
1.810 raeburn 5215: if ($priv eq 'evb') {
5216: # Evade communication block restrictions for specified role in a course
5217: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5218: return $1;
5219: } else {
5220: return;
5221: }
5222: }
5223:
1.620 albertel 5224: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5225: # Free bre access to adm and meta resources
1.775 albertel 5226: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5227: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5228: && ($priv eq 'bre')) {
1.14 www 5229: return 'F';
1.159 www 5230: }
5231:
1.545 banghart 5232: # Free bre access to user's own portfolio contents
1.714 raeburn 5233: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5234: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5235: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5236: my %setters;
5237: my ($startblock,$endblock) =
5238: &Apache::loncommon::blockcheck(\%setters,'port');
5239: if ($startblock && $endblock) {
5240: return 'B';
5241: } else {
5242: return 'F';
5243: }
1.545 banghart 5244: }
5245:
1.762 raeburn 5246: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5247: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5248: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5249: if (exists($env{'request.course.id'})) {
5250: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5251: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5252: if (($domain eq $cdom) && ($name eq $cnum)) {
5253: my $courseprivid=$env{'request.course.id'};
5254: $courseprivid=~s/\_/\//;
5255: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5256: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5257: return $1;
1.762 raeburn 5258: } else {
5259: if ($env{'request.course.sec'}) {
5260: $courseprivid.='/'.$env{'request.course.sec'};
5261: }
5262: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5263: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5264: return $2;
5265: }
1.714 raeburn 5266: }
5267: }
5268: }
5269: }
5270:
1.159 www 5271: # Free bre to public access
5272:
5273: if ($priv eq 'bre') {
1.238 www 5274: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5275: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5276: return 'F';
5277: }
1.238 www 5278: if ($copyright eq 'priv') {
5279: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5280: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5281: return '';
5282: }
5283: }
5284: if ($copyright eq 'domain') {
5285: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5286: unless (($env{'user.domain'} eq $1) ||
5287: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5288: return '';
5289: }
1.262 matthew 5290: }
1.620 albertel 5291: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5292: # Library role, so allow browsing of resources in this domain.
5293: return 'F';
1.238 www 5294: }
1.341 www 5295: if ($copyright eq 'custom') {
5296: unless (&customaccess($priv,$uri)) { return ''; }
5297: }
1.14 www 5298: }
1.264 matthew 5299: # Domain coordinator is trying to create a course
1.620 albertel 5300: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5301: # uri is the requested domain in this case.
5302: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5303: # a role of dc for the domain in question.
1.620 albertel 5304: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5305: }
1.29 www 5306:
1.52 www 5307: my $thisallowed='';
5308: my $statecond=0;
5309: my $courseprivid='';
5310:
1.1039 raeburn 5311: my $ownaccess;
1.1043 raeburn 5312: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5313: if (($priv eq 'bro') && ($env{'user.author'})) {
5314: if ($uri eq '') {
5315: $ownaccess = 1;
5316: } else {
5317: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5318: my $udom = $env{'user.domain'};
5319: my $uname = $env{'user.name'};
5320: if ($uri =~ m{^\Q$udom\E/?$}) {
5321: $ownaccess = 1;
1.1040 raeburn 5322: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5323: unless ($uri =~ m{\.\./}) {
5324: $ownaccess = 1;
5325: }
5326: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5327: my $now = time;
5328: if ($uri =~ m{^([^/]+)/?$}) {
5329: my $adom = $1;
5330: foreach my $key (keys(%env)) {
1.1042 raeburn 5331: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5332: my ($start,$end) = split('.',$env{$key});
5333: if (($now >= $start) && (!$end || $end < $now)) {
5334: $ownaccess = 1;
5335: last;
5336: }
5337: }
5338: }
5339: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5340: my $adom = $1;
5341: my $aname = $2;
1.1042 raeburn 5342: foreach my $role ('ca','aa') {
5343: if ($env{"user.role.$role./$adom/$aname"}) {
5344: my ($start,$end) =
5345: split('.',$env{"user.role.$role./$adom/$aname"});
5346: if (($now >= $start) && (!$end || $end < $now)) {
5347: $ownaccess = 1;
5348: last;
5349: }
1.1039 raeburn 5350: }
5351: }
5352: }
5353: }
5354: }
5355: }
5356: }
5357:
1.52 www 5358: # Course
5359:
1.620 albertel 5360: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5361: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5362: $thisallowed.=$1;
5363: }
1.52 www 5364: }
1.29 www 5365:
1.52 www 5366: # Domain
5367:
1.620 albertel 5368: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5369: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5370: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5371: $thisallowed.=$1;
5372: }
1.12 www 5373: }
1.52 www 5374:
5375: # Course: uri itself is a course
1.66 www 5376: my $courseuri=$uri;
5377: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5378: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5379:
1.620 albertel 5380: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5381: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5382: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5383: $thisallowed.=$1;
5384: }
1.12 www 5385: }
1.29 www 5386:
1.665 albertel 5387: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5388: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5389: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5390: $thisallowed='';
1.671 raeburn 5391: my ($match)=&is_on_map($uri);
5392: if ($match) {
5393: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5394: =~/\Q$priv\E\&([^\:]*)/) {
5395: $thisallowed.=$1;
5396: }
5397: } else {
1.705 albertel 5398: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5399: if ($refuri) {
5400: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5401: $thisallowed='F';
1.671 raeburn 5402: } else {
5403: $refuri=&declutter($refuri);
5404: my ($match) = &is_on_map($refuri);
5405: if ($match) {
5406: $thisallowed='F';
5407: }
1.669 raeburn 5408: }
1.671 raeburn 5409: }
5410: }
1.314 www 5411: }
1.492 albertel 5412:
1.766 albertel 5413: if ($priv eq 'bre'
5414: && $thisallowed ne 'F'
5415: && $thisallowed ne '2'
5416: && &is_portfolio_url($uri)) {
5417: $thisallowed = &portfolio_access($uri);
5418: }
5419:
1.52 www 5420: # Full access at system, domain or course-wide level? Exit.
1.29 www 5421: if ($thisallowed=~/F/) {
5422: return 'F';
5423: }
5424:
1.52 www 5425: # If this is generating or modifying users, exit with special codes
1.29 www 5426:
1.643 www 5427: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5428: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5429: my ($audom,$auname)=split('/',$uri);
1.643 www 5430: # no author name given, so this just checks on the general right to make a co-author in this domain
5431: unless ($auname) { return $thisallowed; }
5432: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5433: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5434: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5435: ($audom ne $env{'request.role.domain'}))) { return ''; }
5436: }
1.52 www 5437: return $thisallowed;
5438: }
5439: #
1.103 harris41 5440: # Gathered so far: system, domain and course wide privileges
1.52 www 5441: #
5442: # Course: See if uri or referer is an individual resource that is part of
5443: # the course
5444:
1.620 albertel 5445: if ($env{'request.course.id'}) {
1.232 www 5446:
1.620 albertel 5447: $courseprivid=$env{'request.course.id'};
5448: if ($env{'request.course.sec'}) {
5449: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5450: }
5451: $courseprivid=~s/\_/\//;
5452: my $checkreferer=1;
1.232 www 5453: my ($match,$cond)=&is_on_map($uri);
5454: if ($match) {
5455: $statecond=$cond;
1.620 albertel 5456: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5457: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5458: $thisallowed.=$1;
5459: $checkreferer=0;
5460: }
1.29 www 5461: }
1.83 www 5462:
1.148 www 5463: if ($checkreferer) {
1.620 albertel 5464: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5465: unless ($refuri) {
1.800 albertel 5466: foreach my $key (keys(%env)) {
5467: if ($key=~/^httpref\..*\*/) {
5468: my $pattern=$key;
1.156 www 5469: $pattern=~s/^httpref\.\/res\///;
1.148 www 5470: $pattern=~s/\*/\[\^\/\]\+/g;
5471: $pattern=~s/\//\\\//g;
1.152 www 5472: if ($orguri=~/$pattern/) {
1.800 albertel 5473: $refuri=$env{$key};
1.148 www 5474: }
5475: }
1.191 harris41 5476: }
1.148 www 5477: }
1.232 www 5478:
1.148 www 5479: if ($refuri) {
1.152 www 5480: $refuri=&declutter($refuri);
1.232 www 5481: my ($match,$cond)=&is_on_map($refuri);
5482: if ($match) {
5483: my $refstatecond=$cond;
1.620 albertel 5484: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5485: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5486: $thisallowed.=$1;
1.53 www 5487: $uri=$refuri;
5488: $statecond=$refstatecond;
1.52 www 5489: }
5490: }
1.148 www 5491: }
1.29 www 5492: }
1.52 www 5493: }
1.29 www 5494:
1.52 www 5495: #
1.103 harris41 5496: # Gathered now: all privileges that could apply, and condition number
1.52 www 5497: #
5498: #
5499: # Full or no access?
5500: #
1.29 www 5501:
1.52 www 5502: if ($thisallowed=~/F/) {
5503: return 'F';
5504: }
1.29 www 5505:
1.52 www 5506: unless ($thisallowed) {
5507: return '';
5508: }
1.29 www 5509:
1.52 www 5510: # Restrictions exist, deal with them
5511: #
5512: # C:according to course preferences
5513: # R:according to resource settings
5514: # L:unless locked
5515: # X:according to user session state
5516: #
5517:
5518: # Possibly locked functionality, check all courses
1.54 www 5519: # Locks might take effect only after 10 minutes cache expiration for other
5520: # courses, and 2 minutes for current course
1.52 www 5521:
5522: my $envkey;
5523: if ($thisallowed=~/L/) {
1.1000 raeburn 5524: foreach $envkey (keys(%env)) {
1.54 www 5525: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5526: my $courseid=$2;
5527: my $roleid=$1.'.'.$2;
1.92 www 5528: $courseid=~s/^\///;
1.54 www 5529: my $expiretime=600;
1.620 albertel 5530: if ($env{'request.role'} eq $roleid) {
1.54 www 5531: $expiretime=120;
5532: }
5533: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5534: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5535: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5536: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5537: }
1.620 albertel 5538: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5539: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5540: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5541: &log($env{'user.domain'},$env{'user.name'},
5542: $env{'user.home'},
1.57 www 5543: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5544: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5545: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5546: return '';
5547: }
5548: }
1.620 albertel 5549: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5550: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5551: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5552: &log($env{'user.domain'},$env{'user.name'},
5553: $env{'user.home'},
1.57 www 5554: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5555: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5556: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5557: return '';
5558: }
5559: }
5560: }
1.29 www 5561: }
1.52 www 5562: }
5563:
5564: #
5565: # Rest of the restrictions depend on selected course
5566: #
5567:
1.620 albertel 5568: unless ($env{'request.course.id'}) {
1.766 albertel 5569: if ($thisallowed eq 'A') {
5570: return 'A';
1.814 raeburn 5571: } elsif ($thisallowed eq 'B') {
5572: return 'B';
1.766 albertel 5573: } else {
5574: return '1';
5575: }
1.52 www 5576: }
1.29 www 5577:
1.52 www 5578: #
5579: # Now user is definitely in a course
5580: #
1.53 www 5581:
5582:
5583: # Course preferences
5584:
5585: if ($thisallowed=~/C/) {
1.620 albertel 5586: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5587: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5588: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5589: =~/\Q$rolecode\E/) {
1.689 albertel 5590: if ($priv ne 'pch') {
5591: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5592: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5593: $env{'request.course.id'});
5594: }
1.237 www 5595: return '';
5596: }
5597:
1.620 albertel 5598: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5599: =~/\Q$unamedom\E/) {
1.689 albertel 5600: if ($priv ne 'pch') {
5601: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5602: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5603: $env{'request.course.id'});
5604: }
1.54 www 5605: return '';
5606: }
1.53 www 5607: }
5608:
5609: # Resource preferences
5610:
5611: if ($thisallowed=~/R/) {
1.620 albertel 5612: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5613: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5614: if ($priv ne 'pch') {
5615: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5616: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5617: }
5618: return '';
1.54 www 5619: }
1.53 www 5620: }
1.30 www 5621:
1.246 www 5622: # Restricted by state or randomout?
1.30 www 5623:
1.52 www 5624: if ($thisallowed=~/X/) {
1.620 albertel 5625: if ($env{'acc.randomout'}) {
1.579 albertel 5626: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5627: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5628: return '';
5629: }
1.247 www 5630: }
5631: if (&condval($statecond)) {
1.52 www 5632: return '2';
5633: } else {
5634: return '';
5635: }
5636: }
1.30 www 5637:
1.766 albertel 5638: if ($thisallowed eq 'A') {
5639: return 'A';
1.814 raeburn 5640: } elsif ($thisallowed eq 'B') {
5641: return 'B';
1.766 albertel 5642: }
1.52 www 5643: return 'F';
1.232 www 5644: }
5645:
1.710 albertel 5646: sub split_uri_for_cond {
5647: my $uri=&deversion(&declutter(shift));
5648: my @uriparts=split(/\//,$uri);
5649: my $filename=pop(@uriparts);
5650: my $pathname=join('/',@uriparts);
5651: return ($pathname,$filename);
5652: }
1.232 www 5653: # --------------------------------------------------- Is a resource on the map?
5654:
5655: sub is_on_map {
1.710 albertel 5656: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5657: #Trying to find the conditional for the file
1.620 albertel 5658: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5659: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5660: if ($match) {
1.289 bowersj2 5661: return (1,$1);
5662: } else {
1.434 www 5663: return (0,0);
1.289 bowersj2 5664: }
1.12 www 5665: }
5666:
1.427 www 5667: # --------------------------------------------------------- Get symb from alias
5668:
5669: sub get_symb_from_alias {
5670: my $symb=shift;
5671: my ($map,$resid,$url)=&decode_symb($symb);
5672: # Already is a symb
5673: if ($url) { return $symb; }
5674: # Must be an alias
5675: my $aliassymb='';
5676: my %bighash;
1.620 albertel 5677: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5678: &GDBM_READER(),0640)) {
5679: my $rid=$bighash{'mapalias_'.$symb};
5680: if ($rid) {
5681: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5682: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5683: $resid,$bighash{'src_'.$rid});
1.427 www 5684: }
5685: untie %bighash;
5686: }
5687: return $aliassymb;
5688: }
5689:
1.12 www 5690: # ----------------------------------------------------------------- Define Role
5691:
5692: sub definerole {
5693: if (allowed('mcr','/')) {
5694: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5695: foreach my $role (split(':',$sysrole)) {
5696: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5697: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5698: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5699: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5700: return "refused:s:$crole&$cqual";
5701: }
5702: }
1.191 harris41 5703: }
1.800 albertel 5704: foreach my $role (split(':',$domrole)) {
5705: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5706: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5707: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5708: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5709: return "refused:d:$crole&$cqual";
5710: }
5711: }
1.191 harris41 5712: }
1.800 albertel 5713: foreach my $role (split(':',$courole)) {
5714: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5715: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5716: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5717: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5718: return "refused:c:$crole&$cqual";
5719: }
5720: }
1.191 harris41 5721: }
1.620 albertel 5722: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5723: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5724: "rolesdef_$rolename=".
5725: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5726: return reply($command,$env{'user.home'});
1.12 www 5727: } else {
5728: return 'refused';
5729: }
1.105 harris41 5730: }
5731:
5732: # ---------------- Make a metadata query against the network of library servers
5733:
5734: sub metadata_query {
1.244 matthew 5735: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5736: my %rhash;
1.845 albertel 5737: my %libserv = &all_library();
1.244 matthew 5738: my @server_list = (defined($server_array) ? @$server_array
5739: : keys(%libserv) );
5740: for my $server (@server_list) {
1.118 harris41 5741: unless ($custom or $customshow) {
5742: my $reply=&reply("querysend:".&escape($query),$server);
5743: $rhash{$server}=$reply;
5744: }
5745: else {
5746: my $reply=&reply("querysend:".&escape($query).':'.
5747: &escape($custom).':'.&escape($customshow),
5748: $server);
5749: $rhash{$server}=$reply;
5750: }
1.112 harris41 5751: }
1.118 harris41 5752: return \%rhash;
1.240 www 5753: }
5754:
5755: # ----------------------------------------- Send log queries and wait for reply
5756:
5757: sub log_query {
5758: my ($uname,$udom,$query,%filters)=@_;
5759: my $uhome=&homeserver($uname,$udom);
5760: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5761: my $uhost=&hostname($uhome);
1.800 albertel 5762: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5763: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5764: $uhome);
1.479 albertel 5765: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5766: return get_query_reply($queryid);
5767: }
5768:
1.818 raeburn 5769: # -------------------------- Update MySQL table for portfolio file
5770:
5771: sub update_portfolio_table {
1.821 raeburn 5772: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5773: if ($group ne '') {
5774: $file_name =~s /^\Q$group\E//;
5775: }
1.818 raeburn 5776: my $homeserver = &homeserver($uname,$udom);
5777: my $queryid=
1.821 raeburn 5778: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5779: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5780: my $reply = &get_query_reply($queryid);
5781: return $reply;
5782: }
5783:
1.899 raeburn 5784: # -------------------------- Update MySQL allusers table
5785:
5786: sub update_allusers_table {
5787: my ($uname,$udom,$names) = @_;
5788: my $homeserver = &homeserver($uname,$udom);
5789: my $queryid=
5790: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5791: 'lastname='.&escape($names->{'lastname'}).'%%'.
5792: 'firstname='.&escape($names->{'firstname'}).'%%'.
5793: 'middlename='.&escape($names->{'middlename'}).'%%'.
5794: 'generation='.&escape($names->{'generation'}).'%%'.
5795: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5796: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5797: return;
1.899 raeburn 5798: }
5799:
1.508 raeburn 5800: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5801:
5802: sub fetch_enrollment_query {
1.511 raeburn 5803: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5804: my $homeserver;
1.547 raeburn 5805: my $maxtries = 1;
1.508 raeburn 5806: if ($context eq 'automated') {
5807: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5808: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5809: } else {
5810: $homeserver = &homeserver($cnum,$dom);
5811: }
1.838 albertel 5812: my $host=&hostname($homeserver);
1.506 raeburn 5813: my $cmd = '';
1.1000 raeburn 5814: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5815: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5816: }
5817: $cmd =~ s/%%$//;
5818: $cmd = &escape($cmd);
5819: my $query = 'fetchenrollment';
1.620 albertel 5820: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5821: unless ($queryid=~/^\Q$host\E\_/) {
5822: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5823: return 'error: '.$queryid;
5824: }
1.506 raeburn 5825: my $reply = &get_query_reply($queryid);
1.547 raeburn 5826: my $tries = 1;
5827: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5828: $reply = &get_query_reply($queryid);
5829: $tries ++;
5830: }
1.526 raeburn 5831: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5832: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5833: } else {
1.901 albertel 5834: my @responses = split(/:/,$reply);
1.515 raeburn 5835: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5836: foreach my $line (@responses) {
5837: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5838: $$replyref{$key} = $value;
5839: }
5840: } else {
1.506 raeburn 5841: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5842: foreach my $line (@responses) {
5843: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5844: $$replyref{$key} = $value;
5845: if ($value > 0) {
1.800 albertel 5846: foreach my $item (@{$$affiliatesref{$key}}) {
5847: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5848: my $destname = $pathname.'/'.$filename;
5849: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5850: if ($xml_classlist =~ /^error/) {
5851: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5852: } else {
1.506 raeburn 5853: if ( open(FILE,">$destname") ) {
5854: print FILE &unescape($xml_classlist);
5855: close(FILE);
1.526 raeburn 5856: } else {
5857: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5858: }
5859: }
5860: }
5861: }
5862: }
5863: }
5864: return 'ok';
5865: }
5866: return 'error';
5867: }
5868:
1.242 www 5869: sub get_query_reply {
5870: my $queryid=shift;
1.240 www 5871: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5872: my $reply='';
5873: for (1..100) {
5874: sleep 2;
5875: if (-e $replyfile.'.end') {
1.448 albertel 5876: if (open(my $fh,$replyfile)) {
1.904 albertel 5877: $reply = join('',<$fh>);
5878: close($fh);
1.240 www 5879: } else { return 'error: reply_file_error'; }
1.242 www 5880: return &unescape($reply);
5881: }
1.240 www 5882: }
1.242 www 5883: return 'timeout:'.$queryid;
1.240 www 5884: }
5885:
5886: sub courselog_query {
1.241 www 5887: #
5888: # possible filters:
5889: # url: url or symb
5890: # username
5891: # domain
5892: # action: view, submit, grade
5893: # start: timestamp
5894: # end: timestamp
5895: #
1.240 www 5896: my (%filters)=@_;
1.620 albertel 5897: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5898: if ($filters{'url'}) {
5899: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5900: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5901: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5902: }
1.620 albertel 5903: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5904: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5905: return &log_query($cname,$cdom,'courselog',%filters);
5906: }
5907:
5908: sub userlog_query {
1.858 raeburn 5909: #
5910: # possible filters:
5911: # action: log check role
5912: # start: timestamp
5913: # end: timestamp
5914: #
1.240 www 5915: my ($uname,$udom,%filters)=@_;
5916: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5917: }
5918:
1.506 raeburn 5919: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5920:
5921: sub auto_run {
1.508 raeburn 5922: my ($cnum,$cdom) = @_;
1.876 raeburn 5923: my $response = 0;
5924: my $settings;
5925: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5926: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5927: $settings = $domconfig{'autoenroll'};
5928: if ($settings->{'run'} eq '1') {
5929: $response = 1;
5930: }
5931: } else {
1.934 raeburn 5932: my $homeserver;
5933: if (&is_course($cdom,$cnum)) {
5934: $homeserver = &homeserver($cnum,$cdom);
5935: } else {
5936: $homeserver = &domain($cdom,'primary');
5937: }
5938: if ($homeserver ne 'no_host') {
5939: $response = &reply('autorun:'.$cdom,$homeserver);
5940: }
1.876 raeburn 5941: }
1.506 raeburn 5942: return $response;
5943: }
1.776 albertel 5944:
1.506 raeburn 5945: sub auto_get_sections {
1.508 raeburn 5946: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5947: my $homeserver;
5948: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5949: $homeserver = &homeserver($cnum,$cdom);
5950: }
5951: if (!defined($homeserver)) {
5952: if ($cdom =~ /^$match_domain$/) {
5953: $homeserver = &domain($cdom,'primary');
5954: }
5955: }
5956: my @secs;
5957: if (defined($homeserver)) {
5958: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5959: unless ($response eq 'refused') {
5960: @secs = split(/:/,$response);
5961: }
1.506 raeburn 5962: }
5963: return @secs;
5964: }
1.776 albertel 5965:
1.506 raeburn 5966: sub auto_new_course {
1.508 raeburn 5967: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5968: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5969: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5970: return $response;
5971: }
1.776 albertel 5972:
1.506 raeburn 5973: sub auto_validate_courseID {
1.508 raeburn 5974: my ($cnum,$cdom,$inst_course_id) = @_;
5975: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5976: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5977: return $response;
5978: }
1.776 albertel 5979:
1.1007 raeburn 5980: sub auto_validate_instcode {
1.1020 raeburn 5981: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5982: my ($homeserver,$response);
5983: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5984: $homeserver = &homeserver($cnum,$cdom);
5985: }
5986: if (!defined($homeserver)) {
5987: if ($cdom =~ /^$match_domain$/) {
5988: $homeserver = &domain($cdom,'primary');
5989: }
5990: }
1.1065 raeburn 5991: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5992: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5993: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5994: return ($outcome,$description);
1.1007 raeburn 5995: }
5996:
1.506 raeburn 5997: sub auto_create_password {
1.873 raeburn 5998: my ($cnum,$cdom,$authparam,$udom) = @_;
5999: my ($homeserver,$response);
1.506 raeburn 6000: my $create_passwd = 0;
6001: my $authchk = '';
1.873 raeburn 6002: if ($udom =~ /^$match_domain$/) {
6003: $homeserver = &domain($udom,'primary');
6004: }
6005: if ($homeserver eq '') {
6006: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6007: $homeserver = &homeserver($cnum,$cdom);
6008: }
6009: }
6010: if ($homeserver eq '') {
6011: $authchk = 'nodomain';
1.506 raeburn 6012: } else {
1.873 raeburn 6013: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6014: if ($response eq 'refused') {
6015: $authchk = 'refused';
6016: } else {
1.901 albertel 6017: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6018: }
1.506 raeburn 6019: }
6020: return ($authparam,$create_passwd,$authchk);
6021: }
6022:
1.706 raeburn 6023: sub auto_photo_permission {
6024: my ($cnum,$cdom,$students) = @_;
6025: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6026: my ($outcome,$perm_reqd,$conditions) =
6027: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6028: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6029: return (undef,undef);
6030: }
1.706 raeburn 6031: return ($outcome,$perm_reqd,$conditions);
6032: }
6033:
6034: sub auto_checkphotos {
6035: my ($uname,$udom,$pid) = @_;
6036: my $homeserver = &homeserver($uname,$udom);
6037: my ($result,$resulttype);
6038: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6039: &escape($uname).':'.&escape($pid),
6040: $homeserver));
1.709 albertel 6041: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6042: return (undef,undef);
6043: }
1.706 raeburn 6044: if ($outcome) {
6045: ($result,$resulttype) = split(/:/,$outcome);
6046: }
6047: return ($result,$resulttype);
6048: }
6049:
6050: sub auto_photochoice {
6051: my ($cnum,$cdom) = @_;
6052: my $homeserver = &homeserver($cnum,$cdom);
6053: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6054: &escape($cdom),
6055: $homeserver)));
1.709 albertel 6056: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6057: return (undef,undef);
6058: }
1.706 raeburn 6059: return ($update,$comment);
6060: }
6061:
6062: sub auto_photoupdate {
6063: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6064: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6065: my $host=&hostname($homeserver);
1.706 raeburn 6066: my $cmd = '';
6067: my $maxtries = 1;
1.800 albertel 6068: foreach my $affiliate (keys(%{$affiliatesref})) {
6069: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6070: }
6071: $cmd =~ s/%%$//;
6072: $cmd = &escape($cmd);
6073: my $query = 'institutionalphotos';
6074: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6075: unless ($queryid=~/^\Q$host\E\_/) {
6076: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6077: return 'error: '.$queryid;
6078: }
6079: my $reply = &get_query_reply($queryid);
6080: my $tries = 1;
6081: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6082: $reply = &get_query_reply($queryid);
6083: $tries ++;
6084: }
6085: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6086: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6087: } else {
6088: my @responses = split(/:/,$reply);
6089: my $outcome = shift(@responses);
6090: foreach my $item (@responses) {
6091: my ($key,$value) = split(/=/,$item);
6092: $$photo{$key} = $value;
6093: }
6094: return $outcome;
6095: }
6096: return 'error';
6097: }
6098:
1.521 raeburn 6099: sub auto_instcode_format {
1.793 albertel 6100: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6101: $cat_order) = @_;
1.521 raeburn 6102: my $courses = '';
1.772 raeburn 6103: my @homeservers;
1.521 raeburn 6104: if ($caller eq 'global') {
1.841 albertel 6105: my %servers = &get_servers($codedom,'library');
6106: foreach my $tryserver (keys(%servers)) {
6107: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6108: push(@homeservers,$tryserver);
6109: }
1.584 raeburn 6110: }
1.1022 raeburn 6111: } elsif ($caller eq 'requests') {
6112: if ($codedom =~ /^$match_domain$/) {
6113: my $chome = &domain($codedom,'primary');
6114: unless ($chome eq 'no_host') {
6115: push(@homeservers,$chome);
6116: }
6117: }
1.521 raeburn 6118: } else {
1.772 raeburn 6119: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6120: }
1.793 albertel 6121: foreach my $code (keys(%{$instcodes})) {
6122: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6123: }
6124: chop($courses);
1.772 raeburn 6125: my $ok_response = 0;
6126: my $response;
6127: while (@homeservers > 0 && $ok_response == 0) {
6128: my $server = shift(@homeservers);
6129: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6130: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6131: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6132: split(/:/,$response);
1.772 raeburn 6133: %{$codes} = (%{$codes},&str2hash($codes_str));
6134: push(@{$codetitles},&str2array($codetitles_str));
6135: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6136: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6137: $ok_response = 1;
6138: }
6139: }
6140: if ($ok_response) {
1.521 raeburn 6141: return 'ok';
1.772 raeburn 6142: } else {
6143: return $response;
1.521 raeburn 6144: }
6145: }
6146:
1.792 raeburn 6147: sub auto_instcode_defaults {
6148: my ($domain,$returnhash,$code_order) = @_;
6149: my @homeservers;
1.841 albertel 6150:
6151: my %servers = &get_servers($domain,'library');
6152: foreach my $tryserver (keys(%servers)) {
6153: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6154: push(@homeservers,$tryserver);
6155: }
1.792 raeburn 6156: }
1.841 albertel 6157:
1.792 raeburn 6158: my $response;
1.841 albertel 6159: foreach my $server (@homeservers) {
1.792 raeburn 6160: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6161: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6162:
6163: foreach my $pair (split(/\&/,$response)) {
6164: my ($name,$value)=split(/\=/,$pair);
6165: if ($name eq 'code_order') {
6166: @{$code_order} = split(/\&/,&unescape($value));
6167: } else {
6168: $returnhash->{&unescape($name)}=&unescape($value);
6169: }
6170: }
6171: return 'ok';
1.792 raeburn 6172: }
1.841 albertel 6173:
6174: return $response;
1.1003 raeburn 6175: }
6176:
6177: sub auto_possible_instcodes {
1.1007 raeburn 6178: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6179: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6180: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6181: return;
6182: }
1.1003 raeburn 6183: my (@homeservers,$uhome);
6184: if (defined(&domain($domain,'primary'))) {
6185: $uhome=&domain($domain,'primary');
6186: push(@homeservers,&domain($domain,'primary'));
6187: } else {
6188: my %servers = &get_servers($domain,'library');
6189: foreach my $tryserver (keys(%servers)) {
6190: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6191: push(@homeservers,$tryserver);
6192: }
6193: }
6194: }
6195: my $response;
6196: foreach my $server (@homeservers) {
6197: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6198: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6199: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6200: split(':',$response);
6201: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6202: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6203: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6204: my ($name,$value)=split('=',$item);
6205: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6206: }
6207: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6208: my ($name,$value)=split('=',$item);
6209: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6210: }
6211: return 'ok';
6212: }
6213: return $response;
6214: }
1.792 raeburn 6215:
1.1010 raeburn 6216: sub auto_courserequest_checks {
6217: my ($dom) = @_;
1.1020 raeburn 6218: my ($homeserver,%validations);
6219: if ($dom =~ /^$match_domain$/) {
6220: $homeserver = &domain($dom,'primary');
6221: }
6222: unless ($homeserver eq 'no_host') {
6223: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6224: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6225: my @items = split(/&/,$response);
6226: foreach my $item (@items) {
6227: my ($key,$value) = split('=',$item);
6228: $validations{&unescape($key)} = &thaw_unescape($value);
6229: }
6230: }
6231: }
1.1010 raeburn 6232: return %validations;
6233: }
6234:
1.1020 raeburn 6235: sub auto_courserequest_validation {
6236: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6237: my ($homeserver,$response);
6238: if ($dom =~ /^$match_domain$/) {
6239: $homeserver = &domain($dom,'primary');
6240: }
6241: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6242:
1.1020 raeburn 6243: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6244: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6245: ':'.&escape($instcode).':'.&escape($instseclist),
6246: $homeserver));
6247: }
6248: return $response;
6249: }
6250:
1.777 albertel 6251: sub auto_validate_class_sec {
1.918 raeburn 6252: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6253: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6254: my $ownerlist;
6255: if (ref($owners) eq 'ARRAY') {
6256: $ownerlist = join(',',@{$owners});
6257: } else {
6258: $ownerlist = $owners;
6259: }
1.773 raeburn 6260: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6261: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6262: return $response;
6263: }
6264:
1.679 raeburn 6265: # ------------------------------------------------------- Course Group routines
6266:
6267: sub get_coursegroups {
1.809 raeburn 6268: my ($cdom,$cnum,$group,$namespace) = @_;
6269: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6270: }
6271:
1.679 raeburn 6272: sub modify_coursegroup {
6273: my ($cdom,$cnum,$groupsettings) = @_;
6274: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6275: }
6276:
1.809 raeburn 6277: sub toggle_coursegroup_status {
6278: my ($cdom,$cnum,$group,$action) = @_;
6279: my ($from_namespace,$to_namespace);
6280: if ($action eq 'delete') {
6281: $from_namespace = 'coursegroups';
6282: $to_namespace = 'deleted_groups';
6283: } else {
6284: $from_namespace = 'deleted_groups';
6285: $to_namespace = 'coursegroups';
6286: }
6287: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6288: if (my $tmp = &error(%curr_group)) {
6289: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6290: return ('read error',$tmp);
6291: } else {
6292: my %savedsettings = %curr_group;
1.809 raeburn 6293: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6294: my $deloutcome;
6295: if ($result eq 'ok') {
1.809 raeburn 6296: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6297: } else {
6298: return ('write error',$result);
6299: }
6300: if ($deloutcome eq 'ok') {
6301: return 'ok';
6302: } else {
6303: return ('delete error',$deloutcome);
6304: }
6305: }
6306: }
6307:
1.679 raeburn 6308: sub modify_group_roles {
1.957 raeburn 6309: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6310: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6311: my $role = 'gr/'.&escape($userprivs);
6312: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6313: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6314: if ($result eq 'ok') {
6315: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6316: }
1.679 raeburn 6317: return $result;
6318: }
6319:
6320: sub modify_coursegroup_membership {
6321: my ($cdom,$cnum,$membership) = @_;
6322: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6323: return $result;
6324: }
6325:
1.682 raeburn 6326: sub get_active_groups {
6327: my ($udom,$uname,$cdom,$cnum) = @_;
6328: my $now = time;
6329: my %groups = ();
6330: foreach my $key (keys(%env)) {
1.811 albertel 6331: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6332: my ($start,$end) = split(/\./,$env{$key});
6333: if (($end!=0) && ($end<$now)) { next; }
6334: if (($start!=0) && ($start>$now)) { next; }
6335: if ($1 eq $cdom && $2 eq $cnum) {
6336: $groups{$3} = $env{$key} ;
6337: }
6338: }
6339: }
6340: return %groups;
6341: }
6342:
1.683 raeburn 6343: sub get_group_membership {
6344: my ($cdom,$cnum,$group) = @_;
6345: return(&dump('groupmembership',$cdom,$cnum,$group));
6346: }
6347:
6348: sub get_users_groups {
6349: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6350: my @usersgroups;
1.683 raeburn 6351: my $cachetime=1800;
6352:
6353: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6354: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6355: if (defined($cached)) {
1.734 albertel 6356: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6357: } else {
6358: $grouplist = '';
1.816 raeburn 6359: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6360: my $extra = &freeze_escape({'skipcheck' => 1});
6361: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6362: my $access_end = $env{'course.'.$courseid.
6363: '.default_enrollment_end_date'};
6364: my $now = time;
6365: foreach my $key (keys(%roleshash)) {
6366: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6367: my $group = $1;
6368: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6369: my $start = $2;
6370: my $end = $1;
6371: if ($start == -1) { next; } # deleted from group
6372: if (($start!=0) && ($start>$now)) { next; }
6373: if (($end!=0) && ($end<$now)) {
6374: if ($access_end && $access_end < $now) {
6375: if ($access_end - $end < 86400) {
6376: push(@usersgroups,$group);
1.733 raeburn 6377: }
6378: }
1.817 raeburn 6379: next;
1.733 raeburn 6380: }
1.817 raeburn 6381: push(@usersgroups,$group);
1.683 raeburn 6382: }
6383: }
6384: }
1.817 raeburn 6385: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6386: $grouplist = join(':',@usersgroups);
6387: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6388: }
1.733 raeburn 6389: return @usersgroups;
1.683 raeburn 6390: }
6391:
6392: sub devalidate_getgroups_cache {
6393: my ($udom,$uname,$cdom,$cnum)=@_;
6394: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6395:
1.683 raeburn 6396: my $hashid="$udom:$uname:$courseid";
6397: &devalidate_cache_new('getgroups',$hashid);
6398: }
6399:
1.12 www 6400: # ------------------------------------------------------------------ Plain Text
6401:
6402: sub plaintext {
1.988 raeburn 6403: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6404: if ($short =~ m{^cr/}) {
1.758 albertel 6405: return (split('/',$short))[-1];
6406: }
1.742 raeburn 6407: if (!defined($cid)) {
6408: $cid = $env{'request.course.id'};
6409: }
6410: my %rolenames = (
1.1008 raeburn 6411: Course => 'std',
6412: Community => 'alt1',
1.742 raeburn 6413: );
1.1037 raeburn 6414: if ($cid ne '') {
6415: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6416: unless ($forcedefault) {
6417: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6418: &Apache::lonlocal::mt_escape(\$roletext);
6419: return &Apache::lonlocal::mt($roletext);
6420: }
6421: }
6422: }
6423: if ((defined($type)) && (defined($rolenames{$type})) &&
6424: (defined($rolenames{$type})) &&
6425: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6426: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6427: } elsif ($cid ne '') {
6428: my $crstype = $env{'course.'.$cid.'.type'};
6429: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6430: (defined($prp{$short}{$rolenames{$crstype}}))) {
6431: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6432: }
1.742 raeburn 6433: }
1.1037 raeburn 6434: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6435: }
6436:
6437: # ----------------------------------------------------------------- Assign Role
6438:
6439: sub assignrole {
1.957 raeburn 6440: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6441: $context)=@_;
1.21 www 6442: my $mrole;
6443: if ($role =~ /^cr\//) {
1.393 www 6444: my $cwosec=$url;
1.811 albertel 6445: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6446: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6447: my $refused = 1;
6448: if ($context eq 'requestcourses') {
6449: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6450: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6451: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6452: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6453: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6454: if ($crsenv{'internal.courseowner'} eq
6455: $env{'user.name'}.':'.$env{'user.domain'}) {
6456: $refused = '';
6457: }
6458: }
6459: }
6460: }
6461: }
6462: if ($refused) {
6463: &logthis('Refused custom assignrole: '.
6464: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6465: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6466: return 'refused';
6467: }
1.104 www 6468: }
1.21 www 6469: $mrole='cr';
1.678 raeburn 6470: } elsif ($role =~ /^gr\//) {
6471: my $cwogrp=$url;
1.811 albertel 6472: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6473: unless (&allowed('mdg',$cwogrp)) {
6474: &logthis('Refused group assignrole: '.
6475: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6476: $env{'user.name'}.' at '.$env{'user.domain'});
6477: return 'refused';
6478: }
6479: $mrole='gr';
1.21 www 6480: } else {
1.82 www 6481: my $cwosec=$url;
1.811 albertel 6482: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6483: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6484: my $refused;
6485: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6486: if (!(&allowed('c'.$role,$url))) {
6487: $refused = 1;
6488: }
6489: } else {
6490: $refused = 1;
6491: }
1.947 raeburn 6492: if ($refused) {
1.1045 raeburn 6493: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6494: if (!$selfenroll && $context eq 'course') {
6495: my %crsenv;
6496: if ($role eq 'cc' || $role eq 'co') {
6497: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6498: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6499: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6500: if ($crsenv{'internal.courseowner'} eq
6501: $env{'user.name'}.':'.$env{'user.domain'}) {
6502: $refused = '';
6503: }
6504: }
6505: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6506: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6507: if ($crsenv{'internal.courseowner'} eq
6508: $env{'user.name'}.':'.$env{'user.domain'}) {
6509: $refused = '';
6510: }
6511: }
6512: }
6513: }
6514: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6515: $refused = '';
1.1017 raeburn 6516: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6517: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6518: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6519: my $wrongcc;
6520: if ($cnum =~ /^$match_community$/) {
6521: $wrongcc = 1 if ($role eq 'cc');
6522: } else {
6523: $wrongcc = 1 if ($role eq 'co');
6524: }
6525: unless ($wrongcc) {
6526: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6527: if ($crsenv{'internal.courseowner'} eq
6528: $env{'user.name'}.':'.$env{'user.domain'}) {
6529: $refused = '';
6530: }
1.1017 raeburn 6531: }
6532: }
6533: }
6534: if ($refused) {
1.947 raeburn 6535: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6536: ' '.$role.' '.$end.' '.$start.' by '.
6537: $env{'user.name'}.' at '.$env{'user.domain'});
6538: return 'refused';
6539: }
1.932 raeburn 6540: }
1.104 www 6541: }
1.21 www 6542: $mrole=$role;
6543: }
1.620 albertel 6544: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6545: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6546: if ($end) { $command.='_'.$end; }
1.21 www 6547: if ($start) {
6548: if ($end) {
1.81 www 6549: $command.='_'.$start;
1.21 www 6550: } else {
1.81 www 6551: $command.='_0_'.$start;
1.21 www 6552: }
6553: }
1.739 raeburn 6554: my $origstart = $start;
6555: my $origend = $end;
1.957 raeburn 6556: my $delflag;
1.357 www 6557: # actually delete
6558: if ($deleteflag) {
1.373 www 6559: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6560: # modify command to delete the role
1.620 albertel 6561: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6562: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6563: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6564: # set start and finish to negative values for userrolelog
6565: $start=-1;
6566: $end=-1;
1.957 raeburn 6567: $delflag = 1;
1.357 www 6568: }
6569: }
6570: # send command
1.349 www 6571: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6572: # log new user role if status is ok
1.349 www 6573: if ($answer eq 'ok') {
1.663 raeburn 6574: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6575: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6576: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6577: unless ($role =~ /^gr/) {
6578: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6579: $origstart,$selfenroll,$context);
1.739 raeburn 6580: }
1.1053 raeburn 6581: if ($role eq 'cc') {
6582: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6583: }
1.349 www 6584: }
6585: return $answer;
1.169 harris41 6586: }
6587:
1.1053 raeburn 6588: sub autoupdate_coowners {
6589: my ($url,$end,$start,$uname,$udom) = @_;
6590: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6591: if (($cdom ne '') && ($cnum ne '')) {
6592: my $now = time;
6593: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6594: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6595: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6596: my $instcode = $coursehash{'internal.coursecode'};
6597: if ($instcode ne '') {
1.1056 raeburn 6598: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6599: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6600: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6601: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6602: if ($result eq 'valid') {
6603: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6604: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6605: push(@newcoowners,$coowner);
6606: }
6607: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6608: push(@newcoowners,$uname.':'.$udom);
6609: }
6610: @newcoowners = sort(@newcoowners);
6611: } else {
6612: push(@newcoowners,$uname.':'.$udom);
6613: }
6614: } else {
6615: if ($coursehash{'internal.co-owners'}) {
6616: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6617: unless ($coowner eq $uname.':'.$udom) {
6618: push(@newcoowners,$coowner);
6619: }
6620: }
6621: unless (@newcoowners > 0) {
6622: $delcoowners = 1;
6623: $coowners = '';
6624: }
6625: }
6626: }
6627: if (@newcoowners || $delcoowners) {
6628: &store_coowners($cdom,$cnum,$coursehash{'home'},
6629: $delcoowners,@newcoowners);
6630: }
6631: }
6632: }
6633: }
6634: }
6635: }
6636: }
6637:
6638: sub store_coowners {
6639: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6640: my $cid = $cdom.'_'.$cnum;
6641: my ($coowners,$delresult,$putresult);
6642: if (@newcoowners) {
6643: $coowners = join(',',@newcoowners);
6644: my %coownershash = (
6645: 'internal.co-owners' => $coowners,
6646: );
6647: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6648: if ($putresult eq 'ok') {
6649: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6650: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6651: }
6652: }
6653: }
6654: if ($delcoowners) {
6655: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6656: if ($delresult eq 'ok') {
6657: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6658: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6659: }
6660: }
6661: }
6662: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6663: my %crsinfo =
6664: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6665: if (ref($crsinfo{$cid}) eq 'HASH') {
6666: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6667: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6668: }
6669: }
6670: }
6671:
1.169 harris41 6672: # -------------------------------------------------- Modify user authentication
1.197 www 6673: # Overrides without validation
6674:
1.169 harris41 6675: sub modifyuserauth {
6676: my ($udom,$uname,$umode,$upass)=@_;
6677: my $uhome=&homeserver($uname,$udom);
1.197 www 6678: unless (&allowed('mau',$udom)) { return 'refused'; }
6679: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6680: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6681: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6682: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6683: &escape($upass),$uhome);
1.620 albertel 6684: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6685: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6686: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6687: &log($udom,,$uname,$uhome,
1.620 albertel 6688: 'Authentication changed by '.$env{'user.domain'}.', '.
6689: $env{'user.name'}.', '.$umode.
1.197 www 6690: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6691: unless ($reply eq 'ok') {
1.197 www 6692: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6693: return 'error: '.$reply;
6694: }
1.170 harris41 6695: return 'ok';
1.80 www 6696: }
6697:
1.81 www 6698: # --------------------------------------------------------------- Modify a user
1.80 www 6699:
1.81 www 6700: sub modifyuser {
1.206 matthew 6701: my ($udom, $uname, $uid,
6702: $umode, $upass, $first,
6703: $middle, $last, $gene,
1.1058 raeburn 6704: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6705: $udom= &LONCAPA::clean_domain($udom);
6706: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6707: my $showcandelete = 'none';
6708: if (ref($candelete) eq 'ARRAY') {
6709: if (@{$candelete} > 0) {
6710: $showcandelete = join(', ',@{$candelete});
6711: }
6712: }
1.81 www 6713: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6714: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6715: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6716: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6717: ' desiredhome not specified').
1.620 albertel 6718: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6719: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6720: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6721: my $newuser;
6722: if ($uhome eq 'no_host') {
6723: $newuser = 1;
6724: }
1.80 www 6725: # ----------------------------------------------------------------- Create User
1.406 albertel 6726: if (($uhome eq 'no_host') &&
6727: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6728: my $unhome='';
1.844 albertel 6729: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6730: $unhome = $desiredhome;
1.620 albertel 6731: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6732: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6733: } else { # load balancing routine for determining $unhome
1.81 www 6734: my $loadm=10000000;
1.841 albertel 6735: my %servers = &get_servers($udom,'library');
6736: foreach my $tryserver (keys(%servers)) {
6737: my $answer=reply('load',$tryserver);
6738: if (($answer=~/\d+/) && ($answer<$loadm)) {
6739: $loadm=$answer;
6740: $unhome=$tryserver;
6741: }
1.80 www 6742: }
6743: }
6744: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6745: return 'error: unable to find a home server for '.$uname.
6746: ' in domain '.$udom;
1.80 www 6747: }
6748: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6749: &escape($upass),$unhome);
6750: unless ($reply eq 'ok') {
6751: return 'error: '.$reply;
6752: }
1.230 stredwic 6753: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6754: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6755: return 'error: unable verify users home machine.';
1.80 www 6756: }
1.209 matthew 6757: } # End of creation of new user
1.80 www 6758: # ---------------------------------------------------------------------- Add ID
6759: if ($uid) {
6760: $uid=~tr/A-Z/a-z/;
6761: my %uidhash=&idrget($udom,$uname);
1.196 www 6762: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6763: && (!$forceid)) {
1.80 www 6764: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6765: return 'error: user id "'.$uid.'" does not match '.
6766: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6767: }
6768: } else {
6769: &idput($udom,($uname => $uid));
6770: }
6771: }
6772: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6773: my @tmp=&get('environment',
1.899 raeburn 6774: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6775: 'permanentemail','inststatus'],
1.134 albertel 6776: $udom,$uname);
1.1075 raeburn 6777: my (%names,%oldnames);
1.313 matthew 6778: if ($tmp[0] =~ m/^error:.*/) {
6779: %names=();
6780: } else {
6781: %names = @tmp;
1.1075 raeburn 6782: %oldnames = %names;
1.313 matthew 6783: }
1.388 www 6784: #
1.1058 raeburn 6785: # If name, email and/or uid are blank (e.g., because an uploaded file
6786: # of users did not contain them), do not overwrite existing values
6787: # unless field is in $candelete array ref.
6788: #
6789:
6790: my @fields = ('firstname','middlename','lastname','generation',
6791: 'permanentemail','id');
6792: my %newvalues;
6793: if (ref($candelete) eq 'ARRAY') {
6794: foreach my $field (@fields) {
6795: if (grep(/^\Q$field\E$/,@{$candelete})) {
6796: if ($field eq 'firstname') {
6797: $names{$field} = $first;
6798: } elsif ($field eq 'middlename') {
6799: $names{$field} = $middle;
6800: } elsif ($field eq 'lastname') {
6801: $names{$field} = $last;
6802: } elsif ($field eq 'generation') {
6803: $names{$field} = $gene;
6804: } elsif ($field eq 'permanentemail') {
6805: $names{$field} = $email;
6806: } elsif ($field eq 'id') {
6807: $names{$field} = $uid;
6808: }
6809: }
6810: }
6811: }
1.388 www 6812: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6813: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6814: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6815: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6816: if ($email) {
6817: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6818: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6819: }
1.899 raeburn 6820: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6821: if (defined($inststatus)) {
6822: $names{'inststatus'} = '';
6823: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6824: if (ref($usertypes) eq 'HASH') {
6825: my @okstatuses;
6826: foreach my $item (split(/:/,$inststatus)) {
6827: if (defined($usertypes->{$item})) {
6828: push(@okstatuses,$item);
6829: }
6830: }
6831: if (@okstatuses) {
6832: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6833: }
6834: }
6835: }
1.1075 raeburn 6836: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6837: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6838: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6839: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6840: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6841: } else {
6842: $logmsg .= ' during self creation';
6843: }
1.1075 raeburn 6844: my $changed;
6845: if ($newuser) {
6846: $changed = 1;
6847: } else {
6848: foreach my $field (@fields) {
6849: if ($names{$field} ne $oldnames{$field}) {
6850: $changed = 1;
6851: last;
6852: }
6853: }
6854: }
6855: unless ($changed) {
6856: $logmsg = 'No changes in user information needed for: '.$logmsg;
6857: &logthis($logmsg);
6858: return 'ok';
6859: }
6860: my $reply = &put('environment', \%names, $udom,$uname);
6861: if ($reply ne 'ok') {
6862: return 'error: '.$reply;
6863: }
1.1087 ! raeburn 6864: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
! 6865: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
! 6866: }
1.1075 raeburn 6867: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6868: &devalidate_cache_new('namescache',$uname.':'.$udom);
6869: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6870: &logthis($logmsg);
1.134 albertel 6871: return 'ok';
1.80 www 6872: }
6873:
1.81 www 6874: # -------------------------------------------------------------- Modify student
1.80 www 6875:
1.81 www 6876: sub modifystudent {
6877: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6878: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6879: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6880: if (!$cid) {
1.620 albertel 6881: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6882: return 'not_in_class';
6883: }
1.80 www 6884: }
6885: # --------------------------------------------------------------- Make the user
1.81 www 6886: my $reply=&modifyuser
1.209 matthew 6887: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6888: $desiredhome,$email,$inststatus);
1.80 www 6889: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6890: # This will cause &modify_student_enrollment to get the uid from the
6891: # students environment
6892: $uid = undef if (!$forceid);
1.455 albertel 6893: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6894: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6895: return $reply;
6896: }
6897:
6898: sub modify_student_enrollment {
1.957 raeburn 6899: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6900: my ($cdom,$cnum,$chome);
6901: if (!$cid) {
1.620 albertel 6902: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6903: return 'not_in_class';
6904: }
1.620 albertel 6905: $cdom=$env{'course.'.$cid.'.domain'};
6906: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6907: } else {
6908: ($cdom,$cnum)=split(/_/,$cid);
6909: }
1.620 albertel 6910: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6911: if (!$chome) {
1.457 raeburn 6912: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6913: }
1.455 albertel 6914: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6915: # Make sure the user exists
1.81 www 6916: my $uhome=&homeserver($uname,$udom);
6917: if (($uhome eq '') || ($uhome eq 'no_host')) {
6918: return 'error: no such user';
6919: }
1.297 matthew 6920: # Get student data if we were not given enough information
6921: if (!defined($first) || $first eq '' ||
6922: !defined($last) || $last eq '' ||
6923: !defined($uid) || $uid eq '' ||
6924: !defined($middle) || $middle eq '' ||
6925: !defined($gene) || $gene eq '') {
1.294 matthew 6926: # They did not supply us with enough data to enroll the student, so
6927: # we need to pick up more information.
1.297 matthew 6928: my %tmp = &get('environment',
1.294 matthew 6929: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6930: ,$udom,$uname);
6931:
1.800 albertel 6932: #foreach my $key (keys(%tmp)) {
6933: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6934: #}
1.294 matthew 6935: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6936: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6937: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6938: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6939: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6940: }
1.556 albertel 6941: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6942: my $reply=cput('classlist',
6943: {"$uname:$udom" =>
1.515 raeburn 6944: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6945: $cdom,$cnum);
1.81 www 6946: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6947: return 'error: '.$reply;
1.652 albertel 6948: } else {
6949: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6950: }
1.297 matthew 6951: # Add student role to user
1.83 www 6952: my $uurl='/'.$cid;
1.81 www 6953: $uurl=~s/\_/\//g;
6954: if ($usec) {
6955: $uurl.='/'.$usec;
6956: }
1.957 raeburn 6957: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6958: }
6959:
1.556 albertel 6960: sub format_name {
6961: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6962: my $name;
6963: if ($first ne 'lastname') {
6964: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6965: } else {
6966: if ($lastname=~/\S/) {
6967: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6968: $name=~s/\s+,/,/;
6969: } else {
6970: $name.= $firstname.' '.$middlename.' '.$generation;
6971: }
6972: }
6973: $name=~s/^\s+//;
6974: $name=~s/\s+$//;
6975: $name=~s/\s+/ /g;
6976: return $name;
6977: }
6978:
1.84 www 6979: # ------------------------------------------------- Write to course preferences
6980:
6981: sub writecoursepref {
6982: my ($courseid,%prefs)=@_;
6983: $courseid=~s/^\///;
6984: $courseid=~s/\_/\//g;
6985: my ($cdomain,$cnum)=split(/\//,$courseid);
6986: my $chome=homeserver($cnum,$cdomain);
6987: if (($chome eq '') || ($chome eq 'no_host')) {
6988: return 'error: no such course';
6989: }
6990: my $cstring='';
1.800 albertel 6991: foreach my $pref (keys(%prefs)) {
6992: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6993: }
1.84 www 6994: $cstring=~s/\&$//;
6995: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6996: }
6997:
6998: # ---------------------------------------------------------- Make/modify course
6999:
7000: sub createcourse {
1.741 raeburn 7001: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7002: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7003: $url=&declutter($url);
7004: my $cid='';
1.1028 raeburn 7005: if ($context eq 'requestcourses') {
7006: my $can_create = 0;
7007: my ($ownername,$ownerdom) = split(':',$course_owner);
7008: if ($udom eq $ownerdom) {
7009: if (&usertools_access($ownername,$ownerdom,$category,undef,
7010: $context)) {
7011: $can_create = 1;
7012: }
7013: } else {
7014: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7015: $category);
7016: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7017: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7018: if (@curr > 0) {
7019: my @options = qw(approval validate autolimit);
7020: my $optregex = join('|',@options);
7021: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7022: $can_create = 1;
7023: }
7024: }
7025: }
7026: }
7027: if ($can_create) {
7028: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7029: unless (&allowed('ccc',$udom)) {
7030: return 'refused';
7031: }
1.1017 raeburn 7032: }
7033: } else {
7034: return 'refused';
7035: }
1.1028 raeburn 7036: } elsif (!&allowed('ccc',$udom)) {
7037: return 'refused';
1.84 www 7038: }
1.1011 raeburn 7039: # --------------------------------------------------------------- Get Unique ID
7040: my $uname;
7041: if ($cnum =~ /^$match_courseid$/) {
7042: my $chome=&homeserver($cnum,$udom,'true');
7043: if (($chome eq '') || ($chome eq 'no_host')) {
7044: $uname = $cnum;
7045: } else {
1.1038 raeburn 7046: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7047: }
7048: } else {
1.1038 raeburn 7049: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7050: }
7051: return $uname if ($uname =~ /^error/);
7052: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7053: if (!defined($course_server)) {
7054: if (defined(&domain($udom,'primary'))) {
7055: $course_server = &domain($udom,'primary');
7056: } else {
7057: $course_server = $env{'user.home'};
7058: }
7059: }
7060: my %host_servers =
7061: &Apache::lonnet::get_servers($udom,'library');
7062: unless ($host_servers{$course_server}) {
7063: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7064: }
1.84 www 7065: # ------------------------------------------------------------- Make the course
7066: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7067: $course_server);
1.84 www 7068: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7069: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7070: if (($uhome eq '') || ($uhome eq 'no_host')) {
7071: return 'error: no such course';
7072: }
1.271 www 7073: # ----------------------------------------------------------------- Course made
1.516 raeburn 7074: # log existence
1.1029 raeburn 7075: my $now = time;
1.918 raeburn 7076: my $newcourse = {
7077: $udom.'_'.$uname => {
1.921 raeburn 7078: description => $description,
7079: inst_code => $inst_code,
7080: owner => $course_owner,
7081: type => $crstype,
1.1029 raeburn 7082: creator => $env{'user.name'}.':'.
7083: $env{'user.domain'},
7084: created => $now,
7085: context => $context,
1.918 raeburn 7086: },
7087: };
1.921 raeburn 7088: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7089: # set toplevel url
1.271 www 7090: my $topurl=$url;
7091: unless ($nonstandard) {
7092: # ------------------------------------------ For standard courses, make top url
7093: my $mapurl=&clutter($url);
1.278 www 7094: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7095: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7096: <map>
7097: <resource id="1" type="start"></resource>
7098: <resource id="2" src="$mapurl"></resource>
7099: <resource id="3" type="finish"></resource>
7100: <link index="1" from="1" to="2"></link>
7101: <link index="2" from="2" to="3"></link>
7102: </map>
7103: ENDINITMAP
7104: $topurl=&declutter(
1.638 albertel 7105: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7106: );
7107: }
7108: # ----------------------------------------------------------- Write preferences
1.84 www 7109: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7110: ('description' => $description,
7111: 'url' => $topurl,
7112: 'internal.creator' => $env{'user.name'}.':'.
7113: $env{'user.domain'},
7114: 'internal.created' => $now,
7115: 'internal.creationcontext' => $context)
7116: );
1.84 www 7117: return '/'.$udom.'/'.$uname;
7118: }
7119:
1.1011 raeburn 7120: # ------------------------------------------------------------------- Create ID
7121: sub generate_coursenum {
1.1038 raeburn 7122: my ($udom,$crstype) = @_;
1.1011 raeburn 7123: my $domdesc = &domain($udom);
7124: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7125: my $first;
7126: if ($crstype eq 'Community') {
7127: $first = '0';
7128: } else {
7129: $first = int(1+rand(9));
7130: }
7131: my $uname=$first.
1.1011 raeburn 7132: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7133: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7134: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7135: # ----------------------------------------------- Make sure that does not exist
7136: my $uhome=&homeserver($uname,$udom,'true');
7137: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7138: if ($crstype eq 'Community') {
7139: $first = '0';
7140: } else {
7141: $first = int(1+rand(9));
7142: }
7143: $uname=$first.
1.1011 raeburn 7144: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7145: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7146: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7147: $uhome=&homeserver($uname,$udom,'true');
7148: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7149: return 'error: unable to generate unique course-ID';
7150: }
7151: }
7152: return $uname;
7153: }
7154:
1.813 albertel 7155: sub is_course {
7156: my ($cdom,$cnum) = @_;
7157: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7158: undef,'.');
1.813 albertel 7159: if (exists($courses{$cdom.'_'.$cnum})) {
7160: return 1;
7161: }
7162: return 0;
7163: }
7164:
1.1015 raeburn 7165: sub store_userdata {
7166: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7167: my $result;
1.1016 raeburn 7168: if ($datakey ne '') {
1.1013 raeburn 7169: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7170: if ($udom eq '' || $uname eq '') {
7171: $udom = $env{'user.domain'};
7172: $uname = $env{'user.name'};
7173: }
7174: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7175: if (($uhome eq '') || ($uhome eq 'no_host')) {
7176: $result = 'error: no_host';
7177: } else {
7178: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7179: $storehash->{'host'} = $perlvar{'lonHostID'};
7180:
7181: my $namevalue='';
7182: foreach my $key (keys(%{$storehash})) {
7183: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7184: }
7185: $namevalue=~s/\&$//;
7186: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7187: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7188: }
7189: } else {
7190: $result = 'error: data to store was not a hash reference';
7191: }
7192: } else {
7193: $result= 'error: invalid requestkey';
7194: }
7195: return $result;
7196: }
7197:
1.21 www 7198: # ---------------------------------------------------------- Assign Custom Role
7199:
7200: sub assigncustomrole {
1.957 raeburn 7201: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7202: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7203: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7204: }
7205:
7206: # ----------------------------------------------------------------- Revoke Role
7207:
7208: sub revokerole {
1.957 raeburn 7209: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7210: my $now=time;
1.965 raeburn 7211: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7212: }
7213:
7214: # ---------------------------------------------------------- Revoke Custom Role
7215:
7216: sub revokecustomrole {
1.957 raeburn 7217: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7218: my $now=time;
1.357 www 7219: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7220: $deleteflag,$selfenroll,$context);
1.17 www 7221: }
7222:
1.533 banghart 7223: # ------------------------------------------------------------ Disk usage
1.535 albertel 7224: sub diskusage {
1.955 raeburn 7225: my ($udom,$uname,$directorypath,$getpropath)=@_;
7226: $directorypath =~ s/\/$//;
7227: my $listing=&reply('du2:'.&escape($directorypath).':'
7228: .&escape($getpropath).':'.&escape($uname).':'
7229: .&escape($udom),homeserver($uname,$udom));
7230: if ($listing eq 'unknown_cmd') {
7231: if ($getpropath) {
7232: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7233: }
7234: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7235: }
1.514 albertel 7236: return $listing;
1.512 banghart 7237: }
7238:
1.566 banghart 7239: sub is_locked {
7240: my ($file_name, $domain, $user) = @_;
7241: my @check;
7242: my $is_locked;
7243: push @check, $file_name;
1.613 albertel 7244: my %locked = &get('file_permissions',\@check,
1.620 albertel 7245: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7246: my ($tmp)=keys(%locked);
7247: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7248:
1.566 banghart 7249: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7250: $is_locked = 'false';
7251: foreach my $entry (@{$locked{$file_name}}) {
7252: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7253: $is_locked = 'true';
7254: last;
1.745 raeburn 7255: }
7256: }
1.566 banghart 7257: } else {
7258: $is_locked = 'false';
7259: }
7260: }
7261:
1.759 albertel 7262: sub declutter_portfile {
7263: my ($file) = @_;
1.833 albertel 7264: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7265: return $file;
7266: }
7267:
1.559 banghart 7268: # ------------------------------------------------------------- Mark as Read Only
7269:
7270: sub mark_as_readonly {
7271: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7272: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7273: my ($tmp)=keys(%current_permissions);
7274: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7275: foreach my $file (@{$files}) {
1.759 albertel 7276: $file = &declutter_portfile($file);
1.561 banghart 7277: push(@{$current_permissions{$file}},$what);
1.559 banghart 7278: }
1.613 albertel 7279: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7280: return;
7281: }
7282:
1.572 banghart 7283: # ------------------------------------------------------------Save Selected Files
7284:
7285: sub save_selected_files {
7286: my ($user, $path, @files) = @_;
7287: my $filename = $user."savedfiles";
1.573 banghart 7288: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7289: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7290: foreach my $file (@files) {
1.620 albertel 7291: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7292: }
7293: foreach my $file (@other_files) {
1.574 banghart 7294: print (OUT $file."\n");
1.572 banghart 7295: }
1.574 banghart 7296: close (OUT);
1.572 banghart 7297: return 'ok';
7298: }
7299:
1.574 banghart 7300: sub clear_selected_files {
7301: my ($user) = @_;
7302: my $filename = $user."savedfiles";
7303: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7304: print (OUT undef);
7305: close (OUT);
7306: return ("ok");
7307: }
7308:
1.572 banghart 7309: sub files_in_path {
7310: my ($user, $path) = @_;
7311: my $filename = $user."savedfiles";
7312: my %return_files;
1.574 banghart 7313: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7314: while (my $line_in = <IN>) {
1.574 banghart 7315: chomp ($line_in);
7316: my @paths_and_file = split (m!/!, $line_in);
7317: my $file_part = pop (@paths_and_file);
7318: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7319: $path_part.='/';
7320: my $path_and_file = $path_part.$file_part;
7321: if ($path_part eq $path) {
7322: $return_files{$file_part}= 'selected';
7323: }
7324: }
1.574 banghart 7325: close (IN);
7326: return (\%return_files);
1.572 banghart 7327: }
7328:
7329: # called in portfolio select mode, to show files selected NOT in current directory
7330: sub files_not_in_path {
7331: my ($user, $path) = @_;
7332: my $filename = $user."savedfiles";
7333: my @return_files;
7334: my $path_part;
1.800 albertel 7335: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7336: while (my $line = <IN>) {
1.572 banghart 7337: #ok, I know it's clunky, but I want it to work
1.800 albertel 7338: my @paths_and_file = split(m|/|, $line);
7339: my $file_part = pop(@paths_and_file);
7340: chomp($file_part);
7341: my $path_part = join('/', @paths_and_file);
1.572 banghart 7342: $path_part .= '/';
7343: my $path_and_file = $path_part.$file_part;
7344: if ($path_part ne $path) {
1.800 albertel 7345: push(@return_files, ($path_and_file));
1.572 banghart 7346: }
7347: }
1.800 albertel 7348: close(OUT);
1.574 banghart 7349: return (@return_files);
1.572 banghart 7350: }
7351:
1.745 raeburn 7352: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7353:
1.745 raeburn 7354: sub get_portfile_permissions {
7355: my ($domain,$user) = @_;
1.613 albertel 7356: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7357: my ($tmp)=keys(%current_permissions);
7358: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7359: return \%current_permissions;
7360: }
7361:
7362: #---------------------------------------------Get portfolio file access controls
7363:
1.749 raeburn 7364: sub get_access_controls {
1.745 raeburn 7365: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7366: my %access;
7367: my $real_file = $file;
7368: $file =~ s/\.meta$//;
1.745 raeburn 7369: if (defined($file)) {
1.749 raeburn 7370: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7371: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7372: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7373: }
7374: }
1.745 raeburn 7375: } else {
1.749 raeburn 7376: foreach my $key (keys(%{$current_permissions})) {
7377: if ($key =~ /\0accesscontrol$/) {
7378: if (defined($group)) {
7379: if ($key !~ m-^\Q$group\E/-) {
7380: next;
7381: }
7382: }
7383: my ($fullpath) = split(/\0/,$key);
7384: if (ref($$current_permissions{$key}) eq 'HASH') {
7385: foreach my $control (keys(%{$$current_permissions{$key}})) {
7386: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7387: }
7388: }
7389: }
7390: }
7391: }
7392: return %access;
7393: }
7394:
7395: sub modify_access_controls {
7396: my ($file_name,$changes,$domain,$user)=@_;
7397: my ($outcome,$deloutcome);
7398: my %store_permissions;
7399: my %new_values;
7400: my %new_control;
7401: my %translation;
7402: my @deletions = ();
7403: my $now = time;
7404: if (exists($$changes{'activate'})) {
7405: if (ref($$changes{'activate'}) eq 'HASH') {
7406: my @newitems = sort(keys(%{$$changes{'activate'}}));
7407: my $numnew = scalar(@newitems);
7408: for (my $i=0; $i<$numnew; $i++) {
7409: my $newkey = $newitems[$i];
7410: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7411: if ($newkey =~ /^\d+:/) {
7412: $newkey =~ s/^(\d+)/$newid/;
7413: $translation{$1} = $newid;
7414: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7415: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7416: $translation{$1} = $newid;
7417: }
1.749 raeburn 7418: $new_values{$file_name."\0".$newkey} =
7419: $$changes{'activate'}{$newitems[$i]};
7420: $new_control{$newkey} = $now;
7421: }
7422: }
7423: }
7424: my %todelete;
7425: my %changed_items;
7426: foreach my $action ('delete','update') {
7427: if (exists($$changes{$action})) {
7428: if (ref($$changes{$action}) eq 'HASH') {
7429: foreach my $key (keys(%{$$changes{$action}})) {
7430: my ($itemnum) = ($key =~ /^([^:]+):/);
7431: if ($action eq 'delete') {
7432: $todelete{$itemnum} = 1;
7433: } else {
7434: $changed_items{$itemnum} = $key;
7435: }
7436: }
1.745 raeburn 7437: }
7438: }
1.749 raeburn 7439: }
7440: # get lock on access controls for file.
7441: my $lockhash = {
7442: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7443: ':'.$env{'user.domain'},
7444: };
7445: my $tries = 0;
7446: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7447:
7448: while (($gotlock ne 'ok') && $tries <3) {
7449: $tries ++;
7450: sleep 1;
7451: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7452: }
7453: if ($gotlock eq 'ok') {
7454: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7455: my ($tmp)=keys(%curr_permissions);
7456: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7457: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7458: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7459: if (ref($curr_controls) eq 'HASH') {
7460: foreach my $control_item (keys(%{$curr_controls})) {
7461: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7462: if (defined($todelete{$itemnum})) {
7463: push(@deletions,$file_name."\0".$control_item);
7464: } else {
7465: if (defined($changed_items{$itemnum})) {
7466: $new_control{$changed_items{$itemnum}} = $now;
7467: push(@deletions,$file_name."\0".$control_item);
7468: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7469: } else {
7470: $new_control{$control_item} = $$curr_controls{$control_item};
7471: }
7472: }
1.745 raeburn 7473: }
7474: }
7475: }
1.970 raeburn 7476: my ($group);
7477: if (&is_course($domain,$user)) {
7478: ($group,my $file) = split(/\//,$file_name,2);
7479: }
1.749 raeburn 7480: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7481: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7482: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7483: # remove lock
7484: my @del_lock = ($file_name."\0".'locked_access_records');
7485: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7486: my $sqlresult =
1.970 raeburn 7487: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7488: $group);
1.749 raeburn 7489: } else {
7490: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7491: }
1.749 raeburn 7492: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7493: }
7494:
1.827 raeburn 7495: sub make_public_indefinitely {
7496: my ($requrl) = @_;
7497: my $now = time;
7498: my $action = 'activate';
7499: my $aclnum = 0;
7500: if (&is_portfolio_url($requrl)) {
7501: my (undef,$udom,$unum,$file_name,$group) =
7502: &parse_portfolio_url($requrl);
7503: my $current_perms = &get_portfile_permissions($udom,$unum);
7504: my %access_controls = &get_access_controls($current_perms,
7505: $group,$file_name);
7506: foreach my $key (keys(%{$access_controls{$file_name}})) {
7507: my ($num,$scope,$end,$start) =
7508: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7509: if ($scope eq 'public') {
7510: if ($start <= $now && $end == 0) {
7511: $action = 'none';
7512: } else {
7513: $action = 'update';
7514: $aclnum = $num;
7515: }
7516: last;
7517: }
7518: }
7519: if ($action eq 'none') {
7520: return 'ok';
7521: } else {
7522: my %changes;
7523: my $newend = 0;
7524: my $newstart = $now;
7525: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7526: $changes{$action}{$newkey} = {
7527: type => 'public',
7528: time => {
7529: start => $newstart,
7530: end => $newend,
7531: },
7532: };
7533: my ($outcome,$deloutcome,$new_values,$translation) =
7534: &modify_access_controls($file_name,\%changes,$udom,$unum);
7535: return $outcome;
7536: }
7537: } else {
7538: return 'invalid';
7539: }
7540: }
7541:
1.745 raeburn 7542: #------------------------------------------------------Get Marked as Read Only
7543:
7544: sub get_marked_as_readonly {
7545: my ($domain,$user,$what,$group) = @_;
7546: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7547: my @readonly_files;
1.629 banghart 7548: my $cmp1=$what;
7549: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7550: while (my ($file_name,$value) = each(%{$current_permissions})) {
7551: if (defined($group)) {
7552: if ($file_name !~ m-^\Q$group\E/-) {
7553: next;
7554: }
7555: }
1.561 banghart 7556: if (ref($value) eq "ARRAY"){
7557: foreach my $stored_what (@{$value}) {
1.629 banghart 7558: my $cmp2=$stored_what;
1.759 albertel 7559: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7560: $cmp2=join('',@{$stored_what});
1.745 raeburn 7561: }
1.629 banghart 7562: if ($cmp1 eq $cmp2) {
1.561 banghart 7563: push(@readonly_files, $file_name);
1.745 raeburn 7564: last;
1.563 banghart 7565: } elsif (!defined($what)) {
7566: push(@readonly_files, $file_name);
1.745 raeburn 7567: last;
1.561 banghart 7568: }
7569: }
1.745 raeburn 7570: }
1.561 banghart 7571: }
7572: return @readonly_files;
7573: }
1.577 banghart 7574: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7575:
1.577 banghart 7576: sub get_marked_as_readonly_hash {
1.745 raeburn 7577: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7578: my %readonly_files;
1.745 raeburn 7579: while (my ($file_name,$value) = each(%{$current_permissions})) {
7580: if (defined($group)) {
7581: if ($file_name !~ m-^\Q$group\E/-) {
7582: next;
7583: }
7584: }
1.577 banghart 7585: if (ref($value) eq "ARRAY"){
7586: foreach my $stored_what (@{$value}) {
1.745 raeburn 7587: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7588: foreach my $lock_descriptor(@{$stored_what}) {
7589: if ($lock_descriptor eq 'graded') {
7590: $readonly_files{$file_name} = 'graded';
7591: } elsif ($lock_descriptor eq 'handback') {
7592: $readonly_files{$file_name} = 'handback';
7593: } else {
7594: if (!exists($readonly_files{$file_name})) {
7595: $readonly_files{$file_name} = 'locked';
7596: }
7597: }
1.745 raeburn 7598: }
1.750 banghart 7599: }
1.577 banghart 7600: }
7601: }
7602: }
7603: return %readonly_files;
7604: }
1.559 banghart 7605: # ------------------------------------------------------------ Unmark as Read Only
7606:
7607: sub unmark_as_readonly {
1.629 banghart 7608: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7609: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7610: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7611: $file_name = &declutter_portfile($file_name);
1.634 albertel 7612: my $symb_crs = $what;
7613: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7614: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7615: my ($tmp)=keys(%current_permissions);
7616: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7617: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7618: foreach my $file (@readonly_files) {
1.759 albertel 7619: my $clean_file = &declutter_portfile($file);
7620: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7621: my $current_locks = $current_permissions{$file};
1.563 banghart 7622: my @new_locks;
7623: my @del_keys;
7624: if (ref($current_locks) eq "ARRAY"){
7625: foreach my $locker (@{$current_locks}) {
1.632 albertel 7626: my $compare=$locker;
1.749 raeburn 7627: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7628: $compare=join('',@{$locker});
1.746 raeburn 7629: if ($compare ne $symb_crs) {
7630: push(@new_locks, $locker);
7631: }
1.563 banghart 7632: }
7633: }
1.650 albertel 7634: if (scalar(@new_locks) > 0) {
1.563 banghart 7635: $current_permissions{$file} = \@new_locks;
7636: } else {
7637: push(@del_keys, $file);
1.613 albertel 7638: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7639: delete($current_permissions{$file});
1.563 banghart 7640: }
7641: }
1.561 banghart 7642: }
1.613 albertel 7643: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7644: return;
7645: }
1.512 banghart 7646:
1.17 www 7647: # ------------------------------------------------------------ Directory lister
7648:
7649: sub dirlist {
1.955 raeburn 7650: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7651: $uri=~s/^\///;
7652: $uri=~s/\/$//;
1.253 stredwic 7653: my ($udom, $uname);
1.955 raeburn 7654: if ($getuserdir) {
1.253 stredwic 7655: $udom = $userdomain;
7656: $uname = $username;
1.955 raeburn 7657: } else {
7658: (undef,$udom,$uname)=split(/\//,$uri);
7659: if(defined($userdomain)) {
7660: $udom = $userdomain;
7661: }
7662: if(defined($username)) {
7663: $uname = $username;
7664: }
1.253 stredwic 7665: }
1.955 raeburn 7666: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7667:
1.955 raeburn 7668: $dirRoot = $perlvar{'lonDocRoot'};
7669: if (defined($getpropath)) {
7670: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7671: $dirRoot =~ s/\/$//;
1.955 raeburn 7672: } elsif (defined($getuserdir)) {
7673: my $subdir=$uname.'__';
7674: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7675: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7676: ."/$udom/$subdir/$uname";
7677: } elsif (defined($alternateRoot)) {
7678: $dirRoot = $alternateRoot;
1.751 banghart 7679: }
1.253 stredwic 7680:
7681: if($udom) {
7682: if($uname) {
1.955 raeburn 7683: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7684: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7685: .':'.&escape($uname).':'.&escape($udom),
7686: &homeserver($uname,$udom));
7687: if ($listing eq 'unknown_cmd') {
7688: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7689: &homeserver($uname,$udom));
7690: } else {
7691: @listing_results = map { &unescape($_); } split(/:/,$listing);
7692: }
1.605 matthew 7693: if ($listing eq 'unknown_cmd') {
1.800 albertel 7694: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7695: &homeserver($uname,$udom));
1.605 matthew 7696: @listing_results = split(/:/,$listing);
7697: } else {
7698: @listing_results = map { &unescape($_); } split(/:/,$listing);
7699: }
7700: return @listing_results;
1.955 raeburn 7701: } elsif(!$alternateRoot) {
1.800 albertel 7702: my %allusers;
1.841 albertel 7703: my %servers = &get_servers($udom,'library');
1.955 raeburn 7704: foreach my $tryserver (keys(%servers)) {
7705: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7706: &escape($udom),$tryserver);
7707: if ($listing eq 'unknown_cmd') {
7708: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7709: $udom, $tryserver);
7710: } else {
7711: @listing_results = map { &unescape($_); } split(/:/,$listing);
7712: }
1.841 albertel 7713: if ($listing eq 'unknown_cmd') {
7714: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7715: $udom, $tryserver);
7716: @listing_results = split(/:/,$listing);
7717: } else {
7718: @listing_results =
7719: map { &unescape($_); } split(/:/,$listing);
7720: }
7721: if ($listing_results[0] ne 'no_such_dir' &&
7722: $listing_results[0] ne 'empty' &&
7723: $listing_results[0] ne 'con_lost') {
7724: foreach my $line (@listing_results) {
7725: my ($entry) = split(/&/,$line,2);
7726: $allusers{$entry} = 1;
7727: }
7728: }
1.253 stredwic 7729: }
7730: my $alluserstr='';
1.800 albertel 7731: foreach my $user (sort(keys(%allusers))) {
7732: $alluserstr.=$user.'&user:';
1.253 stredwic 7733: }
7734: $alluserstr=~s/:$//;
7735: return split(/:/,$alluserstr);
7736: } else {
1.800 albertel 7737: return ('missing user name');
1.253 stredwic 7738: }
1.955 raeburn 7739: } elsif(!defined($getpropath)) {
1.841 albertel 7740: my @all_domains = sort(&all_domains());
1.955 raeburn 7741: foreach my $domain (@all_domains) {
7742: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7743: }
7744: return @all_domains;
7745: } else {
1.800 albertel 7746: return ('missing domain');
1.275 stredwic 7747: }
7748: }
7749:
7750: # --------------------------------------------- GetFileTimestamp
7751: # This function utilizes dirlist and returns the date stamp for
7752: # when it was last modified. It will also return an error of -1
7753: # if an error occurs
7754:
7755: sub GetFileTimestamp {
1.955 raeburn 7756: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7757: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7758: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7759: my ($fileStat) =
7760: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7761: undef,$getuserdir);
1.275 stredwic 7762: my @stats = split('&', $fileStat);
7763: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7764: # @stats contains first the filename, then the stat output
7765: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7766: } else {
7767: return -1;
1.253 stredwic 7768: }
1.26 www 7769: }
7770:
1.712 albertel 7771: sub stat_file {
7772: my ($uri) = @_;
1.787 albertel 7773: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7774:
1.955 raeburn 7775: my ($udom,$uname,$file);
1.712 albertel 7776: if ($uri =~ m-^/(uploaded|editupload)/-) {
7777: ($udom,$uname,$file) =
1.811 albertel 7778: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7779: $file = 'userfiles/'.$file;
7780: }
7781: if ($uri =~ m-^/res/-) {
7782: ($udom,$uname) =
1.807 albertel 7783: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7784: $file = $uri;
7785: }
7786:
7787: if (!$udom || !$uname || !$file) {
7788: # unable to handle the uri
7789: return ();
7790: }
1.956 raeburn 7791: my $getpropath;
7792: if ($file =~ /^userfiles\//) {
7793: $getpropath = 1;
7794: }
1.955 raeburn 7795: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7796: my @stats = split('&', $result);
1.721 banghart 7797:
1.712 albertel 7798: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7799: shift(@stats); #filename is first
7800: return @stats;
7801: }
7802: return ();
7803: }
7804:
1.26 www 7805: # -------------------------------------------------------- Value of a Condition
7806:
1.713 albertel 7807: # gets the value of a specific preevaluated condition
7808: # stored in the string $env{user.state.<cid>}
7809: # or looks up a condition reference in the bighash and if if hasn't
7810: # already been evaluated recurses into docondval to get the value of
7811: # the condition, then memoizing it to
7812: # $env{user.state.<cid>.<condition>}
1.40 www 7813: sub directcondval {
7814: my $number=shift;
1.620 albertel 7815: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7816: &Apache::lonuserstate::evalstate();
7817: }
1.713 albertel 7818: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7819: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7820: } elsif ($number =~ /^_/) {
7821: my $sub_condition;
7822: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7823: &GDBM_READER(),0640)) {
7824: $sub_condition=$bighash{'conditions'.$number};
7825: untie(%bighash);
7826: }
7827: my $value = &docondval($sub_condition);
1.949 raeburn 7828: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7829: return $value;
7830: }
1.620 albertel 7831: if ($env{'user.state.'.$env{'request.course.id'}}) {
7832: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7833: } else {
7834: return 2;
7835: }
7836: }
7837:
1.713 albertel 7838: # get the collection of conditions for this resource
1.26 www 7839: sub condval {
7840: my $condidx=shift;
1.54 www 7841: my $allpathcond='';
1.713 albertel 7842: foreach my $cond (split(/\|/,$condidx)) {
7843: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7844: $allpathcond.=
7845: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7846: }
1.191 harris41 7847: }
1.54 www 7848: $allpathcond=~s/\|$//;
1.713 albertel 7849: return &docondval($allpathcond);
7850: }
7851:
7852: #evaluates an expression of conditions
7853: sub docondval {
7854: my ($allpathcond) = @_;
7855: my $result=0;
7856: if ($env{'request.course.id'}
7857: && defined($allpathcond)) {
7858: my $operand='|';
7859: my @stack;
7860: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7861: if ($chunk eq '(') {
7862: push @stack,($operand,$result);
7863: } elsif ($chunk eq ')') {
7864: my $before=pop @stack;
7865: if (pop @stack eq '&') {
7866: $result=$result>$before?$before:$result;
7867: } else {
7868: $result=$result>$before?$result:$before;
7869: }
7870: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7871: $operand=$chunk;
7872: } else {
7873: my $new=directcondval($chunk);
7874: if ($operand eq '&') {
7875: $result=$result>$new?$new:$result;
7876: } else {
7877: $result=$result>$new?$result:$new;
7878: }
7879: }
7880: }
1.26 www 7881: }
7882: return $result;
1.421 albertel 7883: }
7884:
7885: # ---------------------------------------------------- Devalidate courseresdata
7886:
7887: sub devalidatecourseresdata {
7888: my ($coursenum,$coursedomain)=@_;
7889: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7890: &devalidate_cache_new('courseres',$hashid);
1.28 www 7891: }
7892:
1.763 www 7893:
1.200 www 7894: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7895: #
7896: # Parameters:
7897: # $coursenum - Number of the course.
7898: # $coursedomain - Domain at which the course was created.
7899: # Returns:
7900: # A hash of the course parameters along (I think) with timestamps
7901: # and version info.
1.877 foxr 7902:
1.624 albertel 7903: sub get_courseresdata {
7904: my ($coursenum,$coursedomain)=@_;
1.200 www 7905: my $coursehom=&homeserver($coursenum,$coursedomain);
7906: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7907: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7908: my %dumpreply;
1.417 albertel 7909: unless (defined($cached)) {
1.624 albertel 7910: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7911: $result=\%dumpreply;
1.251 albertel 7912: my ($tmp) = keys(%dumpreply);
7913: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7914: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7915: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7916: return $tmp;
1.416 albertel 7917: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7918: $result=undef;
1.599 albertel 7919: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7920: }
7921: }
1.624 albertel 7922: return $result;
7923: }
7924:
1.633 albertel 7925: sub devalidateuserresdata {
7926: my ($uname,$udom)=@_;
7927: my $hashid="$udom:$uname";
7928: &devalidate_cache_new('userres',$hashid);
7929: }
7930:
1.624 albertel 7931: sub get_userresdata {
7932: my ($uname,$udom)=@_;
7933: #most student don\'t have any data set, check if there is some data
7934: if (&EXT_cache_status($udom,$uname)) { return undef; }
7935:
7936: my $hashid="$udom:$uname";
7937: my ($result,$cached)=&is_cached_new('userres',$hashid);
7938: if (!defined($cached)) {
7939: my %resourcedata=&dump('resourcedata',$udom,$uname);
7940: $result=\%resourcedata;
7941: &do_cache_new('userres',$hashid,$result,600);
7942: }
7943: my ($tmp)=keys(%$result);
7944: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7945: return $result;
7946: }
7947: #error 2 occurs when the .db doesn't exist
7948: if ($tmp!~/error: 2 /) {
1.672 albertel 7949: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7950: " Trying to get resource data for ".
7951: $uname." at ".$udom.": ".
7952: $tmp."</font>");
7953: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7954: #&EXT_cache_set($udom,$uname);
7955: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7956: undef($tmp); # not really an error so don't send it back
1.624 albertel 7957: }
7958: return $tmp;
7959: }
1.879 foxr 7960: #----------------------------------------------- resdata - return resource data
7961: # Purpose:
7962: # Return resource data for either users or for a course.
7963: # Parameters:
7964: # $name - Course/user name.
7965: # $domain - Name of the domain the user/course is registered on.
7966: # $type - Type of thing $name is (must be 'course' or 'user'
7967: # @which - Array of names of resources desired.
7968: # Returns:
7969: # The value of the first reasource in @which that is found in the
7970: # resource hash.
7971: # Exceptional Conditions:
7972: # If the $type passed in is not valid (not the string 'course' or
7973: # 'user', an undefined reference is returned.
7974: # If none of the resources are found, an undef is returned
1.624 albertel 7975: sub resdata {
7976: my ($name,$domain,$type,@which)=@_;
7977: my $result;
7978: if ($type eq 'course') {
7979: $result=&get_courseresdata($name,$domain);
7980: } elsif ($type eq 'user') {
7981: $result=&get_userresdata($name,$domain);
7982: }
7983: if (!ref($result)) { return $result; }
1.251 albertel 7984: foreach my $item (@which) {
1.927 albertel 7985: if (defined($result->{$item->[0]})) {
7986: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7987: }
1.250 albertel 7988: }
1.291 albertel 7989: return undef;
1.200 www 7990: }
7991:
1.379 matthew 7992: #
7993: # EXT resource caching routines
7994: #
7995:
7996: sub clear_EXT_cache_status {
1.383 albertel 7997: &delenv('cache.EXT.');
1.379 matthew 7998: }
7999:
8000: sub EXT_cache_status {
8001: my ($target_domain,$target_user) = @_;
1.383 albertel 8002: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8003: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8004: # We know already the user has no data
8005: return 1;
8006: } else {
8007: return 0;
8008: }
8009: }
8010:
8011: sub EXT_cache_set {
8012: my ($target_domain,$target_user) = @_;
1.383 albertel 8013: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8014: #&appenv({$cachename => time});
1.379 matthew 8015: }
8016:
1.28 www 8017: # --------------------------------------------------------- Value of a Variable
1.58 www 8018: sub EXT {
1.715 albertel 8019:
1.395 albertel 8020: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8021: unless ($varname) { return ''; }
1.218 albertel 8022: #get real user name/domain, courseid and symb
8023: my $courseid;
1.359 albertel 8024: my $publicuser;
1.427 www 8025: if ($symbparm) {
8026: $symbparm=&get_symb_from_alias($symbparm);
8027: }
1.218 albertel 8028: if (!($uname && $udom)) {
1.790 albertel 8029: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8030: if (!$symbparm) { $symbparm=$cursymb; }
8031: } else {
1.620 albertel 8032: $courseid=$env{'request.course.id'};
1.218 albertel 8033: }
1.48 www 8034: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8035: my $rest;
1.320 albertel 8036: if (defined($therest[0])) {
1.48 www 8037: $rest=join('.',@therest);
8038: } else {
8039: $rest='';
8040: }
1.320 albertel 8041:
1.57 www 8042: my $qualifierrest=$qualifier;
8043: if ($rest) { $qualifierrest.='.'.$rest; }
8044: my $spacequalifierrest=$space;
8045: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8046: if ($realm eq 'user') {
1.48 www 8047: # --------------------------------------------------------------- user.resource
8048: if ($space eq 'resource') {
1.651 albertel 8049: if ( (defined($Apache::lonhomework::parsing_a_problem)
8050: || defined($Apache::lonhomework::parsing_a_task))
8051: &&
1.744 albertel 8052: ($symbparm eq &symbread()) ) {
8053: # if we are in the middle of processing the resource the
8054: # get the value we are planning on committing
8055: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8056: return $Apache::lonhomework::results{$qualifierrest};
8057: } else {
8058: return $Apache::lonhomework::history{$qualifierrest};
8059: }
1.335 albertel 8060: } else {
1.359 albertel 8061: my %restored;
1.620 albertel 8062: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8063: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8064: } else {
8065: %restored=&restore($symbparm,$courseid,$udom,$uname);
8066: }
1.335 albertel 8067: return $restored{$qualifierrest};
8068: }
1.48 www 8069: # ----------------------------------------------------------------- user.access
8070: } elsif ($space eq 'access') {
1.218 albertel 8071: # FIXME - not supporting calls for a specific user
1.48 www 8072: return &allowed($qualifier,$rest);
8073: # ------------------------------------------ user.preferences, user.environment
8074: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8075: if (($uname eq $env{'user.name'}) &&
8076: ($udom eq $env{'user.domain'})) {
8077: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8078: } else {
1.359 albertel 8079: my %returnhash;
8080: if (!$publicuser) {
8081: %returnhash=&userenvironment($udom,$uname,
8082: $qualifierrest);
8083: }
1.218 albertel 8084: return $returnhash{$qualifierrest};
8085: }
1.48 www 8086: # ----------------------------------------------------------------- user.course
8087: } elsif ($space eq 'course') {
1.218 albertel 8088: # FIXME - not supporting calls for a specific user
1.620 albertel 8089: return $env{join('.',('request.course',$qualifier))};
1.48 www 8090: # ------------------------------------------------------------------- user.role
8091: } elsif ($space eq 'role') {
1.218 albertel 8092: # FIXME - not supporting calls for a specific user
1.620 albertel 8093: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8094: if ($qualifier eq 'value') {
8095: return $role;
8096: } elsif ($qualifier eq 'extent') {
8097: return $where;
8098: }
8099: # ----------------------------------------------------------------- user.domain
8100: } elsif ($space eq 'domain') {
1.218 albertel 8101: return $udom;
1.48 www 8102: # ------------------------------------------------------------------- user.name
8103: } elsif ($space eq 'name') {
1.218 albertel 8104: return $uname;
1.48 www 8105: # ---------------------------------------------------- Any other user namespace
1.29 www 8106: } else {
1.359 albertel 8107: my %reply;
8108: if (!$publicuser) {
8109: %reply=&get($space,[$qualifierrest],$udom,$uname);
8110: }
8111: return $reply{$qualifierrest};
1.48 www 8112: }
1.236 www 8113: } elsif ($realm eq 'query') {
8114: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8115: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8116: [$spacequalifierrest]);
1.620 albertel 8117: return $env{'form.'.$spacequalifierrest};
1.236 www 8118: } elsif ($realm eq 'request') {
1.48 www 8119: # ------------------------------------------------------------- request.browser
8120: if ($space eq 'browser') {
1.430 www 8121: if ($qualifier eq 'textremote') {
1.676 albertel 8122: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8123: return 1;
8124: } else {
8125: return 0;
8126: }
8127: } else {
1.620 albertel 8128: return $env{'browser.'.$qualifier};
1.430 www 8129: }
1.57 www 8130: # ------------------------------------------------------------ request.filename
8131: } else {
1.620 albertel 8132: return $env{'request.'.$spacequalifierrest};
1.29 www 8133: }
1.28 www 8134: } elsif ($realm eq 'course') {
1.48 www 8135: # ---------------------------------------------------------- course.description
1.620 albertel 8136: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8137: } elsif ($realm eq 'resource') {
1.165 www 8138:
1.620 albertel 8139: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8140: if (!$symbparm) { $symbparm=&symbread(); }
8141: }
1.693 albertel 8142:
8143: if ($space eq 'title') {
8144: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8145: return &gettitle($symbparm);
8146: }
8147:
8148: if ($space eq 'map') {
8149: my ($map) = &decode_symb($symbparm);
8150: return &symbread($map);
8151: }
1.905 albertel 8152: if ($space eq 'filename') {
8153: if ($symbparm) {
8154: return &clutter((&decode_symb($symbparm))[2]);
8155: }
8156: return &hreflocation('',$env{'request.filename'});
8157: }
1.693 albertel 8158:
8159: my ($section, $group, @groups);
1.593 albertel 8160: my ($courselevelm,$courselevel);
1.539 albertel 8161: if ($symbparm && defined($courseid) &&
1.620 albertel 8162: $courseid eq $env{'request.course.id'}) {
1.165 www 8163:
1.218 albertel 8164: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8165:
1.60 www 8166: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8167: my $symbp=$symbparm;
1.735 albertel 8168: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8169:
8170: my $symbparm=$symbp.'.'.$spacequalifierrest;
8171: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8172:
1.620 albertel 8173: if (($env{'user.name'} eq $uname) &&
8174: ($env{'user.domain'} eq $udom)) {
8175: $section=$env{'request.course.sec'};
1.733 raeburn 8176: @groups = split(/:/,$env{'request.course.groups'});
8177: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8178: } else {
1.539 albertel 8179: if (! defined($usection)) {
1.551 albertel 8180: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8181: } else {
8182: $section = $usection;
8183: }
1.733 raeburn 8184: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8185: }
8186:
8187: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8188: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8189: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8190:
1.593 albertel 8191: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8192: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8193: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8194:
1.60 www 8195: # ----------------------------------------------------------- first, check user
1.624 albertel 8196:
8197: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8198: ([$courselevelr,'resource'],
8199: [$courselevelm,'map' ],
8200: [$courselevel, 'course' ]));
1.931 albertel 8201: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8202:
1.594 albertel 8203: # ------------------------------------------------ second, check some of course
1.684 raeburn 8204: my $coursereply;
1.691 raeburn 8205: if (@groups > 0) {
8206: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8207: $mapparm,$spacequalifierrest);
1.927 albertel 8208: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8209: }
1.96 www 8210:
1.684 raeburn 8211: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8212: $env{'course.'.$courseid.'.domain'},
8213: 'course',
8214: ([$seclevelr, 'resource'],
8215: [$seclevelm, 'map' ],
8216: [$seclevel, 'course' ],
8217: [$courselevelr,'resource']));
8218: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8219:
1.60 www 8220: # ------------------------------------------------------ third, check map parms
1.218 albertel 8221: my %parmhash=();
8222: my $thisparm='';
8223: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8224: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8225: &GDBM_READER(),0640)) {
1.218 albertel 8226: $thisparm=$parmhash{$symbparm};
8227: untie(%parmhash);
8228: }
1.927 albertel 8229: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8230: }
1.594 albertel 8231: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8232:
1.218 albertel 8233: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8234: my $filename;
8235: if (!$symbparm) { $symbparm=&symbread(); }
8236: if ($symbparm) {
1.409 www 8237: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8238: } else {
1.620 albertel 8239: $filename=$env{'request.filename'};
1.282 albertel 8240: }
8241: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8242: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8243: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8244: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8245:
1.927 albertel 8246: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8247: if ($symbparm && defined($courseid) &&
1.620 albertel 8248: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8249: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8250: $env{'course.'.$courseid.'.domain'},
8251: 'course',
1.927 albertel 8252: ([$courselevelm,'map' ],
8253: [$courselevel, 'course']));
8254: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8255: }
1.145 www 8256: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8257: unless ($space eq '0') {
1.336 albertel 8258: my @parts=split(/_/,$space);
8259: my $id=pop(@parts);
8260: my $part=join('_',@parts);
8261: if ($part eq '') { $part='0'; }
1.927 albertel 8262: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8263: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8264: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8265: }
1.395 albertel 8266: if ($recurse) { return undef; }
8267: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8268: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8269: # ---------------------------------------------------- Any other user namespace
8270: } elsif ($realm eq 'environment') {
8271: # ----------------------------------------------------------------- environment
1.620 albertel 8272: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8273: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8274: } else {
1.770 albertel 8275: if ($uname eq 'anonymous' && $udom eq '') {
8276: return '';
8277: }
1.219 albertel 8278: my %returnhash=&userenvironment($udom,$uname,
8279: $spacequalifierrest);
8280: return $returnhash{$spacequalifierrest};
8281: }
1.28 www 8282: } elsif ($realm eq 'system') {
1.48 www 8283: # ----------------------------------------------------------------- system.time
8284: if ($space eq 'time') {
8285: return time;
8286: }
1.696 albertel 8287: } elsif ($realm eq 'server') {
8288: # ----------------------------------------------------------------- system.time
8289: if ($space eq 'name') {
8290: return $ENV{'SERVER_NAME'};
8291: }
1.28 www 8292: }
1.48 www 8293: return '';
1.61 www 8294: }
8295:
1.927 albertel 8296: sub get_reply {
8297: my ($reply_value) = @_;
1.940 raeburn 8298: if (ref($reply_value) eq 'ARRAY') {
8299: if (wantarray) {
8300: return @$reply_value;
8301: }
8302: return $reply_value->[0];
8303: } else {
8304: return $reply_value;
1.927 albertel 8305: }
8306: }
8307:
1.691 raeburn 8308: sub check_group_parms {
8309: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8310: my @groupitems = ();
8311: my $resultitem;
1.927 albertel 8312: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8313: foreach my $group (@{$groups}) {
8314: foreach my $level (@levels) {
1.927 albertel 8315: my $item = $courseid.'.['.$group.'].'.$level->[0];
8316: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8317: }
8318: }
8319: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8320: $env{'course.'.$courseid.'.domain'},
8321: 'course',@groupitems);
8322: return $coursereply;
8323: }
8324:
8325: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8326: my ($courseid,@groups) = @_;
8327: @groups = sort(@groups);
1.691 raeburn 8328: return @groups;
8329: }
8330:
1.395 albertel 8331: sub packages_tab_default {
8332: my ($uri,$varname)=@_;
8333: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8334:
8335: my (@extension,@specifics,$do_default);
8336: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8337: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8338: if ($pack_type eq 'default') {
8339: $do_default=1;
8340: } elsif ($pack_type eq 'extension') {
8341: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8342: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8343: # only look at packages defaults for packages that this id is
1.738 albertel 8344: push(@specifics,[$package,$pack_type,$pack_part]);
8345: }
8346: }
8347: # first look for a package that matches the requested part id
8348: foreach my $package (@specifics) {
8349: my (undef,$pack_type,$pack_part)=@{$package};
8350: next if ($pack_part ne $part);
8351: if (defined($packagetab{"$pack_type&$name&default"})) {
8352: return $packagetab{"$pack_type&$name&default"};
8353: }
8354: }
8355: # look for any possible matching non extension_ package
8356: foreach my $package (@specifics) {
8357: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8358: if (defined($packagetab{"$pack_type&$name&default"})) {
8359: return $packagetab{"$pack_type&$name&default"};
8360: }
1.585 albertel 8361: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8362: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8363: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8364: }
8365: }
1.738 albertel 8366: # look for any posible extension_ match
8367: foreach my $package (@extension) {
8368: my ($package,$pack_type)=@{$package};
8369: if (defined($packagetab{"$pack_type&$name&default"})) {
8370: return $packagetab{"$pack_type&$name&default"};
8371: }
8372: if (defined($packagetab{$package."&$name&default"})) {
8373: return $packagetab{$package."&$name&default"};
8374: }
8375: }
8376: # look for a global default setting
8377: if ($do_default && defined($packagetab{"default&$name&default"})) {
8378: return $packagetab{"default&$name&default"};
8379: }
1.395 albertel 8380: return undef;
8381: }
8382:
1.334 albertel 8383: sub add_prefix_and_part {
8384: my ($prefix,$part)=@_;
8385: my $keyroot;
8386: if (defined($prefix) && $prefix !~ /^__/) {
8387: # prefix that has a part already
8388: $keyroot=$prefix;
8389: } elsif (defined($prefix)) {
8390: # prefix that is missing a part
8391: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8392: } else {
8393: # no prefix at all
8394: if (defined($part)) { $keyroot='_'.$part; }
8395: }
8396: return $keyroot;
8397: }
8398:
1.71 www 8399: # ---------------------------------------------------------------- Get metadata
8400:
1.599 albertel 8401: my %metaentry;
1.1070 www 8402: my %importedpartids;
1.71 www 8403: sub metadata {
1.176 www 8404: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8405: $uri=&declutter($uri);
1.288 albertel 8406: # if it is a non metadata possible uri return quickly
1.529 albertel 8407: if (($uri eq '') ||
8408: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8409: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8410: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8411: return undef;
8412: }
8413: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8414: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8415: return undef;
1.288 albertel 8416: }
1.73 www 8417: my $filename=$uri;
8418: $uri=~s/\.meta$//;
1.172 www 8419: #
8420: # Is the metadata already cached?
1.177 www 8421: # Look at timestamp of caching
1.172 www 8422: # Everything is cached by the main uri, libraries are never directly cached
8423: #
1.428 albertel 8424: if (!defined($liburi)) {
1.599 albertel 8425: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8426: if (defined($cached)) { return $result->{':'.$what}; }
8427: }
8428: {
1.1069 www 8429: # Imported parts would go here
1.1070 www 8430: my %importedids=();
8431: my @origfileimportpartids=();
1.1069 www 8432: my $importedparts=0;
1.172 www 8433: #
8434: # Is this a recursive call for a library?
8435: #
1.599 albertel 8436: # if (! exists($metacache{$uri})) {
8437: # $metacache{$uri}={};
8438: # }
1.924 albertel 8439: my $cachetime = 60*60;
1.171 www 8440: if ($liburi) {
8441: $liburi=&declutter($liburi);
8442: $filename=$liburi;
1.401 bowersj2 8443: } else {
1.599 albertel 8444: &devalidate_cache_new('meta',$uri);
8445: undef(%metaentry);
1.401 bowersj2 8446: }
1.140 www 8447: my %metathesekeys=();
1.73 www 8448: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8449: my $metastring;
1.924 albertel 8450: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8451: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8452: $metastring =
1.929 albertel 8453: &Apache::lonnet::ssi_body($which,
1.924 albertel 8454: ('grade_target' => 'meta'));
8455: $cachetime = 1; # only want this cached in the child not long term
8456: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8457: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8458: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8459: $metastring=&getfile($file);
1.489 albertel 8460: }
1.208 albertel 8461: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8462: my $token;
1.140 www 8463: undef %metathesekeys;
1.71 www 8464: while ($token=$parser->get_token) {
1.339 albertel 8465: if ($token->[0] eq 'S') {
8466: if (defined($token->[2]->{'package'})) {
1.172 www 8467: #
8468: # This is a package - get package info
8469: #
1.339 albertel 8470: my $package=$token->[2]->{'package'};
8471: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8472: if (defined($token->[2]->{'id'})) {
8473: $keyroot.='_'.$token->[2]->{'id'};
8474: }
1.599 albertel 8475: if ($metaentry{':packages'}) {
8476: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8477: } else {
1.599 albertel 8478: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8479: }
1.736 albertel 8480: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8481: my $part=$keyroot;
8482: $part=~s/^\_//;
1.736 albertel 8483: if ($pack_entry=~/^\Q$package\E\&/ ||
8484: $pack_entry=~/^\Q$package\E_0\&/) {
8485: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8486: # ignore package.tab specified default values
8487: # here &package_tab_default() will fetch those
8488: if ($subp eq 'default') { next; }
1.736 albertel 8489: my $value=$packagetab{$pack_entry};
1.432 albertel 8490: my $unikey;
8491: if ($pack =~ /_0$/) {
8492: $unikey='parameter_0_'.$name;
8493: $part=0;
8494: } else {
8495: $unikey='parameter'.$keyroot.'_'.$name;
8496: }
1.339 albertel 8497: if ($subp eq 'display') {
8498: $value.=' [Part: '.$part.']';
8499: }
1.599 albertel 8500: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8501: $metathesekeys{$unikey}=1;
1.599 albertel 8502: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8503: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8504: }
1.599 albertel 8505: if (defined($metaentry{':'.$unikey.'.default'})) {
8506: $metaentry{':'.$unikey}=
8507: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8508: }
1.339 albertel 8509: }
8510: }
8511: } else {
1.172 www 8512: #
8513: # This is not a package - some other kind of start tag
1.339 albertel 8514: #
8515: my $entry=$token->[1];
1.1068 www 8516: my $unikey='';
1.175 www 8517:
1.339 albertel 8518: if ($entry eq 'import') {
1.175 www 8519: #
8520: # Importing a library here
1.339 albertel 8521: #
1.1067 www 8522: my $location=$parser->get_text('/import');
8523: my $dir=$filename;
8524: $dir=~s|[^/]*$||;
8525: $location=&filelocation($dir,$location);
1.1069 www 8526:
1.1068 www 8527: my $importmode=$token->[2]->{'importmode'};
8528: if ($importmode eq 'problem') {
1.1069 www 8529: # Import as problem/response
1.1068 www 8530: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8531: } elsif ($importmode eq 'part') {
8532: # Import as part(s)
1.1069 www 8533: $importedparts=1;
8534: # We need to get the original file and the imported file to get the part order correct
8535: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8536: # Load and inspect original file
1.1070 www 8537: if ($#origfileimportpartids<0) {
8538: undef(%importedpartids);
8539: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8540: my $origfile=&getfile($origfilelocation);
8541: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8542: }
8543:
1.1069 www 8544: # Load and inspect imported file
8545: my $impfile=&getfile($location);
8546: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8547: if ($#impfilepartids>=0) {
8548: # This problem had parts
1.1070 www 8549: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8550: } else {
8551: # Importing by turning a single problem into a problem part
8552: # It gets the import-tags ID as part-ID
8553: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8554: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8555: }
1.1068 www 8556: } else {
8557: # Normal import
8558: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8559: if (defined($token->[2]->{'id'})) {
8560: $unikey.='_'.$token->[2]->{'id'};
8561: }
1.1067 www 8562: }
8563:
1.339 albertel 8564: if ($depthcount<20) {
1.736 albertel 8565: my $metadata =
8566: &metadata($uri,'keys', $location,$unikey,
8567: $depthcount+1);
8568: foreach my $meta (split(',',$metadata)) {
8569: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8570: $metathesekeys{$meta}=1;
1.339 albertel 8571: }
1.1068 www 8572:
8573: }
1.1067 www 8574: } else {
8575: #
8576: # Not importing, some other kind of non-package, non-library start tag
8577: #
8578: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8579: if (defined($token->[2]->{'id'})) {
8580: $unikey.='_'.$token->[2]->{'id'};
8581: }
1.339 albertel 8582: if (defined($token->[2]->{'name'})) {
8583: $unikey.='_'.$token->[2]->{'name'};
8584: }
8585: $metathesekeys{$unikey}=1;
1.736 albertel 8586: foreach my $param (@{$token->[3]}) {
8587: $metaentry{':'.$unikey.'.'.$param} =
8588: $token->[2]->{$param};
1.339 albertel 8589: }
8590: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8591: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8592: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8593: # only ws inside the tag, and not in default, so use default
8594: # as value
1.599 albertel 8595: $metaentry{':'.$unikey}=$default;
1.908 albertel 8596: } elsif ( $internaltext =~ /\S/ ) {
8597: # something interesting inside the tag
8598: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8599: } else {
1.908 albertel 8600: # no interesting values, don't set a default
1.339 albertel 8601: }
1.172 www 8602: # end of not-a-package not-a-library import
1.339 albertel 8603: }
1.172 www 8604: # end of not-a-package start tag
1.339 albertel 8605: }
1.172 www 8606: # the next is the end of "start tag"
1.339 albertel 8607: }
8608: }
1.483 albertel 8609: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8610: $extension = lc($extension);
8611: if ($extension eq 'htm') { $extension='html'; }
8612:
1.737 albertel 8613: foreach my $key (keys(%packagetab)) {
1.483 albertel 8614: #no specific packages #how's our extension
8615: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8616: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8617: \%metathesekeys);
8618: }
1.883 albertel 8619:
8620: if (!exists($metaentry{':packages'})
8621: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8622: foreach my $key (keys(%packagetab)) {
1.483 albertel 8623: #no specific packages well let's get default then
8624: if ($key!~/^default&/) { next; }
1.488 albertel 8625: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8626: \%metathesekeys);
8627: }
8628: }
1.338 www 8629: # are there custom rights to evaluate
1.599 albertel 8630: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8631:
1.338 www 8632: #
8633: # Importing a rights file here
1.339 albertel 8634: #
8635: unless ($depthcount) {
1.599 albertel 8636: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8637: my $dir=$filename;
8638: $dir=~s|[^/]*$||;
8639: $location=&filelocation($dir,$location);
1.736 albertel 8640: my $rights_metadata =
8641: &metadata($uri,'keys',$location,'_rights',
8642: $depthcount+1);
8643: foreach my $rights (split(',',$rights_metadata)) {
8644: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8645: $metathesekeys{$rights}=1;
1.339 albertel 8646: }
8647: }
8648: }
1.737 albertel 8649: # uniqifiy package listing
8650: my %seen;
8651: my @uniq_packages =
8652: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8653: $metaentry{':packages'} = join(',',@uniq_packages);
8654:
1.1070 www 8655: if ($importedparts) {
8656: # We had imported parts and need to rebuild partorder
8657: $metaentry{':partorder'}='';
8658: $metathesekeys{'partorder'}=1;
8659: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8660: if ($origfileimportpartids[$index] eq 'part') {
8661: # original part, part of the problem
8662: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8663: } else {
8664: # we have imported parts at this position
8665: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8666: }
8667: }
8668: $metaentry{':partorder'}=~s/^\,//;
8669: }
8670:
1.737 albertel 8671: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8672: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8673: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8674: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8675: # this is the end of "was not already recently cached
1.71 www 8676: }
1.599 albertel 8677: return $metaentry{':'.$what};
1.261 albertel 8678: }
8679:
1.488 albertel 8680: sub metadata_create_package_def {
1.483 albertel 8681: my ($uri,$key,$package,$metathesekeys)=@_;
8682: my ($pack,$name,$subp)=split(/\&/,$key);
8683: if ($subp eq 'default') { next; }
8684:
1.599 albertel 8685: if (defined($metaentry{':packages'})) {
8686: $metaentry{':packages'}.=','.$package;
1.483 albertel 8687: } else {
1.599 albertel 8688: $metaentry{':packages'}=$package;
1.483 albertel 8689: }
8690: my $value=$packagetab{$key};
8691: my $unikey;
8692: $unikey='parameter_0_'.$name;
1.599 albertel 8693: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8694: $$metathesekeys{$unikey}=1;
1.599 albertel 8695: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8696: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8697: }
1.599 albertel 8698: if (defined($metaentry{':'.$unikey.'.default'})) {
8699: $metaentry{':'.$unikey}=
8700: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8701: }
8702: }
8703:
1.261 albertel 8704: sub metadata_generate_part0 {
8705: my ($metadata,$metacache,$uri) = @_;
8706: my %allnames;
1.737 albertel 8707: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8708: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8709: my $part=$$metacache{':'.$metakey.'.part'};
8710: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8711: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8712: $allnames{$name}=$part;
8713: }
8714: }
8715: }
8716: foreach my $name (keys(%allnames)) {
8717: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8718: my $key=":parameter_0_$name";
1.261 albertel 8719: $$metacache{"$key.part"}='0';
8720: $$metacache{"$key.name"}=$name;
1.428 albertel 8721: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8722: $allnames{$name}.'_'.$name.
8723: '.type'};
1.428 albertel 8724: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8725: '.display'};
1.644 www 8726: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8727: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8728: $$metacache{"$key.display"}=$olddis;
8729: }
1.71 www 8730: }
8731:
1.764 albertel 8732: # ------------------------------------------------------ Devalidate title cache
8733:
8734: sub devalidate_title_cache {
8735: my ($url)=@_;
8736: if (!$env{'request.course.id'}) { return; }
8737: my $symb=&symbread($url);
8738: if (!$symb) { return; }
8739: my $key=$env{'request.course.id'}."\0".$symb;
8740: &devalidate_cache_new('title',$key);
8741: }
8742:
1.1014 droeschl 8743: # ------------------------------------------------- Get the title of a course
8744:
8745: sub current_course_title {
8746: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8747: }
1.301 www 8748: # ------------------------------------------------- Get the title of a resource
8749:
8750: sub gettitle {
8751: my $urlsymb=shift;
8752: my $symb=&symbread($urlsymb);
1.534 albertel 8753: if ($symb) {
1.620 albertel 8754: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8755: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8756: if (defined($cached)) {
8757: return $result;
8758: }
1.534 albertel 8759: my ($map,$resid,$url)=&decode_symb($symb);
8760: my $title='';
1.907 albertel 8761: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8762: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8763: } else {
8764: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8765: &GDBM_READER(),0640)) {
8766: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8767: $title=$bighash{'title_'.$mapid.'.'.$resid};
8768: untie(%bighash);
8769: }
1.534 albertel 8770: }
8771: $title=~s/\&colon\;/\:/gs;
8772: if ($title) {
1.599 albertel 8773: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8774: }
8775: $urlsymb=$url;
8776: }
8777: my $title=&metadata($urlsymb,'title');
8778: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8779: return $title;
1.301 www 8780: }
1.613 albertel 8781:
1.614 albertel 8782: sub get_slot {
8783: my ($which,$cnum,$cdom)=@_;
8784: if (!$cnum || !$cdom) {
1.790 albertel 8785: (undef,my $courseid)=&whichuser();
1.620 albertel 8786: $cdom=$env{'course.'.$courseid.'.domain'};
8787: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8788: }
1.703 albertel 8789: my $key=join("\0",'slots',$cdom,$cnum,$which);
8790: my %slotinfo;
8791: if (exists($remembered{$key})) {
8792: $slotinfo{$which} = $remembered{$key};
8793: } else {
8794: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8795: &Apache::lonhomework::showhash(%slotinfo);
8796: my ($tmp)=keys(%slotinfo);
8797: if ($tmp=~/^error:/) { return (); }
8798: $remembered{$key} = $slotinfo{$which};
8799: }
1.616 albertel 8800: if (ref($slotinfo{$which}) eq 'HASH') {
8801: return %{$slotinfo{$which}};
8802: }
8803: return $slotinfo{$which};
1.614 albertel 8804: }
1.31 www 8805: # ------------------------------------------------- Update symbolic store links
8806:
8807: sub symblist {
8808: my ($mapname,%newhash)=@_;
1.438 www 8809: $mapname=&deversion(&declutter($mapname));
1.31 www 8810: my %hash;
1.620 albertel 8811: if (($env{'request.course.fn'}) && (%newhash)) {
8812: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8813: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8814: foreach my $url (keys(%newhash)) {
1.711 albertel 8815: next if ($url eq 'last_known'
8816: && $env{'form.no_update_last_known'});
8817: $hash{declutter($url)}=&encode_symb($mapname,
8818: $newhash{$url}->[1],
8819: $newhash{$url}->[0]);
1.191 harris41 8820: }
1.31 www 8821: if (untie(%hash)) {
8822: return 'ok';
8823: }
8824: }
8825: }
8826: return 'error';
1.212 www 8827: }
8828:
8829: # --------------------------------------------------------------- Verify a symb
8830:
8831: sub symbverify {
1.510 www 8832: my ($symb,$thisurl)=@_;
8833: my $thisfn=$thisurl;
1.439 www 8834: $thisfn=&declutter($thisfn);
1.215 www 8835: # direct jump to resource in page or to a sequence - will construct own symbs
8836: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8837: # check URL part
1.409 www 8838: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8839:
1.431 www 8840: unless ($url eq $thisfn) { return 0; }
1.213 www 8841:
1.216 www 8842: $symb=&symbclean($symb);
1.510 www 8843: $thisurl=&deversion($thisurl);
1.439 www 8844: $thisfn=&deversion($thisfn);
1.213 www 8845:
8846: my %bighash;
8847: my $okay=0;
1.431 www 8848:
1.620 albertel 8849: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8850: &GDBM_READER(),0640)) {
1.1032 raeburn 8851: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8852: $thisurl =~ s/\?.+$//;
8853: }
1.510 www 8854: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8855: unless ($ids) {
1.510 www 8856: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8857: }
8858: if ($ids) {
8859: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8860: foreach my $id (split(/\,/,$ids)) {
8861: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8862: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8863: $symb =~ s/\?.+$//;
8864: }
1.216 www 8865: if (
8866: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8867: eq $symb) {
1.620 albertel 8868: if (($env{'request.role.adv'}) ||
1.800 albertel 8869: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8870: $okay=1;
8871: }
8872: }
1.216 www 8873: }
8874: }
1.213 www 8875: untie(%bighash);
8876: }
8877: return $okay;
1.31 www 8878: }
8879:
1.210 www 8880: # --------------------------------------------------------------- Clean-up symb
8881:
8882: sub symbclean {
8883: my $symb=shift;
1.568 albertel 8884: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8885: # remove version from map
8886: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8887:
1.210 www 8888: # remove version from URL
8889: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8890:
1.507 www 8891: # remove wrapper
8892:
1.510 www 8893: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8894: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8895: return $symb;
1.409 www 8896: }
8897:
8898: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8899:
8900: sub encode_symb {
8901: my ($map,$resid,$url)=@_;
8902: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8903: }
1.409 www 8904:
8905: sub decode_symb {
1.568 albertel 8906: my $symb=shift;
8907: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8908: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8909: return (&fixversion($map),$resid,&fixversion($url));
8910: }
8911:
8912: sub fixversion {
8913: my $fn=shift;
1.609 banghart 8914: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8915: my %bighash;
8916: my $uri=&clutter($fn);
1.620 albertel 8917: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8918: # is this cached?
1.599 albertel 8919: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8920: if (defined($cached)) { return $result; }
8921: # unfortunately not cached, or expired
1.620 albertel 8922: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8923: &GDBM_READER(),0640)) {
8924: if ($bighash{'version_'.$uri}) {
8925: my $version=$bighash{'version_'.$uri};
1.444 www 8926: unless (($version eq 'mostrecent') ||
8927: ($version==&getversion($uri))) {
1.440 www 8928: $uri=~s/\.(\w+)$/\.$version\.$1/;
8929: }
8930: }
8931: untie %bighash;
1.413 www 8932: }
1.599 albertel 8933: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8934: }
8935:
8936: sub deversion {
8937: my $url=shift;
8938: $url=~s/\.\d+\.(\w+)$/\.$1/;
8939: return $url;
1.210 www 8940: }
8941:
1.31 www 8942: # ------------------------------------------------------ Return symb list entry
8943:
8944: sub symbread {
1.249 www 8945: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8946: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8947: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8948: # no filename provided? try from environment
1.44 www 8949: unless ($thisfn) {
1.620 albertel 8950: if ($env{'request.symb'}) {
8951: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8952: }
1.620 albertel 8953: $thisfn=$env{'request.filename'};
1.44 www 8954: }
1.569 albertel 8955: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8956: # is that filename actually a symb? Verify, clean, and return
8957: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8958: if (&symbverify($thisfn,$1)) {
1.620 albertel 8959: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8960: }
1.242 www 8961: }
1.44 www 8962: $thisfn=declutter($thisfn);
1.31 www 8963: my %hash;
1.37 www 8964: my %bighash;
8965: my $syval='';
1.620 albertel 8966: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8967: my $targetfn = $thisfn;
1.609 banghart 8968: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8969: $targetfn = 'adm/wrapper/'.$thisfn;
8970: }
1.687 albertel 8971: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8972: $targetfn=$1;
8973: }
1.620 albertel 8974: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8975: &GDBM_READER(),0640)) {
1.481 raeburn 8976: $syval=$hash{$targetfn};
1.37 www 8977: untie(%hash);
8978: }
8979: # ---------------------------------------------------------- There was an entry
8980: if ($syval) {
1.601 albertel 8981: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8982: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8983: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8984: #return $env{$cache_str}='';
1.601 albertel 8985: #}
8986: #$syval.=$1;
8987: #}
1.37 www 8988: } else {
8989: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8990: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8991: &GDBM_READER(),0640)) {
1.37 www 8992: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8993: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8994: unless ($ids) {
8995: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8996: }
8997: unless ($ids) {
8998: # alias?
8999: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9000: }
1.37 www 9001: if ($ids) {
9002: # ------------------------------------------------------------------- Has ID(s)
9003: my @possibilities=split(/\,/,$ids);
1.39 www 9004: if ($#possibilities==0) {
9005: # ----------------------------------------------- There is only one possibility
1.37 www 9006: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9007: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9008: $resid,$thisfn);
1.249 www 9009: } elsif (!$donotrecurse) {
1.39 www 9010: # ------------------------------------------ There is more than one possibility
9011: my $realpossible=0;
1.800 albertel 9012: foreach my $id (@possibilities) {
9013: my $file=$bighash{'src_'.$id};
1.39 www 9014: if (&allowed('bre',$file)) {
1.800 albertel 9015: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9016: if ($bighash{'map_type_'.$mapid} ne 'page') {
9017: $realpossible++;
1.626 albertel 9018: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9019: $resid,$thisfn);
1.39 www 9020: }
9021: }
1.191 harris41 9022: }
1.39 www 9023: if ($realpossible!=1) { $syval=''; }
1.249 www 9024: } else {
9025: $syval='';
1.37 www 9026: }
9027: }
9028: untie(%bighash)
1.481 raeburn 9029: }
1.31 www 9030: }
1.62 www 9031: if ($syval) {
1.620 albertel 9032: return $env{$cache_str}=$syval;
1.62 www 9033: }
1.31 www 9034: }
1.949 raeburn 9035: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9036: return $env{$cache_str}='';
1.31 www 9037: }
9038:
9039: # ---------------------------------------------------------- Return random seed
9040:
1.32 www 9041: sub numval {
9042: my $txt=shift;
9043: $txt=~tr/A-J/0-9/;
9044: $txt=~tr/a-j/0-9/;
9045: $txt=~tr/K-T/0-9/;
9046: $txt=~tr/k-t/0-9/;
9047: $txt=~tr/U-Z/0-5/;
9048: $txt=~tr/u-z/0-5/;
9049: $txt=~s/\D//g;
1.564 albertel 9050: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9051: return int($txt);
1.368 albertel 9052: }
9053:
1.484 albertel 9054: sub numval2 {
9055: my $txt=shift;
9056: $txt=~tr/A-J/0-9/;
9057: $txt=~tr/a-j/0-9/;
9058: $txt=~tr/K-T/0-9/;
9059: $txt=~tr/k-t/0-9/;
9060: $txt=~tr/U-Z/0-5/;
9061: $txt=~tr/u-z/0-5/;
9062: $txt=~s/\D//g;
9063: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9064: my $total;
9065: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9066: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9067: return int($total);
9068: }
9069:
1.575 albertel 9070: sub numval3 {
9071: use integer;
9072: my $txt=shift;
9073: $txt=~tr/A-J/0-9/;
9074: $txt=~tr/a-j/0-9/;
9075: $txt=~tr/K-T/0-9/;
9076: $txt=~tr/k-t/0-9/;
9077: $txt=~tr/U-Z/0-5/;
9078: $txt=~tr/u-z/0-5/;
9079: $txt=~s/\D//g;
9080: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9081: my $total;
9082: foreach my $val (@txts) { $total+=$val; }
9083: if ($_64bit) { $total=(($total<<32)>>32); }
9084: return $total;
9085: }
9086:
1.675 albertel 9087: sub digest {
9088: my ($data)=@_;
9089: my $digest=&Digest::MD5::md5($data);
9090: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9091: my ($e,$f);
9092: {
9093: use integer;
9094: $e=($a+$b);
9095: $f=($c+$d);
9096: if ($_64bit) {
9097: $e=(($e<<32)>>32);
9098: $f=(($f<<32)>>32);
9099: }
9100: }
9101: if (wantarray) {
9102: return ($e,$f);
9103: } else {
9104: my $g;
9105: {
9106: use integer;
9107: $g=($e+$f);
9108: if ($_64bit) {
9109: $g=(($g<<32)>>32);
9110: }
9111: }
9112: return $g;
9113: }
9114: }
9115:
1.368 albertel 9116: sub latest_rnd_algorithm_id {
1.675 albertel 9117: return '64bit5';
1.366 albertel 9118: }
1.32 www 9119:
1.503 albertel 9120: sub get_rand_alg {
9121: my ($courseid)=@_;
1.790 albertel 9122: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9123: if ($courseid) {
1.620 albertel 9124: return $env{"course.$courseid.rndseed"};
1.503 albertel 9125: }
9126: return &latest_rnd_algorithm_id();
9127: }
9128:
1.562 albertel 9129: sub validCODE {
9130: my ($CODE)=@_;
9131: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9132: return 0;
9133: }
9134:
1.491 albertel 9135: sub getCODE {
1.620 albertel 9136: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9137: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9138: defined($Apache::lonhomework::parsing_a_task) ) &&
9139: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9140: return $Apache::lonhomework::history{'resource.CODE'};
9141: }
9142: return undef;
9143: }
9144:
1.31 www 9145: sub rndseed {
1.155 albertel 9146: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9147: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9148: if (!defined($symb)) {
1.366 albertel 9149: unless ($symb=$wsymb) { return time; }
9150: }
9151: if (!$courseid) { $courseid=$wcourseid; }
9152: if (!$domain) { $domain=$wdomain; }
9153: if (!$username) { $username=$wusername }
1.503 albertel 9154: my $which=&get_rand_alg();
1.803 albertel 9155:
1.491 albertel 9156: if (defined(&getCODE())) {
1.675 albertel 9157: if ($which eq '64bit5') {
9158: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9159: } elsif ($which eq '64bit4') {
1.575 albertel 9160: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9161: } else {
9162: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9163: }
1.675 albertel 9164: } elsif ($which eq '64bit5') {
9165: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9166: } elsif ($which eq '64bit4') {
9167: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9168: } elsif ($which eq '64bit3') {
9169: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9170: } elsif ($which eq '64bit2') {
9171: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9172: } elsif ($which eq '64bit') {
9173: return &rndseed_64bit($symb,$courseid,$domain,$username);
9174: }
9175: return &rndseed_32bit($symb,$courseid,$domain,$username);
9176: }
9177:
9178: sub rndseed_32bit {
9179: my ($symb,$courseid,$domain,$username)=@_;
9180: {
9181: use integer;
9182: my $symbchck=unpack("%32C*",$symb) << 27;
9183: my $symbseed=numval($symb) << 22;
9184: my $namechck=unpack("%32C*",$username) << 17;
9185: my $nameseed=numval($username) << 12;
9186: my $domainseed=unpack("%32C*",$domain) << 7;
9187: my $courseseed=unpack("%32C*",$courseid);
9188: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9189: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9190: #&logthis("rndseed :$num:$symb");
1.564 albertel 9191: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9192: return $num;
9193: }
9194: }
9195:
9196: sub rndseed_64bit {
9197: my ($symb,$courseid,$domain,$username)=@_;
9198: {
9199: use integer;
9200: my $symbchck=unpack("%32S*",$symb) << 21;
9201: my $symbseed=numval($symb) << 10;
9202: my $namechck=unpack("%32S*",$username);
9203:
9204: my $nameseed=numval($username) << 21;
9205: my $domainseed=unpack("%32S*",$domain) << 10;
9206: my $courseseed=unpack("%32S*",$courseid);
9207:
9208: my $num1=$symbchck+$symbseed+$namechck;
9209: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9210: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9211: #&logthis("rndseed :$num:$symb");
1.564 albertel 9212: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9213: return "$num1,$num2";
1.155 albertel 9214: }
1.366 albertel 9215: }
9216:
1.443 albertel 9217: sub rndseed_64bit2 {
9218: my ($symb,$courseid,$domain,$username)=@_;
9219: {
9220: use integer;
9221: # strings need to be an even # of cahracters long, it it is odd the
9222: # last characters gets thrown away
9223: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9224: my $symbseed=numval($symb) << 10;
9225: my $namechck=unpack("%32S*",$username.' ');
9226:
9227: my $nameseed=numval($username) << 21;
1.501 albertel 9228: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9229: my $courseseed=unpack("%32S*",$courseid.' ');
9230:
9231: my $num1=$symbchck+$symbseed+$namechck;
9232: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9233: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9234: #&logthis("rndseed :$num:$symb");
1.803 albertel 9235: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9236: return "$num1,$num2";
9237: }
9238: }
9239:
9240: sub rndseed_64bit3 {
9241: my ($symb,$courseid,$domain,$username)=@_;
9242: {
9243: use integer;
9244: # strings need to be an even # of cahracters long, it it is odd the
9245: # last characters gets thrown away
9246: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9247: my $symbseed=numval2($symb) << 10;
9248: my $namechck=unpack("%32S*",$username.' ');
9249:
9250: my $nameseed=numval2($username) << 21;
1.443 albertel 9251: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9252: my $courseseed=unpack("%32S*",$courseid.' ');
9253:
9254: my $num1=$symbchck+$symbseed+$namechck;
9255: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9256: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9257: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9258: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9259:
1.503 albertel 9260: return "$num1:$num2";
1.443 albertel 9261: }
9262: }
9263:
1.575 albertel 9264: sub rndseed_64bit4 {
9265: my ($symb,$courseid,$domain,$username)=@_;
9266: {
9267: use integer;
9268: # strings need to be an even # of cahracters long, it it is odd the
9269: # last characters gets thrown away
9270: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9271: my $symbseed=numval3($symb) << 10;
9272: my $namechck=unpack("%32S*",$username.' ');
9273:
9274: my $nameseed=numval3($username) << 21;
9275: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9276: my $courseseed=unpack("%32S*",$courseid.' ');
9277:
9278: my $num1=$symbchck+$symbseed+$namechck;
9279: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9280: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9281: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9282: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9283:
9284: return "$num1:$num2";
9285: }
9286: }
9287:
1.675 albertel 9288: sub rndseed_64bit5 {
9289: my ($symb,$courseid,$domain,$username)=@_;
9290: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9291: return "$num1:$num2";
9292: }
9293:
1.366 albertel 9294: sub rndseed_CODE_64bit {
9295: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9296: {
1.366 albertel 9297: use integer;
1.443 albertel 9298: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9299: my $symbseed=numval2($symb);
1.491 albertel 9300: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9301: my $CODEseed=numval(&getCODE());
1.443 albertel 9302: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9303: my $num1=$symbseed+$CODEchck;
9304: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9305: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9306: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9307: if ($_64bit) { $num1=(($num1<<32)>>32); }
9308: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9309: return "$num1:$num2";
1.366 albertel 9310: }
9311: }
9312:
1.575 albertel 9313: sub rndseed_CODE_64bit4 {
9314: my ($symb,$courseid,$domain,$username)=@_;
9315: {
9316: use integer;
9317: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9318: my $symbseed=numval3($symb);
9319: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9320: my $CODEseed=numval3(&getCODE());
9321: my $courseseed=unpack("%32S*",$courseid.' ');
9322: my $num1=$symbseed+$CODEchck;
9323: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9324: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9325: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9326: if ($_64bit) { $num1=(($num1<<32)>>32); }
9327: if ($_64bit) { $num2=(($num2<<32)>>32); }
9328: return "$num1:$num2";
9329: }
9330: }
9331:
1.675 albertel 9332: sub rndseed_CODE_64bit5 {
9333: my ($symb,$courseid,$domain,$username)=@_;
9334: my $code = &getCODE();
9335: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9336: return "$num1:$num2";
9337: }
9338:
1.366 albertel 9339: sub setup_random_from_rndseed {
9340: my ($rndseed)=@_;
1.503 albertel 9341: if ($rndseed =~/([,:])/) {
9342: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9343: &Math::Random::random_set_seed(abs($num1),abs($num2));
9344: } else {
9345: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9346: }
1.36 albertel 9347: }
9348:
1.474 albertel 9349: sub latest_receipt_algorithm_id {
1.835 albertel 9350: return 'receipt3';
1.474 albertel 9351: }
9352:
1.480 www 9353: sub recunique {
9354: my $fucourseid=shift;
9355: my $unique;
1.835 albertel 9356: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9357: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9358: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9359: } else {
9360: $unique=$perlvar{'lonReceipt'};
9361: }
9362: return unpack("%32C*",$unique);
9363: }
9364:
9365: sub recprefix {
9366: my $fucourseid=shift;
9367: my $prefix;
1.835 albertel 9368: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9369: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9370: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9371: } else {
9372: $prefix=$perlvar{'lonHostID'};
9373: }
9374: return unpack("%32C*",$prefix);
9375: }
9376:
1.76 www 9377: sub ireceipt {
1.474 albertel 9378: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9379:
9380: my $return =&recprefix($fucourseid).'-';
9381:
9382: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9383: $env{'request.state'} eq 'construct') {
9384: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9385: return $return;
9386: }
9387:
1.76 www 9388: my $cuname=unpack("%32C*",$funame);
9389: my $cudom=unpack("%32C*",$fudom);
9390: my $cucourseid=unpack("%32C*",$fucourseid);
9391: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9392: my $cunique=&recunique($fucourseid);
1.474 albertel 9393: my $cpart=unpack("%32S*",$part);
1.835 albertel 9394: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9395:
1.790 albertel 9396: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9397:
9398: $return.= ($cunique%$cuname+
9399: $cunique%$cudom+
9400: $cusymb%$cuname+
9401: $cusymb%$cudom+
9402: $cucourseid%$cuname+
9403: $cucourseid%$cudom+
9404: $cpart%$cuname+
9405: $cpart%$cudom);
9406: } else {
9407: $return.= ($cunique%$cuname+
9408: $cunique%$cudom+
9409: $cusymb%$cuname+
9410: $cusymb%$cudom+
9411: $cucourseid%$cuname+
9412: $cucourseid%$cudom);
9413: }
9414: return $return;
1.76 www 9415: }
9416:
9417: sub receipt {
1.474 albertel 9418: my ($part)=@_;
1.790 albertel 9419: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9420: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9421: }
1.260 ng 9422:
1.790 albertel 9423: sub whichuser {
9424: my ($passedsymb)=@_;
9425: my ($symb,$courseid,$domain,$name,$publicuser);
9426: if (defined($env{'form.grade_symb'})) {
9427: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9428: my $allowed=&allowed('vgr',$tmp_courseid);
9429: if (!$allowed &&
9430: exists($env{'request.course.sec'}) &&
9431: $env{'request.course.sec'} !~ /^\s*$/) {
9432: $allowed=&allowed('vgr',$tmp_courseid.
9433: '/'.$env{'request.course.sec'});
9434: }
9435: if ($allowed) {
9436: ($symb)=&get_env_multiple('form.grade_symb');
9437: $courseid=$tmp_courseid;
9438: ($domain)=&get_env_multiple('form.grade_domain');
9439: ($name)=&get_env_multiple('form.grade_username');
9440: return ($symb,$courseid,$domain,$name,$publicuser);
9441: }
9442: }
9443: if (!$passedsymb) {
9444: $symb=&symbread();
9445: } else {
9446: $symb=$passedsymb;
9447: }
9448: $courseid=$env{'request.course.id'};
9449: $domain=$env{'user.domain'};
9450: $name=$env{'user.name'};
9451: if ($name eq 'public' && $domain eq 'public') {
9452: if (!defined($env{'form.username'})) {
9453: $env{'form.username'}.=time.rand(10000000);
9454: }
9455: $name.=$env{'form.username'};
9456: }
9457: return ($symb,$courseid,$domain,$name,$publicuser);
9458:
9459: }
9460:
1.36 albertel 9461: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9462: # returns either the contents of the file or
9463: # -1 if the file doesn't exist
1.481 raeburn 9464: #
9465: # if the target is a file that was uploaded via DOCS,
9466: # a check will be made to see if a current copy exists on the local server,
9467: # if it does this will be served, otherwise a copy will be retrieved from
9468: # the home server for the course and stored in /home/httpd/html/userfiles on
9469: # the local server.
1.472 albertel 9470:
1.36 albertel 9471: sub getfile {
1.538 albertel 9472: my ($file) = @_;
1.609 banghart 9473: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9474: &repcopy($file);
9475: return &readfile($file);
9476: }
9477:
9478: sub repcopy_userfile {
9479: my ($file)=@_;
1.609 banghart 9480: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9481: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9482: my ($cdom,$cnum,$filename) =
1.811 albertel 9483: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9484: my $uri="/uploaded/$cdom/$cnum/$filename";
9485: if (-e "$file") {
1.828 www 9486: # we already have a local copy, check it out
1.538 albertel 9487: my @fileinfo = stat($file);
1.828 www 9488: my $rtncode;
9489: my $info;
1.538 albertel 9490: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9491: if ($lwpresp ne 'ok') {
1.828 www 9492: # there is no such file anymore, even though we had a local copy
1.482 albertel 9493: if ($rtncode eq '404') {
1.538 albertel 9494: unlink($file);
1.482 albertel 9495: }
9496: return -1;
9497: }
9498: if ($info < $fileinfo[9]) {
1.828 www 9499: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9500: return 'ok';
1.828 www 9501: } else {
9502: # the file is outdated, get rid of it
9503: unlink($file);
1.482 albertel 9504: }
1.828 www 9505: }
9506: # one way or the other, at this point, we don't have the file
9507: # construct the correct path for the file
9508: my @parts = ($cdom,$cnum);
9509: if ($filename =~ m|^(.+)/[^/]+$|) {
9510: push @parts, split(/\//,$1);
9511: }
9512: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9513: foreach my $part (@parts) {
9514: $path .= '/'.$part;
9515: if (!-e $path) {
9516: mkdir($path,0770);
1.482 albertel 9517: }
9518: }
1.828 www 9519: # now the path exists for sure
9520: # get a user agent
9521: my $ua=new LWP::UserAgent;
9522: my $transferfile=$file.'.in.transfer';
9523: # FIXME: this should flock
9524: if (-e $transferfile) { return 'ok'; }
9525: my $request;
9526: $uri=~s/^\///;
1.980 raeburn 9527: my $homeserver = &homeserver($cnum,$cdom);
9528: my $protocol = $protocol{$homeserver};
9529: $protocol = 'http' if ($protocol ne 'https');
9530: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9531: my $response=$ua->request($request,$transferfile);
9532: # did it work?
9533: if ($response->is_error()) {
9534: unlink($transferfile);
9535: &logthis("Userfile repcopy failed for $uri");
9536: return -1;
9537: }
9538: # worked, rename the transfer file
9539: rename($transferfile,$file);
1.607 raeburn 9540: return 'ok';
1.481 raeburn 9541: }
9542:
1.517 albertel 9543: sub tokenwrapper {
9544: my $uri=shift;
1.980 raeburn 9545: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9546: $uri=~s|^/||;
1.620 albertel 9547: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9548: my $token=$1;
1.552 albertel 9549: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9550: if ($udom && $uname && $file) {
9551: $file=~s|(\?\.*)*$||;
1.949 raeburn 9552: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9553: my $homeserver = &homeserver($uname,$udom);
9554: my $protocol = $protocol{$homeserver};
9555: $protocol = 'http' if ($protocol ne 'https');
9556: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9557: (($uri=~/\?/)?'&':'?').'token='.$token.
9558: '&tokenissued='.$perlvar{'lonHostID'};
9559: } else {
9560: return '/adm/notfound.html';
9561: }
9562: }
9563:
1.828 www 9564: # call with reqtype HEAD: get last modification time
9565: # call with reqtype GET: get the file contents
9566: # Do not call this with reqtype GET for large files! It loads everything into memory
9567: #
1.481 raeburn 9568: sub getuploaded {
9569: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9570: $uri=~s/^\///;
1.980 raeburn 9571: my $homeserver = &homeserver($cnum,$cdom);
9572: my $protocol = $protocol{$homeserver};
9573: $protocol = 'http' if ($protocol ne 'https');
9574: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9575: my $ua=new LWP::UserAgent;
9576: my $request=new HTTP::Request($reqtype,$uri);
9577: my $response=$ua->request($request);
9578: $$rtncode = $response->code;
1.482 albertel 9579: if (! $response->is_success()) {
9580: return 'failed';
9581: }
9582: if ($reqtype eq 'HEAD') {
1.486 www 9583: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9584: } elsif ($reqtype eq 'GET') {
9585: $$info = $response->content;
1.472 albertel 9586: }
1.482 albertel 9587: return 'ok';
1.36 albertel 9588: }
9589:
1.481 raeburn 9590: sub readfile {
9591: my $file = shift;
9592: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9593: my $fh;
9594: open($fh,"<$file");
9595: my $a='';
1.800 albertel 9596: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9597: return $a;
9598: }
9599:
1.36 albertel 9600: sub filelocation {
1.590 banghart 9601: my ($dir,$file) = @_;
9602: my $location;
9603: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9604:
9605: if ($file =~ m-^/adm/-) {
9606: $file=~s-^/adm/wrapper/-/-;
9607: $file=~s-^/adm/coursedocs/showdoc/-/-;
9608: }
1.882 albertel 9609:
1.590 banghart 9610: if ($file=~m:^/~:) { # is a contruction space reference
9611: $location = $file;
9612: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9613: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9614: # is a correct contruction space reference
9615: $location = $file;
1.956 raeburn 9616: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9617: $location = $file;
1.609 banghart 9618: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9619: my ($udom,$uname,$filename)=
1.811 albertel 9620: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9621: my $home=&homeserver($uname,$udom);
9622: my $is_me=0;
9623: my @ids=¤t_machine_ids();
9624: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9625: if ($is_me) {
1.955 raeburn 9626: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9627: } else {
9628: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9629: $udom.'/'.$uname.'/'.$filename;
9630: }
1.882 albertel 9631: } elsif ($file =~ m-^/adm/-) {
9632: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9633: } else {
9634: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9635: $file=~s:^/res/:/:;
9636: if ( !( $file =~ m:^/:) ) {
9637: $location = $dir. '/'.$file;
9638: } else {
9639: $location = '/home/httpd/html/res'.$file;
9640: }
1.59 albertel 9641: }
1.590 banghart 9642: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9643: while ($location=~m{/\.\./}) {
9644: if ($location =~ m{/[^/]+/\.\./}) {
9645: $location=~ s{/[^/]+/\.\./}{/}g;
9646: } else {
9647: $location=~ s{/\.\./}{/}g;
9648: }
9649: } #remove dir/..
1.590 banghart 9650: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9651: return $location;
1.46 www 9652: }
1.36 albertel 9653:
1.46 www 9654: sub hreflocation {
9655: my ($dir,$file)=@_;
1.980 raeburn 9656: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9657: $file=filelocation($dir,$file);
1.700 albertel 9658: } elsif ($file=~m-^/adm/-) {
9659: $file=~s-^/adm/wrapper/-/-;
9660: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9661: }
9662: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9663: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9664: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9665: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9666: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9667: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9668: -/uploaded/$1/$2/-x;
1.46 www 9669: }
1.913 albertel 9670: if ($file=~ m{^/userfiles/}) {
9671: $file =~ s{^/userfiles/}{/uploaded/};
9672: }
1.462 albertel 9673: return $file;
1.465 albertel 9674: }
9675:
9676: sub current_machine_domains {
1.853 albertel 9677: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9678: }
9679:
9680: sub machine_domains {
9681: my ($hostname) = @_;
1.465 albertel 9682: my @domains;
1.838 albertel 9683: my %hostname = &all_hostnames();
1.465 albertel 9684: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9685: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9686: if ($hostname eq $name) {
1.844 albertel 9687: push(@domains,&host_domain($id));
1.465 albertel 9688: }
9689: }
9690: return @domains;
9691: }
9692:
9693: sub current_machine_ids {
1.853 albertel 9694: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9695: }
9696:
9697: sub machine_ids {
9698: my ($hostname) = @_;
9699: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9700: my @ids;
1.888 albertel 9701: my %name_to_host = &all_names();
1.889 albertel 9702: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9703: return @{ $name_to_host{$hostname} };
9704: }
9705: return;
1.31 www 9706: }
9707:
1.824 raeburn 9708: sub additional_machine_domains {
9709: my @domains;
9710: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9711: while( my $line = <$fh>) {
9712: $line =~ s/\s//g;
9713: push(@domains,$line);
9714: }
9715: return @domains;
9716: }
9717:
9718: sub default_login_domain {
9719: my $domain = $perlvar{'lonDefDomain'};
9720: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9721: foreach my $posdom (¤t_machine_domains(),
9722: &additional_machine_domains()) {
9723: if (lc($posdom) eq lc($testdomain)) {
9724: $domain=$posdom;
9725: last;
9726: }
9727: }
9728: return $domain;
9729: }
9730:
1.31 www 9731: # ------------------------------------------------------------- Declutters URLs
9732:
9733: sub declutter {
9734: my $thisfn=shift;
1.569 albertel 9735: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9736: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9737: $thisfn=~s/^\///;
1.697 albertel 9738: $thisfn=~s|^adm/wrapper/||;
9739: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9740: $thisfn=~s/^res\///;
1.1032 raeburn 9741: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9742: $thisfn=~s/\?.+$//;
9743: }
1.268 www 9744: return $thisfn;
9745: }
9746:
9747: # ------------------------------------------------------------- Clutter up URLs
9748:
9749: sub clutter {
9750: my $thisfn='/'.&declutter(shift);
1.887 albertel 9751: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9752: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9753: $thisfn='/res'.$thisfn;
9754: }
1.1031 raeburn 9755: if ($thisfn !~m|^/adm|) {
9756: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9757: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9758: } else {
9759: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9760: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9761: if ($embstyle eq 'ssi'
9762: || ($embstyle eq 'hdn')
9763: || ($embstyle eq 'rat')
9764: || ($embstyle eq 'prv')
9765: || ($embstyle eq 'ign')) {
9766: #do nothing with these
9767: } elsif (($embstyle eq 'img')
1.695 albertel 9768: || ($embstyle eq 'emb')
9769: || ($embstyle eq 'wrp')) {
9770: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9771: } elsif ($embstyle eq 'unk'
9772: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9773: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9774: } else {
1.718 www 9775: # &logthis("Got a blank emb style");
1.695 albertel 9776: }
1.694 albertel 9777: }
9778: }
1.31 www 9779: return $thisfn;
1.12 www 9780: }
9781:
1.787 albertel 9782: sub clutter_with_no_wrapper {
9783: my $uri = &clutter(shift);
9784: if ($uri =~ m-^/adm/-) {
9785: $uri =~ s-^/adm/wrapper/-/-;
9786: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9787: }
9788: return $uri;
9789: }
9790:
1.557 albertel 9791: sub freeze_escape {
9792: my ($value)=@_;
9793: if (ref($value)) {
9794: $value=&nfreeze($value);
9795: return '__FROZEN__'.&escape($value);
9796: }
9797: return &escape($value);
9798: }
9799:
1.11 www 9800:
1.557 albertel 9801: sub thaw_unescape {
9802: my ($value)=@_;
9803: if ($value =~ /^__FROZEN__/) {
9804: substr($value,0,10,undef);
9805: $value=&unescape($value);
9806: return &thaw($value);
9807: }
9808: return &unescape($value);
9809: }
9810:
1.436 albertel 9811: sub correct_line_ends {
9812: my ($result)=@_;
9813: $$result =~s/\r\n/\n/mg;
9814: $$result =~s/\r/\n/mg;
1.415 albertel 9815: }
1.1 albertel 9816: # ================================================================ Main Program
9817:
1.184 www 9818: sub goodbye {
1.204 albertel 9819: &logthis("Starting Shut down");
1.443 albertel 9820: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9821: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9822: #converted
1.599 albertel 9823: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9824: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9825: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9826: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9827: #1.1 only
1.870 albertel 9828: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9829: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9830: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9831: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9832: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9833: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9834: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9835: &flushcourselogs();
9836: &logthis("Shutting down");
9837: }
9838:
1.852 albertel 9839: sub get_dns {
1.869 albertel 9840: my ($url,$func,$ignore_cache) = @_;
9841: if (!$ignore_cache) {
9842: my ($content,$cached)=
9843: &Apache::lonnet::is_cached_new('dns',$url);
9844: if ($cached) {
9845: &$func($content);
9846: return;
9847: }
9848: }
9849:
9850: my %alldns;
1.852 albertel 9851: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9852: foreach my $dns (<$config>) {
9853: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9854: my $line = $1;
9855: my ($host,$protocol) = split(/:/,$line);
9856: if ($protocol ne 'https') {
9857: $protocol = 'http';
9858: }
9859: $alldns{$host} = $protocol;
1.869 albertel 9860: }
9861: while (%alldns) {
9862: my ($dns) = keys(%alldns);
1.852 albertel 9863: my $ua=new LWP::UserAgent;
1.979 raeburn 9864: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9865: my $response=$ua->request($request);
1.979 raeburn 9866: delete($alldns{$dns});
1.852 albertel 9867: next if ($response->is_error());
9868: my @content = split("\n",$response->content);
1.869 albertel 9869: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9870: &$func(\@content);
1.869 albertel 9871: return;
1.852 albertel 9872: }
9873: close($config);
1.871 albertel 9874: my $which = (split('/',$url))[3];
9875: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9876: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9877: my @content = <$config>;
9878: &$func(\@content);
9879: return;
1.852 albertel 9880: }
1.327 albertel 9881: # ------------------------------------------------------------ Read domain file
9882: {
1.852 albertel 9883: my $loaded;
1.846 albertel 9884: my %domain;
9885:
1.852 albertel 9886: sub parse_domain_tab {
9887: my ($lines) = @_;
9888: foreach my $line (@$lines) {
9889: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9890:
1.846 albertel 9891: chomp($line);
1.852 albertel 9892: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9893: my %this_domain;
9894: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9895: 'lang_def', 'city', 'longi', 'lati',
9896: 'primary') {
9897: $this_domain{$field} = shift(@elements);
9898: }
9899: $domain{$name} = \%this_domain;
1.852 albertel 9900: }
9901: }
1.864 albertel 9902:
9903: sub reset_domain_info {
9904: undef($loaded);
9905: undef(%domain);
9906: }
9907:
1.852 albertel 9908: sub load_domain_tab {
1.869 albertel 9909: my ($ignore_cache) = @_;
9910: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9911: my $fh;
9912: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9913: my @lines = <$fh>;
9914: &parse_domain_tab(\@lines);
1.448 albertel 9915: }
1.852 albertel 9916: close($fh);
9917: $loaded = 1;
1.327 albertel 9918: }
1.846 albertel 9919:
9920: sub domain {
1.852 albertel 9921: &load_domain_tab() if (!$loaded);
9922:
1.846 albertel 9923: my ($name,$what) = @_;
9924: return if ( !exists($domain{$name}) );
9925:
9926: if (!$what) {
9927: return $domain{$name}{'description'};
9928: }
9929: return $domain{$name}{$what};
9930: }
1.974 raeburn 9931:
9932: sub domain_info {
9933: &load_domain_tab() if (!$loaded);
9934: return %domain;
9935: }
9936:
1.327 albertel 9937: }
9938:
9939:
1.1 albertel 9940: # ------------------------------------------------------------- Read hosts file
9941: {
1.838 albertel 9942: my %hostname;
1.844 albertel 9943: my %hostdom;
1.845 albertel 9944: my %libserv;
1.852 albertel 9945: my $loaded;
1.888 albertel 9946: my %name_to_host;
1.1074 raeburn 9947: my %internetdom;
1.852 albertel 9948:
9949: sub parse_hosts_tab {
9950: my ($file) = @_;
9951: foreach my $configline (@$file) {
9952: next if ($configline =~ /^(\#|\s*$ )/x);
9953: next if ($configline =~ /^\^/);
9954: chomp($configline);
1.1074 raeburn 9955: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 9956: $name=~s/\s//g;
9957: if ($id && $domain && $role && $name) {
9958: $hostname{$id}=$name;
1.888 albertel 9959: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9960: $hostdom{$id}=$domain;
9961: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9962: if (defined($protocol)) {
9963: if ($protocol eq 'https') {
9964: $protocol{$id} = $protocol;
9965: } else {
9966: $protocol{$id} = 'http';
9967: }
1.968 raeburn 9968: } else {
1.969 raeburn 9969: $protocol{$id} = 'http';
1.968 raeburn 9970: }
1.1074 raeburn 9971: if (defined($intdom)) {
9972: $internetdom{$id} = $intdom;
9973: }
1.852 albertel 9974: }
9975: }
9976: }
1.864 albertel 9977:
9978: sub reset_hosts_info {
1.897 albertel 9979: &purge_remembered();
1.864 albertel 9980: &reset_domain_info();
9981: &reset_hosts_ip_info();
1.892 albertel 9982: undef(%name_to_host);
1.864 albertel 9983: undef(%hostname);
9984: undef(%hostdom);
9985: undef(%libserv);
9986: undef($loaded);
9987: }
1.1 albertel 9988:
1.852 albertel 9989: sub load_hosts_tab {
1.869 albertel 9990: my ($ignore_cache) = @_;
9991: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9992: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9993: my @config = <$config>;
9994: &parse_hosts_tab(\@config);
9995: close($config);
9996: $loaded=1;
1.1 albertel 9997: }
1.852 albertel 9998:
1.838 albertel 9999: sub hostname {
1.852 albertel 10000: &load_hosts_tab() if (!$loaded);
10001:
1.838 albertel 10002: my ($lonid) = @_;
10003: return $hostname{$lonid};
10004: }
1.845 albertel 10005:
1.838 albertel 10006: sub all_hostnames {
1.852 albertel 10007: &load_hosts_tab() if (!$loaded);
10008:
1.838 albertel 10009: return %hostname;
10010: }
1.845 albertel 10011:
1.888 albertel 10012: sub all_names {
10013: &load_hosts_tab() if (!$loaded);
10014:
10015: return %name_to_host;
10016: }
10017:
1.974 raeburn 10018: sub all_host_domain {
10019: &load_hosts_tab() if (!$loaded);
10020: return %hostdom;
10021: }
10022:
1.845 albertel 10023: sub is_library {
1.852 albertel 10024: &load_hosts_tab() if (!$loaded);
10025:
1.845 albertel 10026: return exists($libserv{$_[0]});
10027: }
10028:
10029: sub all_library {
1.852 albertel 10030: &load_hosts_tab() if (!$loaded);
10031:
1.845 albertel 10032: return %libserv;
10033: }
10034:
1.1062 droeschl 10035: sub unique_library {
10036: #2x reverse removes all hostnames that appear more than once
10037: my %unique = reverse &all_library();
10038: return reverse %unique;
10039: }
10040:
1.841 albertel 10041: sub get_servers {
1.852 albertel 10042: &load_hosts_tab() if (!$loaded);
10043:
1.841 albertel 10044: my ($domain,$type) = @_;
10045: my %possible_hosts = ($type eq 'library') ? %libserv
10046: : %hostname;
10047: my %result;
1.842 albertel 10048: if (ref($domain) eq 'ARRAY') {
10049: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10050: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10051: $result{$host} = $hostname;
10052: }
10053: }
10054: } else {
10055: while ( my ($host,$hostname) = each(%possible_hosts)) {
10056: if ($hostdom{$host} eq $domain) {
10057: $result{$host} = $hostname;
10058: }
1.841 albertel 10059: }
10060: }
10061: return %result;
10062: }
1.845 albertel 10063:
1.1062 droeschl 10064: sub get_unique_servers {
10065: my %unique = reverse &get_servers(@_);
10066: return reverse %unique;
10067: }
10068:
1.844 albertel 10069: sub host_domain {
1.852 albertel 10070: &load_hosts_tab() if (!$loaded);
10071:
1.844 albertel 10072: my ($lonid) = @_;
10073: return $hostdom{$lonid};
10074: }
10075:
1.841 albertel 10076: sub all_domains {
1.852 albertel 10077: &load_hosts_tab() if (!$loaded);
10078:
1.841 albertel 10079: my %seen;
10080: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10081: return @uniq;
10082: }
1.1074 raeburn 10083:
10084: sub internet_dom {
10085: &load_hosts_tab() if (!$loaded);
10086:
10087: my ($lonid) = @_;
10088: return $internetdom{$lonid};
10089: }
1.1 albertel 10090: }
10091:
1.847 albertel 10092: {
10093: my %iphost;
1.856 albertel 10094: my %name_to_ip;
10095: my %lonid_to_ip;
1.869 albertel 10096:
1.847 albertel 10097: sub get_hosts_from_ip {
10098: my ($ip) = @_;
10099: my %iphosts = &get_iphost();
10100: if (ref($iphosts{$ip})) {
10101: return @{$iphosts{$ip}};
10102: }
10103: return;
1.839 albertel 10104: }
1.864 albertel 10105:
10106: sub reset_hosts_ip_info {
10107: undef(%iphost);
10108: undef(%name_to_ip);
10109: undef(%lonid_to_ip);
10110: }
1.856 albertel 10111:
10112: sub get_host_ip {
10113: my ($lonid) = @_;
10114: if (exists($lonid_to_ip{$lonid})) {
10115: return $lonid_to_ip{$lonid};
10116: }
10117: my $name=&hostname($lonid);
10118: my $ip = gethostbyname($name);
10119: return if (!$ip || length($ip) ne 4);
10120: $ip=inet_ntoa($ip);
10121: $name_to_ip{$name} = $ip;
10122: $lonid_to_ip{$lonid} = $ip;
10123: return $ip;
10124: }
1.847 albertel 10125:
10126: sub get_iphost {
1.869 albertel 10127: my ($ignore_cache) = @_;
1.894 albertel 10128:
1.869 albertel 10129: if (!$ignore_cache) {
10130: if (%iphost) {
10131: return %iphost;
10132: }
10133: my ($ip_info,$cached)=
10134: &Apache::lonnet::is_cached_new('iphost','iphost');
10135: if ($cached) {
10136: %iphost = %{$ip_info->[0]};
10137: %name_to_ip = %{$ip_info->[1]};
10138: %lonid_to_ip = %{$ip_info->[2]};
10139: return %iphost;
10140: }
10141: }
1.894 albertel 10142:
10143: # get yesterday's info for fallback
10144: my %old_name_to_ip;
10145: my ($ip_info,$cached)=
10146: &Apache::lonnet::is_cached_new('iphost','iphost');
10147: if ($cached) {
10148: %old_name_to_ip = %{$ip_info->[1]};
10149: }
10150:
1.888 albertel 10151: my %name_to_host = &all_names();
10152: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10153: my $ip;
10154: if (!exists($name_to_ip{$name})) {
10155: $ip = gethostbyname($name);
10156: if (!$ip || length($ip) ne 4) {
1.894 albertel 10157: if (defined($old_name_to_ip{$name})) {
10158: $ip = $old_name_to_ip{$name};
10159: &logthis("Can't find $name defaulting to old $ip");
10160: } else {
10161: &logthis("Name $name no IP found");
10162: next;
10163: }
10164: } else {
10165: $ip=inet_ntoa($ip);
1.847 albertel 10166: }
10167: $name_to_ip{$name} = $ip;
10168: } else {
10169: $ip = $name_to_ip{$name};
1.653 albertel 10170: }
1.888 albertel 10171: foreach my $id (@{ $name_to_host{$name} }) {
10172: $lonid_to_ip{$id} = $ip;
10173: }
10174: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10175: }
1.869 albertel 10176: &Apache::lonnet::do_cache_new('iphost','iphost',
10177: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10178: 48*60*60);
1.869 albertel 10179:
1.847 albertel 10180: return %iphost;
1.598 albertel 10181: }
10182:
1.992 raeburn 10183: #
10184: # Given a DNS returns the loncapa host name for that DNS
10185: #
10186: sub host_from_dns {
10187: my ($dns) = @_;
10188: my @hosts;
10189: my $ip;
10190:
1.993 raeburn 10191: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10192: $ip = $name_to_ip{$dns};
10193: }
10194: if (!$ip) {
10195: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10196: if (length($ip) == 4) {
10197: $ip = &IO::Socket::inet_ntoa($ip);
10198: }
10199: }
10200: if ($ip) {
10201: @hosts = get_hosts_from_ip($ip);
10202: return $hosts[0];
10203: }
10204: return undef;
1.986 foxr 10205: }
1.992 raeburn 10206:
1.1074 raeburn 10207: sub get_internet_names {
10208: my ($lonid) = @_;
10209: return if ($lonid eq '');
10210: my ($idnref,$cached)=
10211: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10212: if ($cached) {
10213: return $idnref;
10214: }
10215: my $ip = &get_host_ip($lonid);
10216: my @hosts = &get_hosts_from_ip($ip);
10217: my %iphost = &get_iphost();
10218: my (@idns,%seen);
10219: foreach my $id (@hosts) {
10220: my $dom = &host_domain($id);
10221: my $prim_id = &domain($dom,'primary');
10222: my $prim_ip = &get_host_ip($prim_id);
10223: next if ($seen{$prim_ip});
10224: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10225: foreach my $id (@{$iphost{$prim_ip}}) {
10226: my $intdom = &internet_dom($id);
10227: unless (grep(/^\Q$intdom\E$/,@idns)) {
10228: push(@idns,$intdom);
10229: }
10230: }
10231: }
10232: $seen{$prim_ip} = 1;
10233: }
10234: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10235: }
10236:
1.986 foxr 10237: }
10238:
1.1079 raeburn 10239: sub all_loncaparevs {
10240: 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);
10241: }
10242:
1.862 albertel 10243: BEGIN {
10244:
10245: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10246: unless ($readit) {
10247: {
10248: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10249: %perlvar = (%perlvar,%{$configvars});
10250: }
10251:
10252:
1.1 albertel 10253: # ------------------------------------------------------ Read spare server file
10254: {
1.448 albertel 10255: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10256:
10257: while (my $configline=<$config>) {
10258: chomp($configline);
1.284 matthew 10259: if ($configline) {
1.784 albertel 10260: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10261: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10262: push(@{ $spareid{$type} }, $host);
1.1 albertel 10263: }
10264: }
1.448 albertel 10265: close($config);
1.1 albertel 10266: }
1.11 www 10267: # ------------------------------------------------------------ Read permissions
10268: {
1.448 albertel 10269: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10270:
10271: while (my $configline=<$config>) {
1.448 albertel 10272: chomp($configline);
10273: if ($configline) {
10274: my ($role,$perm)=split(/ /,$configline);
10275: if ($perm ne '') { $pr{$role}=$perm; }
10276: }
1.11 www 10277: }
1.448 albertel 10278: close($config);
1.11 www 10279: }
10280:
10281: # -------------------------------------------- Read plain texts for permissions
10282: {
1.448 albertel 10283: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10284:
10285: while (my $configline=<$config>) {
1.448 albertel 10286: chomp($configline);
10287: if ($configline) {
1.742 raeburn 10288: my ($short,@plain)=split(/:/,$configline);
10289: %{$prp{$short}} = ();
10290: if (@plain > 0) {
10291: $prp{$short}{'std'} = $plain[0];
10292: for (my $i=1; $i<@plain; $i++) {
10293: $prp{$short}{'alt'.$i} = $plain[$i];
10294: }
10295: }
1.448 albertel 10296: }
1.135 www 10297: }
1.448 albertel 10298: close($config);
1.135 www 10299: }
10300:
10301: # ---------------------------------------------------------- Read package table
10302: {
1.448 albertel 10303: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10304:
10305: while (my $configline=<$config>) {
1.483 albertel 10306: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10307: chomp($configline);
10308: my ($short,$plain)=split(/:/,$configline);
10309: my ($pack,$name)=split(/\&/,$short);
10310: if ($plain ne '') {
10311: $packagetab{$pack.'&'.$name.'&name'}=$name;
10312: $packagetab{$short}=$plain;
10313: }
1.11 www 10314: }
1.448 albertel 10315: close($config);
1.329 matthew 10316: }
10317:
1.1073 raeburn 10318: # ---------------------------------------------------------- Read loncaparev table
10319: {
10320: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10321: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10322: while (my $configline=<$config>) {
10323: chomp($configline);
10324: my ($hostid,$loncaparev)=split(/:/,$configline);
10325: $loncaparevs{$hostid}=$loncaparev;
10326: }
10327: close($config);
10328: }
10329: }
10330: }
10331:
1.1074 raeburn 10332: # ---------------------------------------------------------- Read serverhostID table
10333: {
10334: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10335: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10336: while (my $configline=<$config>) {
10337: chomp($configline);
10338: my ($name,$id)=split(/:/,$configline);
10339: $serverhomeIDs{$name}=$id;
10340: }
10341: close($config);
10342: }
10343: }
10344: }
10345:
1.1079 raeburn 10346: {
10347: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10348: if (-e $file) {
10349: my $parser = HTML::LCParser->new($file);
10350: while (my $token = $parser->get_token()) {
10351: if ($token->[0] eq 'S') {
10352: my $item = $token->[1];
10353: my $name = $token->[2]{'name'};
10354: my $value = $token->[2]{'value'};
10355: if ($item ne '' && $name ne '' && $value ne '') {
10356: my $release = $parser->get_text();
10357: $release =~ s/(^\s*|\s*$ )//gx;
10358: $needsrelease{$item.':'.$name.':'.$value} = $release;
10359: }
10360: }
10361: }
10362: }
1.1073 raeburn 10363: }
10364:
1.329 matthew 10365: # ------------- set up temporary directory
10366: {
10367: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10368:
1.11 www 10369: }
10370:
1.794 albertel 10371: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10372: 'compress_threshold'=> 20_000,
10373: });
1.185 www 10374:
1.281 www 10375: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10376: $dumpcount=0;
1.958 www 10377: $locknum=0;
1.22 www 10378:
1.163 harris41 10379: &logtouch();
1.672 albertel 10380: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10381: $readit=1;
1.564 albertel 10382: {
10383: use integer;
10384: my $test=(2**32)+1;
1.568 albertel 10385: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10386: &logthis(" Detected 64bit platform ($_64bit)");
10387: }
1.195 www 10388: }
1.1 albertel 10389: }
1.179 www 10390:
1.1 albertel 10391: 1;
1.191 harris41 10392: __END__
10393:
1.243 albertel 10394: =pod
10395:
1.191 harris41 10396: =head1 NAME
10397:
1.243 albertel 10398: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10399:
10400: =head1 SYNOPSIS
10401:
1.243 albertel 10402: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10403:
10404: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10405:
1.243 albertel 10406: Common parameters:
10407:
10408: =over 4
10409:
10410: =item *
10411:
10412: $uname : an internal username (if $cname expecting a course Id specifically)
10413:
10414: =item *
10415:
10416: $udom : a domain (if $cdom expecting a course's domain specifically)
10417:
10418: =item *
10419:
10420: $symb : a resource instance identifier
10421:
10422: =item *
10423:
10424: $namespace : the name of a .db file that contains the data needed or
10425: being set.
10426:
10427: =back
10428:
1.394 bowersj2 10429: =head1 OVERVIEW
1.191 harris41 10430:
1.394 bowersj2 10431: lonnet provides subroutines which interact with the
10432: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10433: about classes, users, and resources.
1.243 albertel 10434:
10435: For many of these objects you can also use this to store data about
10436: them or modify them in various ways.
1.191 harris41 10437:
1.394 bowersj2 10438: =head2 Symbs
1.191 harris41 10439:
1.394 bowersj2 10440: To identify a specific instance of a resource, LON-CAPA uses symbols
10441: or "symbs"X<symb>. These identifiers are built from the URL of the
10442: map, the resource number of the resource in the map, and the URL of
10443: the resource itself. The latter is somewhat redundant, but might help
10444: if maps change.
10445:
10446: An example is
10447:
10448: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10449:
10450: The respective map entry is
10451:
10452: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10453: title="Problem 2">
10454: </resource>
10455:
10456: Symbs are used by the random number generator, as well as to store and
10457: restore data specific to a certain instance of for example a problem.
10458:
10459: =head2 Storing And Retrieving Data
10460:
10461: X<store()>X<cstore()>X<restore()>Three of the most important functions
10462: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10463: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10464: is is the non-critical message twin of cstore. These functions are for
10465: handlers to store a perl hash to a user's permanent data space in an
10466: easy manner, and to retrieve it again on another call. It is expected
10467: that a handler would use this once at the beginning to retrieve data,
10468: and then again once at the end to send only the new data back.
10469:
10470: The data is stored in the user's data directory on the user's
10471: homeserver under the ID of the course.
10472:
10473: The hash that is returned by restore will have all of the previous
10474: value for all of the elements of the hash.
10475:
10476: Example:
10477:
10478: #creating a hash
10479: my %hash;
10480: $hash{'foo'}='bar';
10481:
10482: #storing it
10483: &Apache::lonnet::cstore(\%hash);
10484:
10485: #changing a value
10486: $hash{'foo'}='notbar';
10487:
10488: #adding a new value
10489: $hash{'bar'}='foo';
10490: &Apache::lonnet::cstore(\%hash);
10491:
10492: #retrieving the hash
10493: my %history=&Apache::lonnet::restore();
10494:
10495: #print the hash
10496: foreach my $key (sort(keys(%history))) {
10497: print("\%history{$key} = $history{$key}");
10498: }
10499:
10500: Will print out:
1.191 harris41 10501:
1.394 bowersj2 10502: %history{1:foo} = bar
10503: %history{1:keys} = foo:timestamp
10504: %history{1:timestamp} = 990455579
10505: %history{2:bar} = foo
10506: %history{2:foo} = notbar
10507: %history{2:keys} = foo:bar:timestamp
10508: %history{2:timestamp} = 990455580
10509: %history{bar} = foo
10510: %history{foo} = notbar
10511: %history{timestamp} = 990455580
10512: %history{version} = 2
10513:
10514: Note that the special hash entries C<keys>, C<version> and
10515: C<timestamp> were added to the hash. C<version> will be equal to the
10516: total number of versions of the data that have been stored. The
10517: C<timestamp> attribute will be the UNIX time the hash was
10518: stored. C<keys> is available in every historical section to list which
10519: keys were added or changed at a specific historical revision of a
10520: hash.
10521:
10522: B<Warning>: do not store the hash that restore returns directly. This
10523: will cause a mess since it will restore the historical keys as if the
10524: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10525:
1.394 bowersj2 10526: Calling convention:
1.191 harris41 10527:
1.394 bowersj2 10528: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10529: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10530:
1.394 bowersj2 10531: For more detailed information, see lonnet specific documentation.
1.191 harris41 10532:
1.394 bowersj2 10533: =head1 RETURN MESSAGES
1.191 harris41 10534:
1.394 bowersj2 10535: =over 4
1.191 harris41 10536:
1.394 bowersj2 10537: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10538:
1.394 bowersj2 10539: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10540: when the connection is brought back up
1.191 harris41 10541:
1.394 bowersj2 10542: =item * B<con_failed>: unable to contact remote host and unable to save message
10543: for later delivery
1.191 harris41 10544:
1.967 bisitz 10545: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10546:
1.394 bowersj2 10547: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10548: that was requested
1.191 harris41 10549:
1.243 albertel 10550: =back
1.191 harris41 10551:
1.243 albertel 10552: =head1 PUBLIC SUBROUTINES
1.191 harris41 10553:
1.243 albertel 10554: =head2 Session Environment Functions
1.191 harris41 10555:
1.243 albertel 10556: =over 4
1.191 harris41 10557:
1.394 bowersj2 10558: =item *
10559: X<appenv()>
1.949 raeburn 10560: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10561: the user envirnoment file, and will be restored for each access this
1.620 albertel 10562: user makes during this session, also modifies the %env for the current
1.949 raeburn 10563: process. Optional rolesarrayref - if defined contains a reference to an array
10564: of roles which are exempt from the restriction on modifying user.role entries
10565: in the user's environment.db and in %env.
1.191 harris41 10566:
10567: =item *
1.394 bowersj2 10568: X<delenv()>
1.987 raeburn 10569: B<delenv($delthis,$regexp)>: removes all items from the session
10570: environment file that begin with $delthis. If the
10571: optional second arg - $regexp - is true, $delthis is treated as a
10572: regular expression, otherwise \Q$delthis\E is used.
10573: The values are also deleted from the current processes %env.
1.191 harris41 10574:
1.795 albertel 10575: =item * get_env_multiple($name)
10576:
10577: gets $name from the %env hash, it seemlessly handles the cases where multiple
10578: values may be defined and end up as an array ref.
10579:
10580: returns an array of values
10581:
1.243 albertel 10582: =back
10583:
10584: =head2 User Information
1.191 harris41 10585:
1.243 albertel 10586: =over 4
1.191 harris41 10587:
10588: =item *
1.394 bowersj2 10589: X<queryauthenticate()>
10590: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10591: authentication scheme
10592:
10593: =item *
1.394 bowersj2 10594: X<authenticate()>
1.1073 raeburn 10595: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10596: authenticate user from domain's lib servers (first use the current
10597: one). C<$upass> should be the users password.
1.1073 raeburn 10598: $checkdefauth is optional (value is 1 if a check should be made to
10599: authenticate user using default authentication method, and allow
10600: account creation if username does not have account in the domain).
10601: $clientcancheckhost is optional (value is 1 if checking whether the
10602: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10603:
10604: =item *
1.394 bowersj2 10605: X<homeserver()>
10606: B<homeserver($uname,$udom)>: find the server which has
10607: the user's directory and files (there must be only one), this caches
10608: the answer, and also caches if there is a borken connection.
1.191 harris41 10609:
10610: =item *
1.394 bowersj2 10611: X<idget()>
10612: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10613: (IDs are a unique resource in a domain, there must be only 1 ID per
10614: username, and only 1 username per ID in a specific domain) (returns
10615: hash: id=>name,id=>name)
1.191 harris41 10616:
10617: =item *
1.394 bowersj2 10618: X<idrget()>
10619: B<idrget($udom,@unames)>: find the IDs behind a list of
10620: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10621:
10622: =item *
1.394 bowersj2 10623: X<idput()>
10624: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10625:
10626: =item *
1.394 bowersj2 10627: X<rolesinit()>
10628: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10629:
10630: =item *
1.551 albertel 10631: X<getsection()>
10632: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10633: course $cname, return section name/number or '' for "not in course"
10634: and '-1' for "no section"
10635:
10636: =item *
1.394 bowersj2 10637: X<userenvironment()>
10638: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10639: passed in @what from the requested user's environment, returns a hash
10640:
1.858 raeburn 10641: =item *
10642: X<userlog_query()>
1.859 albertel 10643: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10644: activity.log file. %filters defines filters applied when parsing the
10645: log file. These can be start or end timestamps, or the type of action
10646: - log to look for Login or Logout events, check for Checkin or
10647: Checkout, role for role selection. The response is in the form
10648: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10649: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10650:
1.243 albertel 10651: =back
10652:
10653: =head2 User Roles
10654:
10655: =over 4
10656:
10657: =item *
10658:
1.810 raeburn 10659: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10660: F: full access
10661: U,I,K: authentication modes (cxx only)
10662: '': forbidden
10663: 1: user needs to choose course
10664: 2: browse allowed
1.766 albertel 10665: A: passphrase authentication needed
1.243 albertel 10666:
10667: =item *
10668:
10669: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10670: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10671: and course level
10672:
10673: =item *
10674:
1.988 raeburn 10675: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10676: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10677: $type is Course (default) or Community.
1.988 raeburn 10678: If $forcedefault evaluates to true, text returned will be default
10679: text for $type. Otherwise, if this is a course, the text returned
10680: will be a custom name for the role (if defined in the course's
10681: environment). If no custom name is defined the default is returned.
10682:
1.832 raeburn 10683: =item *
10684:
1.935 raeburn 10685: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10686: All arguments are optional. Returns a hash of a roles, either for
10687: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10688: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10689: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10690: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10691: For each key, value is set to colon-separated start and end times for
10692: the role. If no username and domain are specified, will default to
1.934 raeburn 10693: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10694: of role statuses (active, future or previous), roles
10695: (e.g., cc,in, st etc.) and domains of the roles which can be used
10696: to restrict the list of roles reported. If no array ref is
10697: provided for types, will default to return only active roles.
1.834 albertel 10698:
1.243 albertel 10699: =back
10700:
10701: =head2 User Modification
10702:
10703: =over 4
10704:
10705: =item *
10706:
1.957 raeburn 10707: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10708: user for the level given by URL. Optional start and end dates (leave empty
10709: string or zero for "no date")
1.191 harris41 10710:
10711: =item *
10712:
1.243 albertel 10713: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10714: change a users, password, possible return values are: ok,
10715: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10716: refused
1.191 harris41 10717:
10718: =item *
10719:
1.243 albertel 10720: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10721:
10722: =item *
10723:
1.1058 raeburn 10724: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10725: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10726:
10727: will update user information (firstname,middlename,lastname,generation,
10728: permanentemail), and if forceid is true, student/employee ID also.
10729: A user's institutional affiliation(s) can also be updated.
10730: User information fields will not be overwritten with empty entries
10731: unless the field is included in the $candelete array reference.
10732: This array is included when a single user is modified via "Manage Users",
10733: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10734:
10735: =item *
10736:
1.286 matthew 10737: modifystudent
10738:
1.957 raeburn 10739: modify a student's enrollment and identification information.
1.286 matthew 10740: The course id is resolved based on the current users environment.
10741: This means the envoking user must be a course coordinator or otherwise
10742: associated with a course.
10743:
1.297 matthew 10744: This call is essentially a wrapper for lonnet::modifyuser and
10745: lonnet::modify_student_enrollment
1.286 matthew 10746:
10747: Inputs:
10748:
10749: =over 4
10750:
1.957 raeburn 10751: =item B<$udom> Student's loncapa domain
1.286 matthew 10752:
1.957 raeburn 10753: =item B<$uname> Student's loncapa login name
1.286 matthew 10754:
1.964 bisitz 10755: =item B<$uid> Student/Employee ID
1.286 matthew 10756:
1.957 raeburn 10757: =item B<$umode> Student's authentication mode
1.286 matthew 10758:
1.957 raeburn 10759: =item B<$upass> Student's password
1.286 matthew 10760:
1.957 raeburn 10761: =item B<$first> Student's first name
1.286 matthew 10762:
1.957 raeburn 10763: =item B<$middle> Student's middle name
1.286 matthew 10764:
1.957 raeburn 10765: =item B<$last> Student's last name
1.286 matthew 10766:
1.957 raeburn 10767: =item B<$gene> Student's generation
1.286 matthew 10768:
1.957 raeburn 10769: =item B<$usec> Student's section in course
1.286 matthew 10770:
10771: =item B<$end> Unix time of the roles expiration
10772:
10773: =item B<$start> Unix time of the roles start date
10774:
10775: =item B<$forceid> If defined, allow $uid to be changed
10776:
10777: =item B<$desiredhome> server to use as home server for student
10778:
1.957 raeburn 10779: =item B<$email> Student's permanent e-mail address
10780:
10781: =item B<$type> Type of enrollment (auto or manual)
10782:
1.963 raeburn 10783: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10784:
10785: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10786:
1.963 raeburn 10787: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10788:
1.963 raeburn 10789: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10790:
1.963 raeburn 10791: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10792:
1.286 matthew 10793: =back
1.297 matthew 10794:
10795: =item *
10796:
10797: modify_student_enrollment
10798:
10799: Change a students enrollment status in a class. The environment variable
10800: 'role.request.course' must be defined for this function to proceed.
10801:
10802: Inputs:
10803:
10804: =over 4
10805:
10806: =item $udom, students domain
10807:
10808: =item $uname, students name
10809:
10810: =item $uid, students user id
10811:
10812: =item $first, students first name
10813:
10814: =item $middle
10815:
10816: =item $last
10817:
10818: =item $gene
10819:
10820: =item $usec
10821:
10822: =item $end
10823:
10824: =item $start
10825:
1.957 raeburn 10826: =item $type
10827:
10828: =item $locktype
10829:
10830: =item $cid
10831:
10832: =item $selfenroll
10833:
10834: =item $context
10835:
1.297 matthew 10836: =back
10837:
1.191 harris41 10838:
10839: =item *
10840:
1.243 albertel 10841: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10842: custom role; give a custom role to a user for the level given by URL. Specify
10843: name and domain of role author, and role name
1.191 harris41 10844:
10845: =item *
10846:
1.243 albertel 10847: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10848:
10849: =item *
10850:
1.243 albertel 10851: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10852:
10853: =back
10854:
10855: =head2 Course Infomation
10856:
10857: =over 4
1.191 harris41 10858:
10859: =item *
10860:
1.631 albertel 10861: coursedescription($courseid) : returns a hash of information about the
10862: specified course id, including all environment settings for the
10863: course, the description of the course will be in the hash under the
10864: key 'description'
1.191 harris41 10865:
10866: =item *
10867:
1.624 albertel 10868: resdata($name,$domain,$type,@which) : request for current parameter
10869: setting for a specific $type, where $type is either 'course' or 'user',
10870: @what should be a list of parameters to ask about. This routine caches
10871: answers for 5 minutes.
1.243 albertel 10872:
1.877 foxr 10873: =item *
10874:
10875: get_courseresdata($courseid, $domain) : dump the entire course resource
10876: data base, returning a hash that is keyed by the resource name and has
10877: values that are the resource value. I believe that the timestamps and
10878: versions are also returned.
10879:
10880:
1.243 albertel 10881: =back
10882:
10883: =head2 Course Modification
10884:
10885: =over 4
1.191 harris41 10886:
10887: =item *
10888:
1.243 albertel 10889: writecoursepref($courseid,%prefs) : write preferences (environment
10890: database) for a course
1.191 harris41 10891:
10892: =item *
10893:
1.1011 raeburn 10894: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10895:
10896: =item *
10897:
1.1038 raeburn 10898: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10899:
10900: =back
10901:
10902: =head2 Resource Subroutines
10903:
10904: =over 4
1.191 harris41 10905:
10906: =item *
10907:
1.243 albertel 10908: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10909:
10910: =item *
10911:
1.243 albertel 10912: repcopy($filename) : subscribes to the requested file, and attempts to
10913: replicate from the owning library server, Might return
1.607 raeburn 10914: 'unavailable', 'not_found', 'forbidden', 'ok', or
10915: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10916: resource. Expects the local filesystem pathname
10917: (/home/httpd/html/res/....)
10918:
10919: =back
10920:
10921: =head2 Resource Information
10922:
10923: =over 4
1.191 harris41 10924:
10925: =item *
10926:
1.243 albertel 10927: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10928: a vairety of different possible values, $varname should be a request
10929: string, and the other parameters can be used to specify who and what
10930: one is asking about.
10931:
10932: Possible values for $varname are environment.lastname (or other item
10933: from the envirnment hash), user.name (or someother aspect about the
10934: user), resource.0.maxtries (or some other part and parameter of a
10935: resource)
1.204 albertel 10936:
10937: =item *
10938:
1.243 albertel 10939: directcondval($number) : get current value of a condition; reads from a state
10940: string
1.204 albertel 10941:
10942: =item *
10943:
1.243 albertel 10944: condval($condidx) : value of condition index based on state
1.204 albertel 10945:
10946: =item *
10947:
1.243 albertel 10948: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10949: resource's metadata, $what should be either a specific key, or either
10950: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10951: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10952:
10953: this function automatically caches all requests
1.191 harris41 10954:
10955: =item *
10956:
1.243 albertel 10957: metadata_query($query,$custom,$customshow) : make a metadata query against the
10958: network of library servers; returns file handle of where SQL and regex results
10959: will be stored for query
1.191 harris41 10960:
10961: =item *
10962:
1.243 albertel 10963: symbread($filename) : return symbolic list entry (filename argument optional);
10964: returns the data handle
1.191 harris41 10965:
10966: =item *
10967:
1.243 albertel 10968: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10969: a possible symb for the URL in $thisfn, and if is an encryypted
10970: resource that the user accessed using /enc/ returns a 1 on success, 0
10971: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10972: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10973:
1.191 harris41 10974:
10975: =item *
10976:
1.243 albertel 10977: symbclean($symb) : removes versions numbers from a symb, returns the
10978: cleaned symb
1.191 harris41 10979:
10980: =item *
10981:
1.243 albertel 10982: is_on_map($uri) : checks if the $uri is somewhere on the current
10983: course map, user must be in a course for it to work.
1.191 harris41 10984:
10985: =item *
10986:
1.243 albertel 10987: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10988:
10989: =item *
10990:
1.243 albertel 10991: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10992: a random seed, all arguments are optional, if they aren't sent it uses the
10993: environment to derive them. Note: if symb isn't sent and it can't get one
10994: from &symbread it will use the current time as its return value
1.191 harris41 10995:
10996: =item *
10997:
1.243 albertel 10998: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10999: unfakeable, receipt
1.191 harris41 11000:
11001: =item *
11002:
1.620 albertel 11003: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11004:
11005: =item *
11006:
1.243 albertel 11007: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11008:
11009: =item *
11010:
1.243 albertel 11011: 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 11012:
11013: =item *
11014:
1.243 albertel 11015: 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 11016:
11017: =item *
11018:
1.243 albertel 11019: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11020:
11021: =item *
11022:
1.243 albertel 11023: devalidate($symb) : devalidate temporary spreadsheet calculations,
11024: forcing spreadsheet to reevaluate the resource scores next time.
11025:
11026: =back
11027:
11028: =head2 Storing/Retreiving Data
11029:
11030: =over 4
1.191 harris41 11031:
11032: =item *
11033:
1.243 albertel 11034: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11035: for this url; hashref needs to be given and should be a \%hashname; the
11036: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11037: be derived from the env
1.191 harris41 11038:
11039: =item *
11040:
1.243 albertel 11041: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11042: uses critical subroutine
1.191 harris41 11043:
11044: =item *
11045:
1.243 albertel 11046: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11047: all args are optional
1.191 harris41 11048:
11049: =item *
11050:
1.717 albertel 11051: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11052: dumps the complete (or key matching regexp) namespace into a hash
11053: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11054: normally &store()ed into
11055:
11056: $range should be either an integer '100' (give me the first 100
11057: matching records)
11058: or be two integers sperated by a - with no spaces
11059: '30-50' (give me the 30th through the 50th matching
11060: records)
11061:
11062:
11063: =item *
11064:
11065: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11066: replaces a &store() version of data with a replacement set of data
11067: for a particular resource in a namespace passed in the $storehash hash
11068: reference
11069:
11070: =item *
11071:
1.243 albertel 11072: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11073: works very similar to store/cstore, but all data is stored in a
11074: temporary location and can be reset using tmpreset, $storehash should
11075: be a hash reference, returns nothing on success
1.191 harris41 11076:
11077: =item *
11078:
1.243 albertel 11079: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11080: similar to restore, but all data is stored in a temporary location and
11081: can be reset using tmpreset. Returns a hash of values on success,
11082: error string otherwise.
1.191 harris41 11083:
11084: =item *
11085:
1.243 albertel 11086: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11087: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11088:
11089: =item *
11090:
1.243 albertel 11091: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11092: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11093:
11094: =item *
11095:
1.243 albertel 11096: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11097: namesp ($udom and $uname are optional)
1.191 harris41 11098:
11099: =item *
11100:
1.702 albertel 11101: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11102: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11103: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11104:
1.702 albertel 11105: $range should be either an integer '100' (give me the first 100
11106: matching records)
11107: or be two integers sperated by a - with no spaces
11108: '30-50' (give me the 30th through the 50th matching
11109: records)
1.449 matthew 11110: =item *
11111:
11112: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11113: $store can be a scalar, an array reference, or if the amount to be
11114: incremented is > 1, a hash reference.
11115:
11116: ($udom and $uname are optional)
1.191 harris41 11117:
11118: =item *
11119:
1.243 albertel 11120: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11121: ($udom and $uname are optional)
1.191 harris41 11122:
11123: =item *
11124:
1.243 albertel 11125: cput($namespace,$storehash,$udom,$uname) : critical put
11126: ($udom and $uname are optional)
1.191 harris41 11127:
11128: =item *
11129:
1.748 albertel 11130: newput($namespace,$storehash,$udom,$uname) :
11131:
11132: Attempts to store the items in the $storehash, but only if they don't
11133: currently exist, if this succeeds you can be certain that you have
11134: successfully created a new key value pair in the $namespace db.
11135:
11136:
11137: Args:
11138: $namespace: name of database to store values to
11139: $storehash: hashref to store to the db
11140: $udom: (optional) domain of user containing the db
11141: $uname: (optional) name of user caontaining the db
11142:
11143: Returns:
11144: 'ok' -> succeeded in storing all keys of $storehash
11145: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11146: least <key> already existed in the db (other
11147: requested keys may also already exist)
1.967 bisitz 11148: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11149: 'con_lost' -> unable to contact request server
11150: 'refused' -> action was not allowed by remote machine
11151:
11152:
11153: =item *
11154:
1.243 albertel 11155: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11156: reference filled in from namesp (encrypts the return communication)
11157: ($udom and $uname are optional)
1.191 harris41 11158:
11159: =item *
11160:
1.243 albertel 11161: log($udom,$name,$home,$message) : write to permanent log for user; use
11162: critical subroutine
11163:
1.806 raeburn 11164: =item *
11165:
1.860 raeburn 11166: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11167: array reference filled in from namespace found in domain level on either
11168: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11169:
11170: =item *
11171:
1.860 raeburn 11172: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11173: domain level either on specified domain server ($uhome) or primary domain
11174: server ($udom and $uhome are optional)
1.806 raeburn 11175:
1.943 raeburn 11176: =item *
11177:
11178: get_domain_defaults($target_domain) : returns hash with defaults for
11179: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11180: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11181: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11182: Values are retrieved from cache (if current), or from domain's configuration.db
11183: (if available), or lastly from values in lonTabs/dns_domain,tab,
11184: or lonTabs/domain.tab.
11185:
11186: %domdefaults = &get_auth_defaults($target_domain);
11187:
1.243 albertel 11188: =back
11189:
11190: =head2 Network Status Functions
11191:
11192: =over 4
1.191 harris41 11193:
11194: =item *
11195:
11196: dirlist($uri) : return directory list based on URI
11197:
11198: =item *
11199:
1.243 albertel 11200: spareserver() : find server with least workload from spare.tab
11201:
1.986 foxr 11202:
11203: =item *
11204:
11205: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11206: if there is no corresponding loncapa host.
11207:
1.243 albertel 11208: =back
11209:
1.986 foxr 11210:
1.243 albertel 11211: =head2 Apache Request
11212:
11213: =over 4
1.191 harris41 11214:
11215: =item *
11216:
1.243 albertel 11217: ssi($url,%hash) : server side include, does a complete request cycle on url to
11218: localhost, posts hash
11219:
11220: =back
11221:
11222: =head2 Data to String to Data
11223:
11224: =over 4
1.191 harris41 11225:
11226: =item *
11227:
1.243 albertel 11228: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11229: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11230:
11231: =item *
11232:
1.243 albertel 11233: hashref2str($hashref) : convert a hashref into a string complete with
11234: escaping and '=' and '&' separators, supports elements that are
11235: arrayrefs and hashrefs
1.191 harris41 11236:
11237: =item *
11238:
1.243 albertel 11239: arrayref2str($arrayref) : convert an arrayref into a string complete
11240: with escaping and '&' separators, supports elements that are arrayrefs
11241: and hashrefs
1.191 harris41 11242:
11243: =item *
11244:
1.243 albertel 11245: str2hash($string) : convert string to hash using unescaping and
11246: splitting on '=' and '&', supports elements that are arrayrefs and
11247: hashrefs
1.191 harris41 11248:
11249: =item *
11250:
1.243 albertel 11251: str2array($string) : convert string to hash using unescaping and
11252: splitting on '&', supports elements that are arrayrefs and hashrefs
11253:
11254: =back
11255:
11256: =head2 Logging Routines
11257:
11258: =over 4
11259:
11260: These routines allow one to make log messages in the lonnet.log and
11261: lonnet.perm logfiles.
1.191 harris41 11262:
11263: =item *
11264:
1.243 albertel 11265: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11266:
11267: =item *
11268:
1.243 albertel 11269: logthis() : append message to the normal lonnet.log file, it gets
11270: preiodically rolled over and deleted.
1.191 harris41 11271:
11272: =item *
11273:
1.243 albertel 11274: logperm() : append a permanent message to lonnet.perm.log, this log
11275: file never gets deleted by any automated portion of the system, only
11276: messages of critical importance should go in here.
11277:
11278: =back
11279:
11280: =head2 General File Helper Routines
11281:
11282: =over 4
1.191 harris41 11283:
11284: =item *
11285:
1.481 raeburn 11286: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11287: (a) files in /uploaded
11288: (i) If a local copy of the file exists -
11289: compares modification date of local copy with last-modified date for
11290: definitive version stored on home server for course. If local copy is
11291: stale, requests a new version from the home server and stores it.
11292: If the original has been removed from the home server, then local copy
11293: is unlinked.
11294: (ii) If local copy does not exist -
11295: requests the file from the home server and stores it.
11296:
11297: If $caller is 'uploadrep':
11298: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11299: for request for files originally uploaded via DOCS.
11300: - returns 'ok' if fresh local copy now available, -1 otherwise.
11301:
11302: Otherwise:
11303: This indicates a call from the content generation phase of the request.
11304: - returns the entire contents of the file or -1.
11305:
11306: (b) files in /res
11307: - returns the entire contents of a file or -1;
11308: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11309:
1.712 albertel 11310:
11311: =item *
11312:
11313: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11314: reference
11315:
11316: returns either a stat() list of data about the file or an empty list
11317: if the file doesn't exist or couldn't find out about it (connection
11318: problems or user unknown)
11319:
1.191 harris41 11320: =item *
11321:
1.243 albertel 11322: filelocation($dir,$file) : returns file system location of a file
11323: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11324: directory that relative $file lookups are to looked in ($dir of /a/dir
11325: and a file of ../bob will become /a/bob)
1.191 harris41 11326:
11327: =item *
11328:
11329: hreflocation($dir,$file) : returns file system location or a URL; same as
11330: filelocation except for hrefs
11331:
11332: =item *
11333:
11334: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11335:
1.243 albertel 11336: =back
11337:
1.608 albertel 11338: =head2 Usererfile file routines (/uploaded*)
11339:
11340: =over 4
11341:
11342: =item *
11343:
11344: userfileupload(): main rotine for putting a file in a user or course's
11345: filespace, arguments are,
11346:
1.620 albertel 11347: formname - required - this is the name of the element in $env where the
1.608 albertel 11348: filename, and the contents of the file to create/modifed exist
1.620 albertel 11349: the filename is in $env{'form.'.$formname.'.filename'} and the
11350: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11351: coursedoc - if true, store the file in the course of the active role
11352: of the current user
11353: subdir - required - subdirectory to put the file in under ../userfiles/
11354: if undefined, it will be placed in "unknown"
11355:
11356: (This routine calls clean_filename() to remove any dangerous
11357: characters from the filename, and then calls finuserfileupload() to
11358: complete the transaction)
11359:
11360: returns either the url of the uploaded file (/uploaded/....) if successful
11361: and /adm/notfound.html if unsuccessful
11362:
11363: =item *
11364:
11365: clean_filename(): routine for cleaing a filename up for storage in
11366: userfile space, argument is:
11367:
11368: filename - proposed filename
11369:
11370: returns: the new clean filename
11371:
11372: =item *
11373:
11374: finishuserfileupload(): routine that creaes and sends the file to
11375: userspace, probably shouldn't be called directly
11376:
11377: docuname: username or courseid of destination for the file
11378: docudom: domain of user/course of destination for the file
11379: formname: same as for userfileupload()
11380: fname: filename (inculding subdirectories) for the file
11381:
11382: returns either the url of the uploaded file (/uploaded/....) if successful
11383: and /adm/notfound.html if unsuccessful
11384:
11385: =item *
11386:
11387: renameuserfile(): renames an existing userfile to a new name
11388:
11389: Args:
11390: docuname: username or courseid of destination for the file
11391: docudom: domain of user/course of destination for the file
11392: old: current file name (including any subdirs under userfiles)
11393: new: desired file name (including any subdirs under userfiles)
11394:
11395: =item *
11396:
11397: mkdiruserfile(): creates a directory is a userfiles dir
11398:
11399: Args:
11400: docuname: username or courseid of destination for the file
11401: docudom: domain of user/course of destination for the file
11402: dir: dir to create (including any subdirs under userfiles)
11403:
11404: =item *
11405:
11406: removeuserfile(): removes a file that exists in userfiles
11407:
11408: Args:
11409: docuname: username or courseid of destination for the file
11410: docudom: domain of user/course of destination for the file
11411: fname: filname to delete (including any subdirs under userfiles)
11412:
11413: =item *
11414:
11415: removeuploadedurl(): convience function for removeuserfile()
11416:
11417: Args:
11418: url: a full /uploaded/... url to delete
11419:
1.747 albertel 11420: =item *
11421:
11422: get_portfile_permissions():
11423: Args:
11424: domain: domain of user or course contain the portfolio files
11425: user: name of user or num of course contain the portfolio files
11426: Returns:
11427: hashref of a dump of the proper file_permissions.db
11428:
11429:
11430: =item *
11431:
11432: get_access_controls():
11433:
11434: Args:
11435: current_permissions: the hash ref returned from get_portfile_permissions()
11436: group: (optional) the group you want the files associated with
11437: file: (optional) the file you want access info on
11438:
11439: Returns:
1.749 raeburn 11440: a hash (keys are file names) of hashes containing
11441: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11442: values are XML containing access control settings (see below)
1.747 albertel 11443:
11444: Internal notes:
11445:
1.749 raeburn 11446: access controls are stored in file_permissions.db as key=value pairs.
11447: key -> path to file/file_name\0uniqueID:scope_end_start
11448: where scope -> public,guest,course,group,domains or users.
11449: end -> UNIX time for end of access (0 -> no end date)
11450: start -> UNIX time for start of access
11451:
11452: value -> XML description of access control
11453: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11454: <start></start>
11455: <end></end>
11456:
11457: <password></password> for scope type = guest
11458:
11459: <domain></domain> for scope type = course or group
11460: <number></number>
11461: <roles id="">
11462: <role></role>
11463: <access></access>
11464: <section></section>
11465: <group></group>
11466: </roles>
11467:
11468: <dom></dom> for scope type = domains
11469:
11470: <users> for scope type = users
11471: <user>
11472: <uname></uname>
11473: <udom></udom>
11474: </user>
11475: </users>
11476: </scope>
11477:
11478: Access data is also aggregated for each file in an additional key=value pair:
11479: key -> path to file/file_name\0accesscontrol
11480: value -> reference to hash
11481: hash contains key = value pairs
11482: where key = uniqueID:scope_end_start
11483: value = UNIX time record was last updated
11484:
11485: Used to improve speed of look-ups of access controls for each file.
11486:
11487: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11488:
11489: modify_access_controls():
11490:
11491: Modifies access controls for a portfolio file
11492: Args
11493: 1. file name
11494: 2. reference to hash of required changes,
11495: 3. domain
11496: 4. username
11497: where domain,username are the domain of the portfolio owner
11498: (either a user or a course)
11499:
11500: Returns:
11501: 1. result of additions or updates ('ok' or 'error', with error message).
11502: 2. result of deletions ('ok' or 'error', with error message).
11503: 3. reference to hash of any new or updated access controls.
11504: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11505: key = integer (inbound ID)
11506: value = uniqueID
1.747 albertel 11507:
1.608 albertel 11508: =back
11509:
1.243 albertel 11510: =head2 HTTP Helper Routines
11511:
11512: =over 4
11513:
1.191 harris41 11514: =item *
11515:
11516: escape() : unpack non-word characters into CGI-compatible hex codes
11517:
11518: =item *
11519:
11520: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11521:
1.243 albertel 11522: =back
11523:
11524: =head1 PRIVATE SUBROUTINES
11525:
11526: =head2 Underlying communication routines (Shouldn't call)
11527:
11528: =over 4
11529:
11530: =item *
11531:
11532: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11533:
11534: =item *
11535:
11536: reply() : uses subreply to send a message to remote machine, logs all failures
11537:
11538: =item *
11539:
11540: critical() : passes a critical message to another server; if cannot
11541: get through then place message in connection buffer directory and
11542: returns con_delayed, if incapable of saving message, returns
11543: con_failed
11544:
11545: =item *
11546:
11547: reconlonc() : tries to reconnect lonc client processes.
11548:
11549: =back
11550:
11551: =head2 Resource Access Logging
11552:
11553: =over 4
11554:
11555: =item *
11556:
11557: flushcourselogs() : flush (save) buffer logs and access logs
11558:
11559: =item *
11560:
11561: courselog($what) : save message for course in hash
11562:
11563: =item *
11564:
11565: courseacclog($what) : save message for course using &courselog(). Perform
11566: special processing for specific resource types (problems, exams, quizzes, etc).
11567:
1.191 harris41 11568: =item *
11569:
11570: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11571: as a PerlChildExitHandler
1.243 albertel 11572:
11573: =back
11574:
11575: =head2 Other
11576:
11577: =over 4
11578:
11579: =item *
11580:
11581: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11582:
11583: =back
11584:
11585: =cut
1.877 foxr 11586:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>