Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.11
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.11! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.10 2010/09/27 01:41: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.1056.4.5 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.1056.4.3 raeburn 199: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
1.1056.4.3 raeburn 214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: }
220: }
221: my ($answer,$loncaparev);
222: my @ids=¤t_machine_ids();
223: if (grep(/^\Q$lonhost\E$/,@ids)) {
224: $answer = $perlvar{'lonVersion'};
1.1056.4.7 raeburn 225: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 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.1056.4.8 raeburn 233: $ua->timeout(4);
1.1056.4.3 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.1056.4.7 raeburn 241: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3 raeburn 242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
1.1056.4.7 raeburn 248: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 249: $loncaparev = $1;
250: }
251: }
252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
253: }
254: }
255:
256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 260: if (defined($cached)) {
1.1056.4.3 raeburn 261: return $serverhomeID;
262: }
263: }
264: my $cachetime = 12*3600;
265: my $serverhomeID;
266: if ($caller eq 'loncron') {
267: my @machine_ids = &machine_ids($hostname);
268: foreach my $id (@machine_ids) {
269: my $response = &reply('serverhomeID',$id);
270: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
271: $serverhomeID = $response;
272: last;
273: }
1.993 raeburn 274: }
1.1056.4.3 raeburn 275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 280: }
1.1056.4.3 raeburn 281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 282: }
283:
1.1 albertel 284: # -------------------------------------------------- Non-critical communication
285: sub subreply {
286: my ($cmd,$server)=@_;
1.838 albertel 287: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 288: #
289: # With loncnew process trimming, there's a timing hole between lonc server
290: # process exit and the master server picking up the listen on the AF_UNIX
291: # socket. In that time interval, a lock file will exist:
292:
293: my $lockfile=$peerfile.".lock";
294: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
295: sleep(1);
296: }
297: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 298: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 299: #
1.550 foxr 300: # We'll give the connection a few tries before abandoning it. If
301: # connection is not possible, we'll con_lost back to the client.
302: #
303: my $client;
304: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
305: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
306: Type => SOCK_STREAM,
307: Timeout => 10);
1.869 albertel 308: if ($client) {
1.550 foxr 309: last; # Connected!
1.850 albertel 310: } else {
1.853 albertel 311: &create_connection(&hostname($server),$server);
1.550 foxr 312: }
1.850 albertel 313: sleep(1); # Try again later if failed connection.
1.550 foxr 314: }
315: my $answer;
316: if ($client) {
1.704 albertel 317: print $client "sethost:$server:$cmd\n";
1.550 foxr 318: $answer=<$client>;
319: if (!$answer) { $answer="con_lost"; }
320: chomp($answer);
321: } else {
322: $answer = 'con_lost'; # Failed connection.
323: }
1.1 albertel 324: return $answer;
325: }
326:
327: sub reply {
328: my ($cmd,$server)=@_;
1.838 albertel 329: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 330: my $answer=subreply($cmd,$server);
1.65 www 331: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 332: &logthis("<font color=\"blue\">WARNING:".
1.12 www 333: " $cmd to $server returned $answer</font>");
334: }
1.1 albertel 335: return $answer;
336: }
337:
338: # ----------------------------------------------------------- Send USR1 to lonc
339:
340: sub reconlonc {
1.891 albertel 341: my ($lonid) = @_;
342: my $hostname = &hostname($lonid);
343: if ($lonid) {
344: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
345: if ($hostname && -e $peerfile) {
346: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
347: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
348: Type => SOCK_STREAM,
349: Timeout => 10);
350: if ($client) {
351: print $client ("reset_retries\n");
352: my $answer=<$client>;
353: #reset just this one.
354: }
355: }
356: return;
357: }
358:
1.836 www 359: &logthis("Trying to reconnect lonc");
1.1 albertel 360: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 361: if (open(my $fh,"<$loncfile")) {
1.1 albertel 362: my $loncpid=<$fh>;
363: chomp($loncpid);
364: if (kill 0 => $loncpid) {
365: &logthis("lonc at pid $loncpid responding, sending USR1");
366: kill USR1 => $loncpid;
367: sleep 1;
1.836 www 368: } else {
1.12 www 369: &logthis(
1.672 albertel 370: "<font color=\"blue\">WARNING:".
1.12 www 371: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 372: }
373: } else {
1.836 www 374: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 375: }
376: }
377:
378: # ------------------------------------------------------ Critical communication
1.12 www 379:
1.1 albertel 380: sub critical {
381: my ($cmd,$server)=@_;
1.838 albertel 382: unless (&hostname($server)) {
1.672 albertel 383: &logthis("<font color=\"blue\">WARNING:".
1.89 www 384: " Critical message to unknown server ($server)</font>");
385: return 'no_such_host';
386: }
1.1 albertel 387: my $answer=reply($cmd,$server);
388: if ($answer eq 'con_lost') {
389: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 390: my $answer=reply($cmd,$server);
1.1 albertel 391: if ($answer eq 'con_lost') {
392: my $now=time;
393: my $middlename=$cmd;
1.5 www 394: $middlename=substr($middlename,0,16);
1.1 albertel 395: $middlename=~s/\W//g;
396: my $dfilename=
1.305 www 397: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
398: $dumpcount++;
1.1 albertel 399: {
1.448 albertel 400: my $dfh;
401: if (open($dfh,">$dfilename")) {
402: print $dfh "$cmd\n";
403: close($dfh);
404: }
1.1 albertel 405: }
406: sleep 2;
407: my $wcmd='';
408: {
1.448 albertel 409: my $dfh;
410: if (open($dfh,"<$dfilename")) {
411: $wcmd=<$dfh>;
412: close($dfh);
413: }
1.1 albertel 414: }
415: chomp($wcmd);
1.7 www 416: if ($wcmd eq $cmd) {
1.672 albertel 417: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 418: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 419: &logperm("D:$server:$cmd");
420: return 'con_delayed';
421: } else {
1.672 albertel 422: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 423: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 424: &logperm("F:$server:$cmd");
425: return 'con_failed';
426: }
427: }
428: }
429: return $answer;
1.405 albertel 430: }
431:
1.755 albertel 432: # ------------------------------------------- check if return value is an error
433:
434: sub error {
435: my ($result) = @_;
1.756 albertel 436: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 437: if ($2 == 2) { return undef; }
438: return $1;
439: }
440: return undef;
441: }
442:
1.783 albertel 443: sub convert_and_load_session_env {
444: my ($lonidsdir,$handle)=@_;
445: my @profile;
446: {
1.917 albertel 447: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
448: if (!$opened) {
1.915 albertel 449: return 0;
450: }
1.783 albertel 451: flock($idf,LOCK_SH);
452: @profile=<$idf>;
453: close($idf);
454: }
455: my %temp_env;
456: foreach my $line (@profile) {
1.786 albertel 457: if ($line !~ m/=/) {
458: return 0;
459: }
1.783 albertel 460: chomp($line);
461: my ($envname,$envvalue)=split(/=/,$line,2);
462: $temp_env{&unescape($envname)} = &unescape($envvalue);
463: }
464: unlink("$lonidsdir/$handle.id");
465: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
466: 0640)) {
467: %disk_env = %temp_env;
468: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
469: untie(%disk_env);
470: }
1.786 albertel 471: return 1;
1.783 albertel 472: }
473:
1.374 www 474: # ------------------------------------------- Transfer profile into environment
1.780 albertel 475: my $env_loaded;
476: sub transfer_profile_to_env {
1.788 albertel 477: my ($lonidsdir,$handle,$force_transfer) = @_;
478: if (!$force_transfer && $env_loaded) { return; }
1.374 www 479:
1.720 albertel 480: if (!defined($lonidsdir)) {
481: $lonidsdir = $perlvar{'lonIDsDir'};
482: }
483: if (!defined($handle)) {
484: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
485: }
486:
1.786 albertel 487: my $convert;
488: {
1.917 albertel 489: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
490: if (!$opened) {
1.915 albertel 491: return;
492: }
1.786 albertel 493: flock($idf,LOCK_SH);
494: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
495: &GDBM_READER(),0640)) {
496: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
497: untie(%disk_env);
498: } else {
499: $convert = 1;
500: }
501: }
502: if ($convert) {
503: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
504: &logthis("Failed to load session, or convert session.");
505: }
1.374 www 506: }
1.783 albertel 507:
1.786 albertel 508: my %remove;
1.783 albertel 509: while ( my $envname = each(%env) ) {
1.433 matthew 510: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
511: if ($time < time-300) {
1.783 albertel 512: $remove{$key}++;
1.433 matthew 513: }
514: }
515: }
1.783 albertel 516:
1.619 albertel 517: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 518: $env_loaded=1;
1.783 albertel 519: foreach my $expired_key (keys(%remove)) {
1.433 matthew 520: &delenv($expired_key);
1.374 www 521: }
1.1 albertel 522: }
523:
1.916 albertel 524: # ---------------------------------------------------- Check for valid session
525: sub check_for_valid_session {
526: my ($r) = @_;
527: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
528: my $lonid=$cookies{'lonID'};
529: return undef if (!$lonid);
530:
531: my $handle=&LONCAPA::clean_handle($lonid->value);
532: my $lonidsdir=$r->dir_config('lonIDsDir');
533: return undef if (!-e "$lonidsdir/$handle.id");
534:
1.917 albertel 535: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
536: return undef if (!$opened);
1.916 albertel 537:
538: flock($idf,LOCK_SH);
539: my %disk_env;
540: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
541: &GDBM_READER(),0640)) {
542: return undef;
543: }
544:
545: if (!defined($disk_env{'user.name'})
546: || !defined($disk_env{'user.domain'})) {
547: return undef;
548: }
549: return $handle;
550: }
551:
1.830 albertel 552: sub timed_flock {
553: my ($file,$lock_type) = @_;
554: my $failed=0;
555: eval {
556: local $SIG{__DIE__}='DEFAULT';
557: local $SIG{ALRM}=sub {
558: $failed=1;
559: die("failed lock");
560: };
561: alarm(13);
562: flock($file,$lock_type);
563: alarm(0);
564: };
565: if ($failed) {
566: return undef;
567: } else {
568: return 1;
569: }
570: }
571:
1.5 www 572: # ---------------------------------------------------------- Append Environment
573:
574: sub appenv {
1.949 raeburn 575: my ($newenv,$roles) = @_;
576: if (ref($newenv) eq 'HASH') {
577: foreach my $key (keys(%{$newenv})) {
578: my $refused = 0;
579: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
580: $refused = 1;
581: if (ref($roles) eq 'ARRAY') {
582: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
583: if (grep(/^\Q$role\E$/,@{$roles})) {
584: $refused = 0;
585: }
586: }
587: }
588: if ($refused) {
589: &logthis("<font color=\"blue\">WARNING: ".
590: "Attempt to modify environment ".$key." to ".$newenv->{$key}
591: .'</font>');
592: delete($newenv->{$key});
593: } else {
594: $env{$key}=$newenv->{$key};
595: }
596: }
597: my $opened = open(my $env_file,'+<',$env{'user.environment'});
598: if ($opened
599: && &timed_flock($env_file,LOCK_EX)
600: &&
601: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
602: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
603: while (my ($key,$value) = each(%{$newenv})) {
604: $disk_env{$key} = $value;
605: }
606: untie(%disk_env);
1.35 www 607: }
1.191 harris41 608: }
1.56 www 609: return 'ok';
610: }
611: # ----------------------------------------------------- Delete from Environment
612:
613: sub delenv {
1.987 raeburn 614: my ($delthis,$regexp) = @_;
1.56 www 615: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 616: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 617: "Attempt to delete from environment ".$delthis);
618: return 'error';
619: }
1.917 albertel 620: my $opened = open(my $env_file,'+<',$env{'user.environment'});
621: if ($opened
1.915 albertel 622: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 623: &&
624: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
625: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 626: foreach my $key (keys(%disk_env)) {
1.987 raeburn 627: if ($regexp) {
628: if ($key=~/^$delthis/) {
629: delete($env{$key});
630: delete($disk_env{$key});
631: }
632: } else {
633: if ($key=~/^\Q$delthis\E/) {
634: delete($env{$key});
635: delete($disk_env{$key});
636: }
637: }
1.448 albertel 638: }
1.783 albertel 639: untie(%disk_env);
1.5 www 640: }
641: return 'ok';
1.369 albertel 642: }
643:
1.790 albertel 644: sub get_env_multiple {
645: my ($name) = @_;
646: my @values;
647: if (defined($env{$name})) {
648: # exists is it an array
649: if (ref($env{$name})) {
650: @values=@{ $env{$name} };
651: } else {
652: $values[0]=$env{$name};
653: }
654: }
655: return(@values);
656: }
657:
1.958 www 658: # ------------------------------------------------------------------- Locking
659:
660: sub set_lock {
661: my ($text)=@_;
662: $locknum++;
663: my $id=$$.'-'.$locknum;
664: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
665: 'session.lock.'.$id => $text});
666: return $id;
667: }
668:
669: sub get_locks {
670: my $num=0;
671: my %texts=();
672: foreach my $lock (split(/\,/,$env{'session.locks'})) {
673: if ($lock=~/\w/) {
674: $num++;
675: $texts{$lock}=$env{'session.lock.'.$lock};
676: }
677: }
678: return ($num,%texts);
679: }
680:
681: sub remove_lock {
682: my ($id)=@_;
683: my $newlocks='';
684: foreach my $lock (split(/\,/,$env{'session.locks'})) {
685: if (($lock=~/\w/) && ($lock ne $id)) {
686: $newlocks.=','.$lock;
687: }
688: }
689: &appenv({'session.locks' => $newlocks});
690: &delenv('session.lock.'.$id);
691: }
692:
693: sub remove_all_locks {
694: my $activelocks=$env{'session.locks'};
695: foreach my $lock (split(/\,/,$env{'session.locks'})) {
696: if ($lock=~/\w/) {
697: &remove_lock($lock);
698: }
699: }
700: }
701:
702:
1.369 albertel 703: # ------------------------------------------ Find out current server userload
704: sub userload {
705: my $numusers=0;
706: {
707: opendir(LONIDS,$perlvar{'lonIDsDir'});
708: my $filename;
709: my $curtime=time;
710: while ($filename=readdir(LONIDS)) {
1.925 albertel 711: next if ($filename eq '.' || $filename eq '..');
712: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 713: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 714: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 715: }
716: closedir(LONIDS);
717: }
718: my $userloadpercent=0;
719: my $maxuserload=$perlvar{'lonUserLoadLim'};
720: if ($maxuserload) {
1.371 albertel 721: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 722: }
1.372 albertel 723: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 724: return $userloadpercent;
1.283 www 725: }
726:
727: # ------------------------------------------ Fight off request when overloaded
728:
729: sub overloaderror {
730: my ($r,$checkserver)=@_;
731: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
732: my $loadavg;
733: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 734: open(my $loadfile,'/proc/loadavg');
1.283 www 735: $loadavg=<$loadfile>;
736: $loadavg =~ s/\s.*//g;
1.285 matthew 737: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 738: close($loadfile);
1.283 www 739: } else {
740: $loadavg=&reply('load',$checkserver);
741: }
1.285 matthew 742: my $overload=$loadavg-100;
1.283 www 743: if ($overload>0) {
1.285 matthew 744: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 745: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 746: return 413;
1.283 www 747: }
748: return '';
1.5 www 749: }
1.1 albertel 750:
751: # ------------------------------ Find server with least workload from spare.tab
1.11 www 752:
1.1 albertel 753: sub spareserver {
1.670 albertel 754: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 755: my $spare_server;
1.370 albertel 756: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 757: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
758: : $userloadpercent;
1.1056.4.8 raeburn 759: my ($uint_dom,$remotesessions);
760: if ($env{'user.domain'}) {
761: my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
762: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
763: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
764: $remotesessions = $udomdefaults{'remotesessions'};
765: }
1.784 albertel 766: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8 raeburn 767: if ($uint_dom) {
768: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
769: $remotesessions,$try_server));
770: }
1.784 albertel 771: ($spare_server, $lowest_load) =
772: &compare_server_load($try_server, $spare_server, $lowest_load);
773: }
774:
775: my $found_server = ($spare_server ne '' && $lowest_load < 100);
776:
777: if (!$found_server) {
778: foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8 raeburn 779: if ($uint_dom) {
780: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
781: $remotesessions,$try_server));
782: }
1.784 albertel 783: ($spare_server, $lowest_load) =
784: &compare_server_load($try_server, $spare_server, $lowest_load);
785: }
786: }
787:
788: if (!$want_server_name) {
1.968 raeburn 789: my $protocol = 'http';
790: if ($protocol{$spare_server} eq 'https') {
791: $protocol = $protocol{$spare_server};
792: }
1.1001 raeburn 793: if (defined($spare_server)) {
794: my $hostname = &hostname($spare_server);
1.1056.4.8 raeburn 795: if (defined($hostname)) {
1.1001 raeburn 796: $spare_server = $protocol.'://'.$hostname;
797: }
798: }
1.784 albertel 799: }
800: return $spare_server;
801: }
802:
803: sub compare_server_load {
804: my ($try_server, $spare_server, $lowest_load) = @_;
805:
806: my $loadans = &reply('load', $try_server);
807: my $userloadans = &reply('userload',$try_server);
808:
809: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3 raeburn 810: return; #didn't get a number from the server
1.784 albertel 811: }
812:
813: my $load;
814: if ($loadans =~ /\d/) {
815: if ($userloadans =~ /\d/) {
816: #both are numbers, pick the bigger one
817: $load = ($loadans > $userloadans) ? $loadans
818: : $userloadans;
1.411 albertel 819: } else {
1.784 albertel 820: $load = $loadans;
1.411 albertel 821: }
1.784 albertel 822: } else {
823: $load = $userloadans;
824: }
825:
826: if (($load =~ /\d/) && ($load < $lowest_load)) {
827: $spare_server = $try_server;
828: $lowest_load = $load;
1.370 albertel 829: }
1.784 albertel 830: return ($spare_server,$lowest_load);
1.202 matthew 831: }
1.914 albertel 832:
833: # --------------------------- ask offload servers if user already has a session
834: sub find_existing_session {
835: my ($udom,$uname) = @_;
836: foreach my $try_server (@{ $spareid{'primary'} },
837: @{ $spareid{'default'} }) {
838: return $try_server if (&has_user_session($try_server, $udom, $uname));
839: }
840: return;
841: }
842:
843: # -------------------------------- ask if server already has a session for user
844: sub has_user_session {
845: my ($lonid,$udom,$uname) = @_;
846: my $result = &reply(join(':','userhassession',
847: map {&escape($_)} ($udom,$uname)),$lonid);
848: return 1 if ($result eq 'ok');
849:
850: return 0;
851: }
852:
1.1056.4.3 raeburn 853: # --------- determine least loaded server in a user's domain which allows login
854:
855: sub choose_server {
856: my ($udom) = @_;
857: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
858: my %servers = &get_servers($udom);
859: my $lowest_load = 30000;
860: my ($login_host,$hostname);
861: foreach my $lonhost (keys(%servers)) {
862: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
863: if ($loginvia eq '') {
864: ($login_host, $lowest_load) =
865: &compare_server_load($lonhost, $login_host, $lowest_load);
866: }
867: }
868: if ($login_host ne '') {
869: $hostname = $servers{$login_host};
870: }
871: return ($login_host,$hostname);
872: }
873:
1.202 matthew 874: # --------------------------------------------- Try to change a user's password
875:
876: sub changepass {
1.799 raeburn 877: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 878: $currentpass = &escape($currentpass);
879: $newpass = &escape($newpass);
1.1030 raeburn 880: my $lonhost = $perlvar{'lonHostID'};
881: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 882: $server);
883: if (! $answer) {
884: &logthis("No reply on password change request to $server ".
885: "by $uname in domain $udom.");
886: } elsif ($answer =~ "^ok") {
887: &logthis("$uname in $udom successfully changed their password ".
888: "on $server.");
889: } elsif ($answer =~ "^pwchange_failure") {
890: &logthis("$uname in $udom was unable to change their password ".
891: "on $server. The action was blocked by either lcpasswd ".
892: "or pwchange");
893: } elsif ($answer =~ "^non_authorized") {
894: &logthis("$uname in $udom did not get their password correct when ".
895: "attempting to change it on $server.");
896: } elsif ($answer =~ "^auth_mode_error") {
897: &logthis("$uname in $udom attempted to change their password despite ".
898: "not being locally or internally authenticated on $server.");
899: } elsif ($answer =~ "^unknown_user") {
900: &logthis("$uname in $udom attempted to change their password ".
901: "on $server but were unable to because $server is not ".
902: "their home server.");
903: } elsif ($answer =~ "^refused") {
904: &logthis("$server refused to change $uname in $udom password because ".
905: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 906: } elsif ($answer =~ "invalid_client") {
907: &logthis("$server refused to change $uname in $udom password because ".
908: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 909: }
910: return $answer;
1.1 albertel 911: }
912:
1.169 harris41 913: # ----------------------- Try to determine user's current authentication scheme
914:
915: sub queryauthenticate {
916: my ($uname,$udom)=@_;
1.456 albertel 917: my $uhome=&homeserver($uname,$udom);
918: if (!$uhome) {
919: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
920: return 'no_host';
921: }
922: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
923: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
924: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 925: }
1.456 albertel 926: return $answer;
1.169 harris41 927: }
928:
1.1 albertel 929: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 930:
1.1 albertel 931: sub authenticate {
1.1056.4.3 raeburn 932: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 933: $upass=&escape($upass);
934: $uname= &LONCAPA::clean_username($uname);
1.836 www 935: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 936: my $newhome;
1.836 www 937: if ((!$uhome) || ($uhome eq 'no_host')) {
938: # Maybe the machine was offline and only re-appeared again recently?
939: &reconlonc();
940: # One more
1.952 raeburn 941: $uhome=&homeserver($uname,$udom,1);
942: if (($uhome eq 'no_host') && $checkdefauth) {
943: if (defined(&domain($udom,'primary'))) {
944: $newhome=&domain($udom,'primary');
945: }
946: if ($newhome ne '') {
947: $uhome = $newhome;
948: }
949: }
1.836 www 950: if ((!$uhome) || ($uhome eq 'no_host')) {
951: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 952: return 'no_host';
953: }
1.1 albertel 954: }
1.1056.4.3 raeburn 955: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 956: if ($answer eq 'authorized') {
1.952 raeburn 957: if ($newhome) {
958: &logthis("User $uname at $udom authorized by $uhome, but needs account");
959: return 'no_account_on_host';
960: } else {
961: &logthis("User $uname at $udom authorized by $uhome");
962: return $uhome;
963: }
1.471 albertel 964: }
965: if ($answer eq 'non_authorized') {
966: &logthis("User $uname at $udom rejected by $uhome");
967: return 'no_host';
1.9 www 968: }
1.471 albertel 969: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 970: return 'no_host';
971: }
972:
1.1056.4.3 raeburn 973: sub can_host_session {
974: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
975: my $canhost = 1;
976: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
977: if (ref($remotesessions) eq 'HASH') {
978: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
979: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
980: $canhost = 0;
981: } else {
982: $canhost = 1;
983: }
984: }
985: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
986: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
987: $canhost = 1;
988: } else {
989: $canhost = 0;
990: }
991: }
992: if ($canhost) {
993: if ($remotesessions->{'version'} ne '') {
994: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
995: if ($reqmajor ne '' && $reqminor ne '') {
996: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
997: my $major = $1;
998: my $minor = $2;
999: if (($major < $reqmajor ) ||
1000: (($major == $reqmajor) && ($minor < $reqminor))) {
1001: $canhost = 0;
1002: }
1003: } else {
1004: $canhost = 0;
1005: }
1006: }
1007: }
1008: }
1009: }
1010: if ($canhost) {
1011: if (ref($hostedsessions) eq 'HASH') {
1012: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1013: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1014: $canhost = 0;
1015: } else {
1016: $canhost = 1;
1017: }
1018: }
1019: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1020: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1021: $canhost = 1;
1022: } else {
1023: $canhost = 0;
1024: }
1025: }
1026: }
1027: }
1028: return $canhost;
1029: }
1030:
1.1056.4.8 raeburn 1031: sub spare_can_host {
1032: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1033: my $canhost=1;
1034: my @intdoms;
1035: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1036: if (ref($internet_names) eq 'ARRAY') {
1037: @intdoms = @{$internet_names};
1038: }
1039: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1040: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1041: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1042: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1043: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1044: $canhost = &can_host_session($udom,$try_server,$remoterev,
1045: $remotesessions,
1046: $defdomdefaults{'hostedsessions'});
1047: }
1048: return $canhost;
1049: }
1050:
1.1 albertel 1051: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1052:
1.599 albertel 1053: my %homecache;
1.1 albertel 1054: sub homeserver {
1.230 stredwic 1055: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1056: my $index="$uname:$udom";
1.426 albertel 1057:
1.599 albertel 1058: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1059:
1060: my %servers = &get_servers($udom,'library');
1061: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1062: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1063: exists($badServerCache{$tryserver}));
1.841 albertel 1064:
1065: my $answer=reply("home:$udom:$uname",$tryserver);
1066: if ($answer eq 'found') {
1067: delete($badServerCache{$tryserver});
1068: return $homecache{$index}=$tryserver;
1069: } elsif ($answer eq 'no_host') {
1070: $badServerCache{$tryserver}=1;
1071: }
1.1 albertel 1072: }
1073: return 'no_host';
1.70 www 1074: }
1075:
1076: # ------------------------------------- Find the usernames behind a list of IDs
1077:
1078: sub idget {
1079: my ($udom,@ids)=@_;
1080: my %returnhash=();
1081:
1.841 albertel 1082: my %servers = &get_servers($udom,'library');
1083: foreach my $tryserver (keys(%servers)) {
1084: my $idlist=join('&',@ids);
1085: $idlist=~tr/A-Z/a-z/;
1086: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1087: my @answer=();
1088: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1089: @answer=split(/\&/,$reply);
1090: } ;
1091: my $i;
1092: for ($i=0;$i<=$#ids;$i++) {
1093: if ($answer[$i]) {
1094: $returnhash{$ids[$i]}=$answer[$i];
1095: }
1096: }
1097: }
1.70 www 1098: return %returnhash;
1099: }
1100:
1101: # ------------------------------------- Find the IDs behind a list of usernames
1102:
1103: sub idrget {
1104: my ($udom,@unames)=@_;
1105: my %returnhash=();
1.800 albertel 1106: foreach my $uname (@unames) {
1107: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1108: }
1.70 www 1109: return %returnhash;
1110: }
1111:
1112: # ------------------------------- Store away a list of names and associated IDs
1113:
1114: sub idput {
1115: my ($udom,%ids)=@_;
1116: my %servers=();
1.800 albertel 1117: foreach my $uname (keys(%ids)) {
1118: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1119: my $uhom=&homeserver($uname,$udom);
1.70 www 1120: if ($uhom ne 'no_host') {
1.800 albertel 1121: my $id=&escape($ids{$uname});
1.70 www 1122: $id=~tr/A-Z/a-z/;
1.800 albertel 1123: my $esc_unam=&escape($uname);
1.70 www 1124: if ($servers{$uhom}) {
1.800 albertel 1125: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1126: } else {
1.800 albertel 1127: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1128: }
1129: }
1.191 harris41 1130: }
1.800 albertel 1131: foreach my $server (keys(%servers)) {
1132: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1133: }
1.344 www 1134: }
1135:
1.1023 raeburn 1136: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1137: sub dump_dom {
1.1023 raeburn 1138: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1139: if (!$udom) {
1140: $udom=$env{'user.domain'};
1141: }
1142: my %returnhash;
1.1023 raeburn 1143: if ($udom) {
1144: my $uname = &get_domainconfiguser($udom);
1145: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1146: }
1147: return %returnhash;
1148: }
1149:
1.1023 raeburn 1150: # ------------------------------------------ get items from domain db files
1.806 raeburn 1151:
1152: sub get_dom {
1.860 raeburn 1153: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1154: my $items='';
1155: foreach my $item (@$storearr) {
1156: $items.=&escape($item).'&';
1157: }
1158: $items=~s/\&$//;
1.860 raeburn 1159: if (!$udom) {
1160: $udom=$env{'user.domain'};
1161: if (defined(&domain($udom,'primary'))) {
1162: $uhome=&domain($udom,'primary');
1163: } else {
1.874 albertel 1164: undef($uhome);
1.860 raeburn 1165: }
1166: } else {
1167: if (!$uhome) {
1168: if (defined(&domain($udom,'primary'))) {
1169: $uhome=&domain($udom,'primary');
1170: }
1171: }
1172: }
1173: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1174: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1175: my %returnhash;
1.875 albertel 1176: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1177: return %returnhash;
1178: }
1.806 raeburn 1179: my @pairs=split(/\&/,$rep);
1180: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1181: return @pairs;
1182: }
1183: my $i=0;
1184: foreach my $item (@$storearr) {
1185: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1186: $i++;
1187: }
1188: return %returnhash;
1189: } else {
1.880 banghart 1190: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1191: }
1192: }
1193:
1194: # -------------------------------------------- put items in domain db files
1195:
1196: sub put_dom {
1.860 raeburn 1197: my ($namespace,$storehash,$udom,$uhome)=@_;
1198: if (!$udom) {
1199: $udom=$env{'user.domain'};
1200: if (defined(&domain($udom,'primary'))) {
1201: $uhome=&domain($udom,'primary');
1202: } else {
1.874 albertel 1203: undef($uhome);
1.860 raeburn 1204: }
1205: } else {
1206: if (!$uhome) {
1207: if (defined(&domain($udom,'primary'))) {
1208: $uhome=&domain($udom,'primary');
1209: }
1210: }
1211: }
1212: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1213: my $items='';
1214: foreach my $item (keys(%$storehash)) {
1215: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1216: }
1217: $items=~s/\&$//;
1218: return &reply("putdom:$udom:$namespace:$items",$uhome);
1219: } else {
1.860 raeburn 1220: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1221: }
1222: }
1223:
1.1023 raeburn 1224: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1225: sub newput_dom {
1.1023 raeburn 1226: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1227: my $result;
1228: if (!$udom) {
1229: $udom=$env{'user.domain'};
1230: }
1.1023 raeburn 1231: if ($udom) {
1232: my $uname = &get_domainconfiguser($udom);
1233: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1234: }
1235: return $result;
1236: }
1237:
1.1023 raeburn 1238: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1239: sub del_dom {
1.1023 raeburn 1240: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1241: if (ref($storearr) eq 'ARRAY') {
1242: if (!$udom) {
1243: $udom=$env{'user.domain'};
1244: }
1.1023 raeburn 1245: if ($udom) {
1246: my $uname = &get_domainconfiguser($udom);
1247: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1248: }
1249: }
1250: }
1251:
1.1023 raeburn 1252: # ----------------------------------construct domainconfig user for a domain
1253: sub get_domainconfiguser {
1254: my ($udom) = @_;
1255: return $udom.'-domainconfig';
1256: }
1257:
1.837 raeburn 1258: sub retrieve_inst_usertypes {
1259: my ($udom) = @_;
1260: my (%returnhash,@order);
1.989 raeburn 1261: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1262: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1263: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1264: %returnhash = %{$domdefs{'inststatustypes'}};
1265: @order = @{$domdefs{'inststatusorder'}};
1266: } else {
1267: if (defined(&domain($udom,'primary'))) {
1268: my $uhome=&domain($udom,'primary');
1269: my $rep=&reply("inst_usertypes:$udom",$uhome);
1270: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1271: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1272: return (\%returnhash,\@order);
1273: }
1274: my ($hashitems,$orderitems) = split(/:/,$rep);
1275: my @pairs=split(/\&/,$hashitems);
1276: foreach my $item (@pairs) {
1277: my ($key,$value)=split(/=/,$item,2);
1278: $key = &unescape($key);
1279: next if ($key =~ /^error: 2 /);
1280: $returnhash{$key}=&thaw_unescape($value);
1281: }
1282: my @esc_order = split(/\&/,$orderitems);
1283: foreach my $item (@esc_order) {
1284: push(@order,&unescape($item));
1285: }
1286: } else {
1287: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1288: }
1289: }
1290: return (\%returnhash,\@order);
1291: }
1292:
1.868 raeburn 1293: sub is_domainimage {
1294: my ($url) = @_;
1295: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1296: if (&domain($1) ne '') {
1297: return '1';
1298: }
1299: }
1300: return;
1301: }
1302:
1.899 raeburn 1303: sub inst_directory_query {
1304: my ($srch) = @_;
1305: my $udom = $srch->{'srchdomain'};
1306: my %results;
1307: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1308: my $outcome;
1.899 raeburn 1309: if ($homeserver ne '') {
1.904 albertel 1310: my $queryid=&reply("querysend:instdirsearch:".
1311: &escape($srch->{'srchby'}).':'.
1312: &escape($srch->{'srchterm'}).':'.
1313: &escape($srch->{'srchtype'}),$homeserver);
1314: my $host=&hostname($homeserver);
1315: if ($queryid !~/^\Q$host\E\_/) {
1316: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1317: return;
1318: }
1319: my $response = &get_query_reply($queryid);
1320: my $maxtries = 5;
1321: my $tries = 1;
1322: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1323: $response = &get_query_reply($queryid);
1324: $tries ++;
1325: }
1326:
1327: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1328: if ($response eq 'unavailable') {
1329: $outcome = $response;
1330: } else {
1331: $outcome = 'ok';
1332: my @matches = split(/\n/,$response);
1333: foreach my $match (@matches) {
1334: my ($key,$value) = split(/=/,$match);
1335: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1336: }
1.899 raeburn 1337: }
1338: }
1339: }
1.909 raeburn 1340: return ($outcome,%results);
1.899 raeburn 1341: }
1342:
1343: sub usersearch {
1344: my ($srch) = @_;
1345: my $dom = $srch->{'srchdomain'};
1346: my %results;
1347: my %libserv = &all_library();
1348: my $query = 'usersearch';
1349: foreach my $tryserver (keys(%libserv)) {
1350: if (&host_domain($tryserver) eq $dom) {
1351: my $host=&hostname($tryserver);
1352: my $queryid=
1.911 raeburn 1353: &reply("querysend:".&escape($query).':'.
1354: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1355: &escape($srch->{'srchtype'}).':'.
1356: &escape($srch->{'srchterm'}),$tryserver);
1357: if ($queryid !~/^\Q$host\E\_/) {
1358: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1359: next;
1.899 raeburn 1360: }
1361: my $reply = &get_query_reply($queryid);
1362: my $maxtries = 1;
1363: my $tries = 1;
1364: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1365: $reply = &get_query_reply($queryid);
1366: $tries ++;
1367: }
1368: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1369: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1370: } else {
1.911 raeburn 1371: my @matches;
1372: if ($reply =~ /\n/) {
1373: @matches = split(/\n/,$reply);
1374: } else {
1375: @matches = split(/\&/,$reply);
1376: }
1.899 raeburn 1377: foreach my $match (@matches) {
1378: my ($uname,$udom,%userhash);
1.911 raeburn 1379: foreach my $entry (split(/:/,$match)) {
1380: my ($key,$value) =
1381: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1382: $userhash{$key} = $value;
1383: if ($key eq 'username') {
1384: $uname = $value;
1385: } elsif ($key eq 'domain') {
1386: $udom = $value;
1.911 raeburn 1387: }
1.899 raeburn 1388: }
1389: $results{$uname.':'.$udom} = \%userhash;
1390: }
1391: }
1392: }
1393: }
1394: return %results;
1395: }
1396:
1.912 raeburn 1397: sub get_instuser {
1398: my ($udom,$uname,$id) = @_;
1399: my $homeserver = &domain($udom,'primary');
1400: my ($outcome,%results);
1401: if ($homeserver ne '') {
1402: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1403: &escape($id).':'.&escape($udom),$homeserver);
1404: my $host=&hostname($homeserver);
1405: if ($queryid !~/^\Q$host\E\_/) {
1406: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1407: return;
1408: }
1409: my $response = &get_query_reply($queryid);
1410: my $maxtries = 5;
1411: my $tries = 1;
1412: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1413: $response = &get_query_reply($queryid);
1414: $tries ++;
1415: }
1416: if (!&error($response) && $response ne 'refused') {
1417: if ($response eq 'unavailable') {
1418: $outcome = $response;
1419: } else {
1420: $outcome = 'ok';
1421: my @matches = split(/\n/,$response);
1422: foreach my $match (@matches) {
1423: my ($key,$value) = split(/=/,$match);
1424: $results{&unescape($key)} = &thaw_unescape($value);
1425: }
1426: }
1427: }
1428: }
1429: my %userinfo;
1430: if (ref($results{$uname}) eq 'HASH') {
1431: %userinfo = %{$results{$uname}};
1432: }
1433: return ($outcome,%userinfo);
1434: }
1435:
1436: sub inst_rulecheck {
1.923 raeburn 1437: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1438: my %returnhash;
1439: if ($udom ne '') {
1440: if (ref($rules) eq 'ARRAY') {
1441: @{$rules} = map {&escape($_);} (@{$rules});
1442: my $rulestr = join(':',@{$rules});
1443: my $homeserver=&domain($udom,'primary');
1444: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1445: my $response;
1446: if ($item eq 'username') {
1447: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1448: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1449: $homeserver));
1.923 raeburn 1450: } elsif ($item eq 'id') {
1451: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1452: ':'.&escape($id).':'.$rulestr,
1453: $homeserver));
1.945 raeburn 1454: } elsif ($item eq 'selfcreate') {
1455: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1456: &escape($udom).':'.&escape($uname).
1457: ':'.$rulestr,$homeserver));
1.923 raeburn 1458: }
1.912 raeburn 1459: if ($response ne 'refused') {
1460: my @pairs=split(/\&/,$response);
1461: foreach my $item (@pairs) {
1462: my ($key,$value)=split(/=/,$item,2);
1463: $key = &unescape($key);
1464: next if ($key =~ /^error: 2 /);
1465: $returnhash{$key}=&thaw_unescape($value);
1466: }
1467: }
1468: }
1469: }
1470: }
1471: return %returnhash;
1472: }
1473:
1474: sub inst_userrules {
1.923 raeburn 1475: my ($udom,$check) = @_;
1.912 raeburn 1476: my (%ruleshash,@ruleorder);
1477: if ($udom ne '') {
1478: my $homeserver=&domain($udom,'primary');
1479: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1480: my $response;
1481: if ($check eq 'id') {
1482: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1483: $homeserver);
1.943 raeburn 1484: } elsif ($check eq 'email') {
1485: $response=&reply('instemailrules:'.&escape($udom),
1486: $homeserver);
1.923 raeburn 1487: } else {
1488: $response=&reply('instuserrules:'.&escape($udom),
1489: $homeserver);
1490: }
1.912 raeburn 1491: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1492: ($response ne 'unknown_cmd') &&
1.912 raeburn 1493: ($response ne 'no_such_host')) {
1494: my ($hashitems,$orderitems) = split(/:/,$response);
1495: my @pairs=split(/\&/,$hashitems);
1496: foreach my $item (@pairs) {
1497: my ($key,$value)=split(/=/,$item,2);
1498: $key = &unescape($key);
1499: next if ($key =~ /^error: 2 /);
1500: $ruleshash{$key}=&thaw_unescape($value);
1501: }
1502: my @esc_order = split(/\&/,$orderitems);
1503: foreach my $item (@esc_order) {
1504: push(@ruleorder,&unescape($item));
1505: }
1506: }
1507: }
1508: }
1509: return (\%ruleshash,\@ruleorder);
1510: }
1511:
1.976 raeburn 1512: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1513:
1514: sub get_domain_defaults {
1515: my ($domain) = @_;
1516: my $cachetime = 60*60*24;
1517: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1518: if (defined($cached)) {
1519: if (ref($result) eq 'HASH') {
1520: return %{$result};
1521: }
1522: }
1523: my %domdefaults;
1524: my %domconfig =
1.989 raeburn 1525: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1526: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1527: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1528: if (ref($domconfig{'defaults'}) eq 'HASH') {
1529: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1530: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1531: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1532: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1533: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1534: } else {
1535: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1536: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1537: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1538: }
1.976 raeburn 1539: if (ref($domconfig{'quotas'}) eq 'HASH') {
1540: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1541: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1542: } else {
1543: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1544: }
1545: my @usertools = ('aboutme','blog','portfolio');
1546: foreach my $item (@usertools) {
1547: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1548: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1549: }
1550: }
1551: }
1.985 raeburn 1552: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1553: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1554: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1555: }
1556: }
1.989 raeburn 1557: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1558: foreach my $item ('inststatustypes','inststatusorder') {
1559: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1560: }
1561: }
1.1047 raeburn 1562: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1563: foreach my $item ('canuse_pdfforms') {
1564: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1565: }
1566: }
1.1056.4.3 raeburn 1567: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1568: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1569: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1570: }
1571: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1572: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1573: }
1574: }
1.943 raeburn 1575: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1576: $cachetime);
1577: return %domdefaults;
1578: }
1579:
1.344 www 1580: # --------------------------------------------------- Assign a key to a student
1581:
1582: sub assign_access_key {
1.364 www 1583: #
1584: # a valid key looks like uname:udom#comments
1585: # comments are being appended
1586: #
1.498 www 1587: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1588: $kdom=
1.620 albertel 1589: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1590: $knum=
1.620 albertel 1591: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1592: $cdom=
1.620 albertel 1593: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1594: $cnum=
1.620 albertel 1595: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1596: $udom=$env{'user.name'} unless (defined($udom));
1597: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1598: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1599: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1600: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1601: # assigned to this person
1602: # - this should not happen,
1.345 www 1603: # unless something went wrong
1604: # the first time around
1605: # ready to assign
1.364 www 1606: $logentry=$1.'; '.$logentry;
1.496 www 1607: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1608: $kdom,$knum) eq 'ok') {
1.345 www 1609: # key now belongs to user
1.346 www 1610: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1611: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1612: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1613: return 'ok';
1614: } else {
1615: return
1616: 'error: Count not permanently assign key, will need to be re-entered later.';
1617: }
1618: } else {
1619: return 'error: Could not assign key, try again later.';
1620: }
1.364 www 1621: } elsif (!$existing{$ckey}) {
1.345 www 1622: # the key does not exist
1623: return 'error: The key does not exist';
1624: } else {
1625: # the key is somebody else's
1626: return 'error: The key is already in use';
1627: }
1.344 www 1628: }
1629:
1.364 www 1630: # ------------------------------------------ put an additional comment on a key
1631:
1632: sub comment_access_key {
1633: #
1634: # a valid key looks like uname:udom#comments
1635: # comments are being appended
1636: #
1637: my ($ckey,$cdom,$cnum,$logentry)=@_;
1638: $cdom=
1.620 albertel 1639: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1640: $cnum=
1.620 albertel 1641: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1642: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1643: if ($existing{$ckey}) {
1644: $existing{$ckey}.='; '.$logentry;
1645: # ready to assign
1.367 www 1646: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1647: $cdom,$cnum) eq 'ok') {
1648: return 'ok';
1649: } else {
1650: return 'error: Count not store comment.';
1651: }
1652: } else {
1653: # the key does not exist
1654: return 'error: The key does not exist';
1655: }
1656: }
1657:
1.344 www 1658: # ------------------------------------------------------ Generate a set of keys
1659:
1660: sub generate_access_keys {
1.364 www 1661: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1662: $cdom=
1.620 albertel 1663: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1664: $cnum=
1.620 albertel 1665: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1666: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1667: unless (($cdom) && ($cnum)) { return 0; }
1668: if ($number>10000) { return 0; }
1669: sleep(2); # make sure don't get same seed twice
1670: srand(time()^($$+($$<<15))); # from "Programming Perl"
1671: my $total=0;
1672: for (my $i=1;$i<=$number;$i++) {
1673: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1674: sprintf("%lx",int(100000*rand)).'-'.
1675: sprintf("%lx",int(100000*rand));
1676: $newkey=~s/1/g/g; # folks mix up 1 and l
1677: $newkey=~s/0/h/g; # and also 0 and O
1678: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1679: if ($existing{$newkey}) {
1680: $i--;
1681: } else {
1.364 www 1682: if (&put('accesskeys',
1683: { $newkey => '# generated '.localtime().
1.620 albertel 1684: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1685: '; '.$logentry },
1686: $cdom,$cnum) eq 'ok') {
1.344 www 1687: $total++;
1688: }
1689: }
1690: }
1.620 albertel 1691: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1692: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1693: return $total;
1694: }
1695:
1696: # ------------------------------------------------------- Validate an accesskey
1697:
1698: sub validate_access_key {
1699: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1700: $cdom=
1.620 albertel 1701: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1702: $cnum=
1.620 albertel 1703: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1704: $udom=$env{'user.domain'} unless (defined($udom));
1705: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1706: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1707: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1708: }
1709:
1710: # ------------------------------------- Find the section of student in a course
1.652 albertel 1711: sub devalidate_getsection_cache {
1712: my ($udom,$unam,$courseid)=@_;
1713: my $hashid="$udom:$unam:$courseid";
1714: &devalidate_cache_new('getsection',$hashid);
1715: }
1.298 matthew 1716:
1.815 albertel 1717: sub courseid_to_courseurl {
1718: my ($courseid) = @_;
1719: #already url style courseid
1720: return $courseid if ($courseid =~ m{^/});
1721:
1722: if (exists($env{'course.'.$courseid.'.num'})) {
1723: my $cnum = $env{'course.'.$courseid.'.num'};
1724: my $cdom = $env{'course.'.$courseid.'.domain'};
1725: return "/$cdom/$cnum";
1726: }
1727:
1728: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1729: if (exists($courseinfo{'num'})) {
1730: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1731: }
1732:
1733: return undef;
1734: }
1735:
1.298 matthew 1736: sub getsection {
1737: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1738: my $cachetime=1800;
1.551 albertel 1739:
1740: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1741: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1742: if (defined($cached)) { return $result; }
1743:
1.298 matthew 1744: my %Pending;
1745: my %Expired;
1746: #
1747: # Each role can either have not started yet (pending), be active,
1748: # or have expired.
1749: #
1750: # If there is an active role, we are done.
1751: #
1752: # If there is more than one role which has not started yet,
1753: # choose the one which will start sooner
1754: # If there is one role which has not started yet, return it.
1755: #
1756: # If there is more than one expired role, choose the one which ended last.
1757: # If there is a role which has expired, return it.
1758: #
1.815 albertel 1759: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1760: my $extra = &freeze_escape({'skipcheck' => 1});
1761: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1762: foreach my $key (keys(%roleshash)) {
1.479 albertel 1763: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1764: my $section=$1;
1765: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1766: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1767: my $now=time;
1.548 albertel 1768: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1769: $Expired{$end}=$section;
1770: next;
1771: }
1.548 albertel 1772: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1773: $Pending{$start}=$section;
1774: next;
1775: }
1.599 albertel 1776: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1777: }
1778: #
1779: # Presumedly there will be few matching roles from the above
1780: # loop and the sorting time will be negligible.
1781: if (scalar(keys(%Pending))) {
1782: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1783: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1784: }
1785: if (scalar(keys(%Expired))) {
1786: my @sorted = sort {$a <=> $b} keys(%Expired);
1787: my $time = pop(@sorted);
1.599 albertel 1788: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1789: }
1.599 albertel 1790: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1791: }
1.70 www 1792:
1.599 albertel 1793: sub save_cache {
1794: &purge_remembered();
1.722 albertel 1795: #&Apache::loncommon::validate_page();
1.620 albertel 1796: undef(%env);
1.780 albertel 1797: undef($env_loaded);
1.599 albertel 1798: }
1.452 albertel 1799:
1.599 albertel 1800: my $to_remember=-1;
1801: my %remembered;
1802: my %accessed;
1803: my $kicks=0;
1804: my $hits=0;
1.849 albertel 1805: sub make_key {
1806: my ($name,$id) = @_;
1.872 albertel 1807: if (length($id) > 65
1808: && length(&escape($id)) > 200) {
1809: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1810: }
1.849 albertel 1811: return &escape($name.':'.$id);
1812: }
1813:
1.599 albertel 1814: sub devalidate_cache_new {
1815: my ($name,$id,$debug) = @_;
1816: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1817: $id=&make_key($name,$id);
1.599 albertel 1818: $memcache->delete($id);
1819: delete($remembered{$id});
1820: delete($accessed{$id});
1821: }
1822:
1823: sub is_cached_new {
1824: my ($name,$id,$debug) = @_;
1.849 albertel 1825: $id=&make_key($name,$id);
1.599 albertel 1826: if (exists($remembered{$id})) {
1827: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1828: $accessed{$id}=[&gettimeofday()];
1829: $hits++;
1830: return ($remembered{$id},1);
1831: }
1832: my $value = $memcache->get($id);
1833: if (!(defined($value))) {
1834: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1835: return (undef,undef);
1.416 albertel 1836: }
1.599 albertel 1837: if ($value eq '__undef__') {
1838: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1839: $value=undef;
1840: }
1841: &make_room($id,$value,$debug);
1842: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1843: return ($value,1);
1844: }
1845:
1846: sub do_cache_new {
1847: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1848: $id=&make_key($name,$id);
1.599 albertel 1849: my $setvalue=$value;
1850: if (!defined($setvalue)) {
1851: $setvalue='__undef__';
1852: }
1.623 albertel 1853: if (!defined($time) ) {
1854: $time=600;
1855: }
1.599 albertel 1856: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1857: my $result = $memcache->set($id,$setvalue,$time);
1858: if (! $result) {
1.872 albertel 1859: &logthis("caching of id -> $id failed");
1.910 albertel 1860: $memcache->disconnect_all();
1.872 albertel 1861: }
1.600 albertel 1862: # need to make a copy of $value
1.919 albertel 1863: &make_room($id,$value,$debug);
1.599 albertel 1864: return $value;
1865: }
1866:
1867: sub make_room {
1868: my ($id,$value,$debug)=@_;
1.919 albertel 1869:
1870: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1871: : $value;
1.599 albertel 1872: if ($to_remember<0) { return; }
1873: $accessed{$id}=[&gettimeofday()];
1874: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1875: my $to_kick;
1876: my $max_time=0;
1877: foreach my $other (keys(%accessed)) {
1878: if (&tv_interval($accessed{$other}) > $max_time) {
1879: $to_kick=$other;
1880: $max_time=&tv_interval($accessed{$other});
1881: }
1882: }
1883: delete($remembered{$to_kick});
1884: delete($accessed{$to_kick});
1885: $kicks++;
1886: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1887: return;
1888: }
1889:
1.599 albertel 1890: sub purge_remembered {
1.604 albertel 1891: #&logthis("Tossing ".scalar(keys(%remembered)));
1892: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1893: undef(%remembered);
1894: undef(%accessed);
1.428 albertel 1895: }
1.70 www 1896: # ------------------------------------- Read an entry from a user's environment
1897:
1898: sub userenvironment {
1899: my ($udom,$unam,@what)=@_;
1.976 raeburn 1900: my $items;
1901: foreach my $item (@what) {
1902: $items.=&escape($item).'&';
1903: }
1904: $items=~s/\&$//;
1.70 www 1905: my %returnhash=();
1.1009 raeburn 1906: my $uhome = &homeserver($unam,$udom);
1907: unless ($uhome eq 'no_host') {
1908: my @answer=split(/\&/,
1909: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1910: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1911: return %returnhash;
1912: }
1.1009 raeburn 1913: my $i;
1914: for ($i=0;$i<=$#what;$i++) {
1915: $returnhash{$what[$i]}=&unescape($answer[$i]);
1916: }
1.70 www 1917: }
1918: return %returnhash;
1.1 albertel 1919: }
1920:
1.617 albertel 1921: # ---------------------------------------------------------- Get a studentphoto
1922: sub studentphoto {
1923: my ($udom,$unam,$ext) = @_;
1924: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1925: if (defined($env{'request.course.id'})) {
1.708 raeburn 1926: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1927: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1928: return(&retrievestudentphoto($udom,$unam,$ext));
1929: } else {
1930: my ($result,$perm_reqd)=
1.707 albertel 1931: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1932: if ($result eq 'ok') {
1933: if (!($perm_reqd eq 'yes')) {
1934: return(&retrievestudentphoto($udom,$unam,$ext));
1935: }
1936: }
1937: }
1938: }
1939: } else {
1940: my ($result,$perm_reqd) =
1.707 albertel 1941: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1942: if ($result eq 'ok') {
1943: if (!($perm_reqd eq 'yes')) {
1944: return(&retrievestudentphoto($udom,$unam,$ext));
1945: }
1946: }
1947: }
1948: return '/adm/lonKaputt/lonlogo_broken.gif';
1949: }
1950:
1951: sub retrievestudentphoto {
1952: my ($udom,$unam,$ext,$type) = @_;
1953: my $home=&Apache::lonnet::homeserver($unam,$udom);
1954: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1955: if ($ret eq 'ok') {
1956: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1957: if ($type eq 'thumbnail') {
1958: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1959: }
1960: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1961: return $tokenurl;
1962: } else {
1963: if ($type eq 'thumbnail') {
1964: return '/adm/lonKaputt/genericstudent_tn.gif';
1965: } else {
1966: return '/adm/lonKaputt/lonlogo_broken.gif';
1967: }
1.617 albertel 1968: }
1969: }
1970:
1.263 www 1971: # -------------------------------------------------------------------- New chat
1972:
1973: sub chatsend {
1.724 raeburn 1974: my ($newentry,$anon,$group)=@_;
1.620 albertel 1975: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1976: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1977: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1978: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1979: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1980: &escape($newentry)).':'.$group,$chome);
1.292 www 1981: }
1982:
1983: # ------------------------------------------ Find current version of a resource
1984:
1985: sub getversion {
1986: my $fname=&clutter(shift);
1987: unless ($fname=~/^\/res\//) { return -1; }
1988: return ¤tversion(&filelocation('',$fname));
1989: }
1990:
1991: sub currentversion {
1992: my $fname=shift;
1.599 albertel 1993: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1994: if (defined($cached)) { return $result; }
1.292 www 1995: my $author=$fname;
1996: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1997: my ($udom,$uname)=split(/\//,$author);
1998: my $home=homeserver($uname,$udom);
1999: if ($home eq 'no_host') {
2000: return -1;
2001: }
2002: my $answer=reply("currentversion:$fname",$home);
2003: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2004: return -1;
2005: }
1.599 albertel 2006: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2007: }
2008:
1.1 albertel 2009: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2010:
1.1 albertel 2011: sub subscribe {
2012: my $fname=shift;
1.761 raeburn 2013: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2014: $fname=~s/[\n\r]//g;
1.1 albertel 2015: my $author=$fname;
2016: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2017: my ($udom,$uname)=split(/\//,$author);
2018: my $home=homeserver($uname,$udom);
1.335 albertel 2019: if ($home eq 'no_host') {
2020: return 'not_found';
1.1 albertel 2021: }
2022: my $answer=reply("sub:$fname",$home);
1.64 www 2023: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2024: $answer.=' by '.$home;
2025: }
1.1 albertel 2026: return $answer;
2027: }
2028:
1.8 www 2029: # -------------------------------------------------------------- Replicate file
2030:
2031: sub repcopy {
2032: my $filename=shift;
1.23 www 2033: $filename=~s/\/+/\//g;
1.607 raeburn 2034: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2035: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2036: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2037: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2038: return &repcopy_userfile($filename);
2039: }
1.532 albertel 2040: $filename=~s/[\n\r]//g;
1.8 www 2041: my $transname="$filename.in.transfer";
1.828 www 2042: # FIXME: this should flock
1.607 raeburn 2043: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2044: my $remoteurl=subscribe($filename);
1.64 www 2045: if ($remoteurl =~ /^con_lost by/) {
2046: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2047: return 'unavailable';
1.8 www 2048: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2049: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2050: return 'not_found';
1.64 www 2051: } elsif ($remoteurl =~ /^rejected by/) {
2052: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2053: return 'forbidden';
1.20 www 2054: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2055: return 'ok';
1.8 www 2056: } else {
1.290 www 2057: my $author=$filename;
2058: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2059: my ($udom,$uname)=split(/\//,$author);
2060: my $home=homeserver($uname,$udom);
2061: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2062: my @parts=split(/\//,$filename);
2063: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2064: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2065: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2066: return 'bad_request';
1.8 www 2067: }
2068: my $count;
2069: for ($count=5;$count<$#parts;$count++) {
2070: $path.="/$parts[$count]";
2071: if ((-e $path)!=1) {
2072: mkdir($path,0777);
2073: }
2074: }
2075: my $ua=new LWP::UserAgent;
2076: my $request=new HTTP::Request('GET',"$remoteurl");
2077: my $response=$ua->request($request,$transname);
2078: if ($response->is_error()) {
2079: unlink($transname);
2080: my $message=$response->status_line;
1.672 albertel 2081: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2082: ." LWP get: $message: $filename</font>");
1.607 raeburn 2083: return 'unavailable';
1.8 www 2084: } else {
1.16 www 2085: if ($remoteurl!~/\.meta$/) {
2086: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2087: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2088: if ($mresponse->is_error()) {
2089: unlink($filename.'.meta');
2090: &logthis(
1.672 albertel 2091: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2092: }
2093: }
1.8 www 2094: rename($transname,$filename);
1.607 raeburn 2095: return 'ok';
1.8 www 2096: }
1.290 www 2097: }
1.8 www 2098: }
1.330 www 2099: }
2100:
2101: # ------------------------------------------------ Get server side include body
2102: sub ssi_body {
1.381 albertel 2103: my ($filelink,%form)=@_;
1.606 matthew 2104: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2105: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2106: }
1.953 www 2107: my $output='';
2108: my $response;
1.980 raeburn 2109: if ($filelink=~/^https?\:/) {
1.954 raeburn 2110: ($output,$response)=&externalssi($filelink);
1.953 www 2111: } else {
1.1004 droeschl 2112: $filelink .= $filelink=~/\?/ ? '&' : '?';
2113: $filelink .= 'inhibitmenu=yes';
1.953 www 2114: ($output,$response)=&ssi($filelink,%form);
2115: }
1.778 albertel 2116: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2117: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2118: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2119: if (wantarray) {
2120: return ($output, $response);
2121: } else {
2122: return $output;
2123: }
1.8 www 2124: }
2125:
1.15 www 2126: # --------------------------------------------------------- Server Side Include
2127:
1.782 albertel 2128: sub absolute_url {
2129: my ($host_name) = @_;
2130: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2131: if ($host_name eq '') {
2132: $host_name = $ENV{'SERVER_NAME'};
2133: }
2134: return $protocol.$host_name;
2135: }
2136:
1.942 foxr 2137: #
2138: # Server side include.
2139: # Parameters:
2140: # fn Possibly encrypted resource name/id.
2141: # form Hash that describes how the rendering should be done
2142: # and other things.
1.944 foxr 2143: # Returns:
1.950 raeburn 2144: # Scalar context: The content of the response.
2145: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2146: #
1.15 www 2147: sub ssi {
2148:
1.944 foxr 2149: my ($fn,%form)=@_;
1.15 www 2150: my $ua=new LWP::UserAgent;
1.23 www 2151: my $request;
1.711 albertel 2152:
2153: $form{'no_update_last_known'}=1;
1.895 albertel 2154: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2155: if (%form) {
1.782 albertel 2156: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2157: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2158: } else {
1.782 albertel 2159: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2160: }
2161:
1.15 www 2162: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2163: my $response=$ua->request($request);
2164:
1.944 foxr 2165: if (wantarray) {
2166: return ($response->content, $response);
2167: } else {
2168: return $response->content;
1.942 foxr 2169: }
1.324 www 2170: }
2171:
2172: sub externalssi {
2173: my ($url)=@_;
2174: my $ua=new LWP::UserAgent;
2175: my $request=new HTTP::Request('GET',$url);
2176: my $response=$ua->request($request);
1.954 raeburn 2177: if (wantarray) {
2178: return ($response->content, $response);
2179: } else {
2180: return $response->content;
2181: }
1.15 www 2182: }
1.254 www 2183:
1.492 albertel 2184: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2185:
2186: sub allowuploaded {
2187: my ($srcurl,$url)=@_;
2188: $url=&clutter(&declutter($url));
2189: my $dir=$url;
2190: $dir=~s/\/[^\/]+$//;
2191: my %httpref=();
2192: my $httpurl=&hreflocation('',$url);
2193: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2194: &Apache::lonnet::appenv(\%httpref);
1.254 www 2195: }
1.477 raeburn 2196:
1.478 albertel 2197: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2198: # input: action, courseID, current domain, intended
1.637 raeburn 2199: # path to file, source of file, instruction to parse file for objects,
2200: # ref to hash for embedded objects,
2201: # ref to hash for codebase of java objects.
2202: #
1.485 raeburn 2203: # output: url to file (if action was uploaddoc),
2204: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2205: #
1.478 albertel 2206: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2207: # course.
1.477 raeburn 2208: #
1.478 albertel 2209: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2210: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2211: # course's home server.
1.477 raeburn 2212: #
1.478 albertel 2213: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2214: # be copied from $source (current location) to
2215: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2216: # and will then be copied to
2217: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2218: # course's home server.
1.485 raeburn 2219: #
1.481 raeburn 2220: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2221: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2222: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2223: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2224: # in course's home server.
1.637 raeburn 2225: #
1.477 raeburn 2226:
2227: sub process_coursefile {
1.638 albertel 2228: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2229: my $fetchresult;
1.638 albertel 2230: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2231: if ($action eq 'propagate') {
1.638 albertel 2232: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2233: $home);
1.481 raeburn 2234: } else {
1.477 raeburn 2235: my $fpath = '';
2236: my $fname = $file;
1.478 albertel 2237: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2238: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2239: my $filepath = &build_filepath($fpath);
1.481 raeburn 2240: if ($action eq 'copy') {
2241: if ($source eq '') {
2242: $fetchresult = 'no source file';
2243: return $fetchresult;
2244: } else {
2245: my $destination = $filepath.'/'.$fname;
2246: rename($source,$destination);
2247: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2248: $home);
1.481 raeburn 2249: }
2250: } elsif ($action eq 'uploaddoc') {
2251: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2252: print $fh $env{'form.'.$source};
1.481 raeburn 2253: close($fh);
1.637 raeburn 2254: if ($parser eq 'parse') {
1.1024 raeburn 2255: my $mm = new File::MMagic;
2256: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2257: if ($mime_type eq 'text/html') {
2258: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2259: unless ($parse_result eq 'ok') {
2260: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2261: }
1.637 raeburn 2262: }
2263: }
1.477 raeburn 2264: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2265: $home);
1.481 raeburn 2266: if ($fetchresult eq 'ok') {
2267: return '/uploaded/'.$fpath.'/'.$fname;
2268: } else {
2269: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2270: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2271: return '/adm/notfound.html';
2272: }
1.477 raeburn 2273: }
2274: }
1.485 raeburn 2275: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2276: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2277: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2278: }
2279: return $fetchresult;
2280: }
2281:
1.637 raeburn 2282: sub build_filepath {
2283: my ($fpath) = @_;
2284: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2285: unless ($fpath eq '') {
2286: my @parts=split('/',$fpath);
2287: foreach my $part (@parts) {
2288: $filepath.= '/'.$part;
2289: if ((-e $filepath)!=1) {
2290: mkdir($filepath,0777);
2291: }
2292: }
2293: }
2294: return $filepath;
2295: }
2296:
2297: sub store_edited_file {
1.638 albertel 2298: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2299: my $file = $primary_url;
2300: $file =~ s#^/uploaded/$docudom/$docuname/##;
2301: my $fpath = '';
2302: my $fname = $file;
2303: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2304: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2305: my $filepath = &build_filepath($fpath);
2306: open(my $fh,'>'.$filepath.'/'.$fname);
2307: print $fh $content;
2308: close($fh);
1.638 albertel 2309: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2310: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2311: $home);
1.637 raeburn 2312: if ($$fetchresult eq 'ok') {
2313: return '/uploaded/'.$fpath.'/'.$fname;
2314: } else {
1.638 albertel 2315: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2316: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2317: return '/adm/notfound.html';
2318: }
2319: }
2320:
1.531 albertel 2321: sub clean_filename {
1.831 albertel 2322: my ($fname,$args)=@_;
1.315 www 2323: # Replace Windows backslashes by forward slashes
1.257 www 2324: $fname=~s/\\/\//g;
1.831 albertel 2325: if (!$args->{'keep_path'}) {
2326: # Get rid of everything but the actual filename
2327: $fname=~s/^.*\/([^\/]+)$/$1/;
2328: }
1.315 www 2329: # Replace spaces by underscores
2330: $fname=~s/\s+/\_/g;
2331: # Replace all other weird characters by nothing
1.831 albertel 2332: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2333: # Replace all .\d. sequences with _\d. so they no longer look like version
2334: # numbers
2335: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2336: return $fname;
2337: }
1.1051 raeburn 2338: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2339: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2340: # image with the same aspect ratio as the original, but with dimensions which do
2341: # not exceed $resizewidth and $resizeheight.
2342:
1.984 neumanie 2343: sub resizeImage {
1.1051 raeburn 2344: my ($img_path,$resizewidth,$resizeheight) = @_;
2345: my $ima = Image::Magick->new;
2346: my $resized;
2347: if (-e $img_path) {
2348: $ima->Read($img_path);
2349: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2350: my $width = $ima->Get('width');
2351: my $height = $ima->Get('height');
2352: if ($width > $resizewidth) {
2353: my $factor = $width/$resizewidth;
2354: my $newheight = $height/$factor;
2355: $ima->Scale(width=>$resizewidth,height=>$newheight);
2356: $resized = 1;
2357: }
2358: }
2359: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2360: my $width = $ima->Get('width');
2361: my $height = $ima->Get('height');
2362: if ($height > $resizeheight) {
2363: my $factor = $height/$resizeheight;
2364: my $newwidth = $width/$factor;
2365: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2366: $resized = 1;
2367: }
2368: }
2369: if ($resized) {
2370: $ima->Write($img_path);
2371: }
2372: }
2373: return;
1.977 amueller 2374: }
2375:
1.608 albertel 2376: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2377: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2378: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2379: # $coursedoc - if true up to the current course
2380: # if false
2381: # $subdir - directory in userfile to store the file into
1.858 raeburn 2382: # $parser - instruction to parse file for objects ($parser = parse)
2383: # $allfiles - reference to hash for embedded objects
2384: # $codebase - reference to hash for codebase of java objects
2385: # $desuname - username for permanent storage of uploaded file
2386: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2387: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2388: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2389: # $resizewidth - width (pixels) to which to resize uploaded image
2390: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2391: #
1.686 albertel 2392: # output: url of file in userspace, or error: <message>
2393: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2394:
1.531 albertel 2395: sub userfileupload {
1.860 raeburn 2396: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2397: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2398: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2399: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2400: $fname=&clean_filename($fname);
1.315 www 2401: # See if there is anything left
1.257 www 2402: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2403: chop($env{'form.'.$formname});
1.523 raeburn 2404: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2405: my $now = time;
2406: my $filepath = 'tmp/helprequests/'.$now;
2407: my @parts=split(/\//,$filepath);
2408: my $fullpath = $perlvar{'lonDaemons'};
2409: for (my $i=0;$i<@parts;$i++) {
2410: $fullpath .= '/'.$parts[$i];
2411: if ((-e $fullpath)!=1) {
2412: mkdir($fullpath,0777);
2413: }
2414: }
2415: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2416: print $fh $env{'form.'.$formname};
1.523 raeburn 2417: close($fh);
1.741 raeburn 2418: return $fullpath.'/'.$fname;
2419: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2420: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2421: '_'.$env{'user.domain'}.'/pending';
2422: my @parts=split(/\//,$filepath);
2423: my $fullpath = $perlvar{'lonDaemons'};
2424: for (my $i=0;$i<@parts;$i++) {
2425: $fullpath .= '/'.$parts[$i];
2426: if ((-e $fullpath)!=1) {
2427: mkdir($fullpath,0777);
2428: }
2429: }
2430: open(my $fh,'>'.$fullpath.'/'.$fname);
2431: print $fh $env{'form.'.$formname};
2432: close($fh);
2433: return $fullpath.'/'.$fname;
1.523 raeburn 2434: }
1.995 raeburn 2435: if ($subdir eq 'scantron') {
2436: $fname = 'scantron_orig_'.$fname;
2437: } else {
1.258 www 2438: # Create the directory if not present
1.995 raeburn 2439: $fname="$subdir/$fname";
2440: }
1.259 www 2441: if ($coursedoc) {
1.638 albertel 2442: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2443: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2444: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2445: return &finishuserfileupload($docuname,$docudom,
2446: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2447: $codebase,$thumbwidth,$thumbheight,
2448: $resizewidth,$resizeheight);
1.481 raeburn 2449: } else {
1.620 albertel 2450: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2451: return &process_coursefile('uploaddoc',$docuname,$docudom,
2452: $fname,$formname,$parser,
2453: $allfiles,$codebase);
1.481 raeburn 2454: }
1.719 banghart 2455: } elsif (defined($destuname)) {
2456: my $docuname=$destuname;
2457: my $docudom=$destudom;
1.860 raeburn 2458: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2459: $parser,$allfiles,$codebase,
1.1051 raeburn 2460: $thumbwidth,$thumbheight,
2461: $resizewidth,$resizeheight);
1.719 banghart 2462:
1.259 www 2463: } else {
1.638 albertel 2464: my $docuname=$env{'user.name'};
2465: my $docudom=$env{'user.domain'};
1.714 raeburn 2466: if (exists($env{'form.group'})) {
2467: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2468: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2469: }
1.860 raeburn 2470: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2471: $parser,$allfiles,$codebase,
1.1051 raeburn 2472: $thumbwidth,$thumbheight,
2473: $resizewidth,$resizeheight);
1.259 www 2474: }
1.271 www 2475: }
2476:
2477: sub finishuserfileupload {
1.860 raeburn 2478: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2479: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2480: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2481: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2482:
1.860 raeburn 2483: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2484: $file=$fname;
2485: if ($fname=~m|/|) {
2486: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2487: $path.=$fnamepath.'/';
2488: }
1.259 www 2489: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2490: my $count;
2491: for ($count=4;$count<=$#parts;$count++) {
2492: $filepath.="/$parts[$count]";
2493: if ((-e $filepath)!=1) {
2494: mkdir($filepath,0777);
2495: }
2496: }
1.984 neumanie 2497:
1.258 www 2498: # Save the file
2499: {
1.701 albertel 2500: if (!open(FH,'>'.$filepath.'/'.$file)) {
2501: &logthis('Failed to create '.$filepath.'/'.$file);
2502: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2503: return '/adm/notfound.html';
2504: }
2505: if (!print FH ($env{'form.'.$formname})) {
2506: &logthis('Failed to write to '.$filepath.'/'.$file);
2507: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2508: return '/adm/notfound.html';
2509: }
1.570 albertel 2510: close(FH);
1.1051 raeburn 2511: if ($resizewidth && $resizeheight) {
2512: my $mm = new File::MMagic;
2513: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2514: if ($mime_type =~ m{^image/}) {
2515: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2516: }
1.977 amueller 2517: }
1.258 www 2518: }
1.637 raeburn 2519: if ($parser eq 'parse') {
1.1024 raeburn 2520: my $mm = new File::MMagic;
2521: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2522: if ($mime_type eq 'text/html') {
2523: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2524: $allfiles,$codebase);
2525: unless ($parse_result eq 'ok') {
2526: &logthis('Failed to parse '.$filepath.$file.
2527: ' for embedded media: '.$parse_result);
2528: }
1.637 raeburn 2529: }
2530: }
1.860 raeburn 2531: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2532: my $input = $filepath.'/'.$file;
2533: my $output = $filepath.'/'.'tn-'.$file;
2534: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2535: system("convert -sample $thumbsize $input $output");
2536: if (-e $filepath.'/'.'tn-'.$file) {
2537: $fetchthumb = 1;
2538: }
2539: }
1.858 raeburn 2540:
1.259 www 2541: # Notify homeserver to grep it
2542: #
1.984 neumanie 2543: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2544: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2545: if ($fetchresult eq 'ok') {
1.860 raeburn 2546: if ($fetchthumb) {
2547: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2548: if ($thumbresult ne 'ok') {
2549: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2550: $docuhome.': '.$thumbresult);
2551: }
2552: }
1.259 www 2553: #
1.258 www 2554: # Return the URL to it
1.494 albertel 2555: return '/uploaded/'.$path.$file;
1.263 www 2556: } else {
1.494 albertel 2557: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2558: ': '.$fetchresult);
1.263 www 2559: return '/adm/notfound.html';
1.858 raeburn 2560: }
1.493 albertel 2561: }
2562:
1.637 raeburn 2563: sub extract_embedded_items {
1.961 raeburn 2564: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2565: my @state = ();
2566: my %javafiles = (
2567: codebase => '',
2568: code => '',
2569: archive => ''
2570: );
2571: my %mediafiles = (
2572: src => '',
2573: movie => '',
2574: );
1.648 raeburn 2575: my $p;
2576: if ($content) {
2577: $p = HTML::LCParser->new($content);
2578: } else {
1.961 raeburn 2579: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2580: }
1.641 albertel 2581: while (my $t=$p->get_token()) {
1.640 albertel 2582: if ($t->[0] eq 'S') {
2583: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2584: push(@state, $tagname);
1.648 raeburn 2585: if (lc($tagname) eq 'allow') {
2586: &add_filetype($allfiles,$attr->{'src'},'src');
2587: }
1.640 albertel 2588: if (lc($tagname) eq 'img') {
2589: &add_filetype($allfiles,$attr->{'src'},'src');
2590: }
1.886 albertel 2591: if (lc($tagname) eq 'a') {
2592: &add_filetype($allfiles,$attr->{'href'},'href');
2593: }
1.645 raeburn 2594: if (lc($tagname) eq 'script') {
2595: if ($attr->{'archive'} =~ /\.jar$/i) {
2596: &add_filetype($allfiles,$attr->{'archive'},'archive');
2597: } else {
2598: &add_filetype($allfiles,$attr->{'src'},'src');
2599: }
2600: }
2601: if (lc($tagname) eq 'link') {
2602: if (lc($attr->{'rel'}) eq 'stylesheet') {
2603: &add_filetype($allfiles,$attr->{'href'},'href');
2604: }
2605: }
1.640 albertel 2606: if (lc($tagname) eq 'object' ||
2607: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2608: foreach my $item (keys(%javafiles)) {
2609: $javafiles{$item} = '';
2610: }
2611: }
2612: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2613: my $name = lc($attr->{'name'});
2614: foreach my $item (keys(%javafiles)) {
2615: if ($name eq $item) {
2616: $javafiles{$item} = $attr->{'value'};
2617: last;
2618: }
2619: }
2620: foreach my $item (keys(%mediafiles)) {
2621: if ($name eq $item) {
2622: &add_filetype($allfiles, $attr->{'value'}, 'value');
2623: last;
2624: }
2625: }
2626: }
2627: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2628: foreach my $item (keys(%javafiles)) {
2629: if ($attr->{$item}) {
2630: $javafiles{$item} = $attr->{$item};
2631: last;
2632: }
2633: }
2634: foreach my $item (keys(%mediafiles)) {
2635: if ($attr->{$item}) {
2636: &add_filetype($allfiles,$attr->{$item},$item);
2637: last;
2638: }
2639: }
2640: }
2641: } elsif ($t->[0] eq 'E') {
2642: my ($tagname) = ($t->[1]);
2643: if ($javafiles{'codebase'} ne '') {
2644: $javafiles{'codebase'} .= '/';
2645: }
2646: if (lc($tagname) eq 'applet' ||
2647: lc($tagname) eq 'object' ||
2648: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2649: ) {
2650: foreach my $item (keys(%javafiles)) {
2651: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2652: my $file=$javafiles{'codebase'}.$javafiles{$item};
2653: &add_filetype($allfiles,$file,$item);
2654: }
2655: }
2656: }
2657: pop @state;
2658: }
2659: }
1.637 raeburn 2660: return 'ok';
2661: }
2662:
1.639 albertel 2663: sub add_filetype {
2664: my ($allfiles,$file,$type)=@_;
2665: if (exists($allfiles->{$file})) {
2666: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2667: push(@{$allfiles->{$file}}, &escape($type));
2668: }
2669: } else {
2670: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2671: }
2672: }
2673:
1.493 albertel 2674: sub removeuploadedurl {
1.984 neumanie 2675: my ($url)=@_;
2676: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2677: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2678: }
2679:
2680: sub removeuserfile {
2681: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2682: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2683: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2684: if ($result eq 'ok') {
1.798 raeburn 2685: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2686: my $metafile = $fname.'.meta';
2687: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2688: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2689: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2690: my $sqlresult =
1.823 albertel 2691: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2692: 'portfolio_metadata',$group,
2693: 'delete');
1.798 raeburn 2694: }
2695: }
2696: return $result;
1.257 www 2697: }
1.15 www 2698:
1.530 albertel 2699: sub mkdiruserfile {
2700: my ($docuname,$docudom,$dir)=@_;
2701: my $home=&homeserver($docuname,$docudom);
2702: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2703: }
2704:
1.531 albertel 2705: sub renameuserfile {
2706: my ($docuname,$docudom,$old,$new)=@_;
2707: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2708: my $result = &reply("renameuserfile:$docudom:$docuname:".
2709: &escape("$old").':'.&escape("$new"),$home);
2710: if ($result eq 'ok') {
2711: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2712: my $oldmeta = $old.'.meta';
2713: my $newmeta = $new.'.meta';
2714: my $metaresult =
2715: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2716: my $url = "/uploaded/$docudom/$docuname/$old";
2717: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2718: my $sqlresult =
1.823 albertel 2719: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2720: 'portfolio_metadata',$group,
2721: 'delete');
1.798 raeburn 2722: }
2723: }
2724: return $result;
1.531 albertel 2725: }
2726:
1.14 www 2727: # ------------------------------------------------------------------------- Log
2728:
2729: sub log {
2730: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2731: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2732: }
2733:
2734: # ------------------------------------------------------------------ Course Log
1.352 www 2735: #
2736: # This routine flushes several buffers of non-mission-critical nature
2737: #
1.157 www 2738:
2739: sub flushcourselogs {
1.352 www 2740: &logthis('Flushing log buffers');
2741: #
2742: # course logs
2743: # This is a log of all transactions in a course, which can be used
2744: # for data mining purposes
2745: #
2746: # It also collects the courseid database, which lists last transaction
2747: # times and course titles for all courseids
2748: #
2749: my %courseidbuffer=();
1.921 raeburn 2750: foreach my $crsid (keys(%courselogs)) {
1.352 www 2751: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2752: &escape($courselogs{$crsid}),
2753: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2754: delete $courselogs{$crsid};
2755: } else {
2756: &logthis('Failed to flush log buffer for '.$crsid);
2757: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2758: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2759: " exceeded maximum size, deleting.</font>");
2760: delete $courselogs{$crsid};
2761: }
1.352 www 2762: }
1.920 raeburn 2763: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2764: 'description' => $coursedescrbuf{$crsid},
2765: 'inst_code' => $courseinstcodebuf{$crsid},
2766: 'type' => $coursetypebuf{$crsid},
2767: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2768: };
1.191 harris41 2769: }
1.352 www 2770: #
2771: # Write course id database (reverse lookup) to homeserver of courses
2772: # Is used in pickcourse
2773: #
1.840 albertel 2774: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2775: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2776: $courseidbuffer{$crs_home},
2777: $crs_home,'timeonly');
1.352 www 2778: }
2779: #
2780: # File accesses
2781: # Writes to the dynamic metadata of resources to get hit counts, etc.
2782: #
1.449 matthew 2783: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2784: if ($entry =~ /___count$/) {
2785: my ($dom,$name);
1.807 albertel 2786: ($dom,$name,undef)=
1.811 albertel 2787: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2788: if (! defined($dom) || $dom eq '' ||
2789: ! defined($name) || $name eq '') {
1.620 albertel 2790: my $cid = $env{'request.course.id'};
2791: $dom = $env{'request.'.$cid.'.domain'};
2792: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2793: }
1.450 matthew 2794: my $value = $accesshash{$entry};
2795: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2796: my %temphash=($url => $value);
1.449 matthew 2797: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2798: if ($result eq 'ok') {
2799: delete $accesshash{$entry};
2800: } elsif ($result eq 'unknown_cmd') {
2801: # Target server has old code running on it.
1.450 matthew 2802: my %temphash=($entry => $value);
1.449 matthew 2803: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2804: delete $accesshash{$entry};
2805: }
2806: }
2807: } else {
1.811 albertel 2808: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2809: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2810: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2811: delete $accesshash{$entry};
2812: }
1.185 www 2813: }
1.191 harris41 2814: }
1.352 www 2815: #
2816: # Roles
2817: # Reverse lookup of user roles for course faculty/staff and co-authorship
2818: #
1.800 albertel 2819: foreach my $entry (keys(%userrolehash)) {
1.351 www 2820: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2821: split(/\:/,$entry);
2822: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2823: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2824: $rudom,$runame) eq 'ok') {
2825: delete $userrolehash{$entry};
2826: }
2827: }
1.662 raeburn 2828: #
2829: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2830: #
2831: my %domrolebuffer = ();
1.1000 raeburn 2832: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2833: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2834: if ($domrolebuffer{$rudom}) {
2835: $domrolebuffer{$rudom}.='&'.&escape($entry).
2836: '='.&escape($domainrolehash{$entry});
2837: } else {
2838: $domrolebuffer{$rudom}.=&escape($entry).
2839: '='.&escape($domainrolehash{$entry});
2840: }
2841: delete $domainrolehash{$entry};
2842: }
2843: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2844: my %servers = &get_servers($dom,'library');
2845: foreach my $tryserver (keys(%servers)) {
2846: unless (&reply('domroleput:'.$dom.':'.
2847: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2848: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2849: }
1.662 raeburn 2850: }
2851: }
1.186 www 2852: $dumpcount++;
1.157 www 2853: }
2854:
2855: sub courselog {
2856: my $what=shift;
1.158 www 2857: $what=time.':'.$what;
1.620 albertel 2858: unless ($env{'request.course.id'}) { return ''; }
2859: $coursedombuf{$env{'request.course.id'}}=
2860: $env{'course.'.$env{'request.course.id'}.'.domain'};
2861: $coursenumbuf{$env{'request.course.id'}}=
2862: $env{'course.'.$env{'request.course.id'}.'.num'};
2863: $coursehombuf{$env{'request.course.id'}}=
2864: $env{'course.'.$env{'request.course.id'}.'.home'};
2865: $coursedescrbuf{$env{'request.course.id'}}=
2866: $env{'course.'.$env{'request.course.id'}.'.description'};
2867: $courseinstcodebuf{$env{'request.course.id'}}=
2868: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2869: $courseownerbuf{$env{'request.course.id'}}=
2870: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2871: $coursetypebuf{$env{'request.course.id'}}=
2872: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2873: if (defined $courselogs{$env{'request.course.id'}}) {
2874: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2875: } else {
1.620 albertel 2876: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2877: }
1.620 albertel 2878: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2879: &flushcourselogs();
2880: }
1.158 www 2881: }
2882:
2883: sub courseacclog {
2884: my $fnsymb=shift;
1.620 albertel 2885: unless ($env{'request.course.id'}) { return ''; }
2886: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2887: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2888: $what.=':POST';
1.583 matthew 2889: # FIXME: Probably ought to escape things....
1.800 albertel 2890: foreach my $key (keys(%env)) {
2891: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2892: my $formitem = $1;
2893: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2894: $what.=':'.$formitem.'='.$env{$key};
2895: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2896: $what.=':'.$formitem.'='.$env{$key};
2897: }
1.158 www 2898: }
1.191 harris41 2899: }
1.583 matthew 2900: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2901: # FIXME: We should not be depending on a form parameter that someone
2902: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2903: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2904: $what.= ':POST';
2905: # FIXME: Probably ought to escape things....
2906: foreach my $element ('courseexp','crsfulltext','crsrelated',
2907: 'crsdiscuss') {
1.620 albertel 2908: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2909: }
2910: }
1.158 www 2911: }
2912: &courselog($what);
1.149 www 2913: }
2914:
1.185 www 2915: sub countacc {
2916: my $url=&declutter(shift);
1.458 matthew 2917: return if (! defined($url) || $url eq '');
1.620 albertel 2918: unless ($env{'request.course.id'}) { return ''; }
2919: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2920: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2921: $accesshash{$key}++;
1.185 www 2922: }
1.349 www 2923:
1.361 www 2924: sub linklog {
2925: my ($from,$to)=@_;
2926: $from=&declutter($from);
2927: $to=&declutter($to);
2928: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2929: $accesshash{$to.'___'.$from.'___goto'}=1;
2930: }
2931:
1.349 www 2932: sub userrolelog {
2933: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2934: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2935: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2936: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2937: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2938: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2939: $userrolehash
2940: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2941: =$tend.':'.$tstart;
1.662 raeburn 2942: }
1.898 albertel 2943: if (($env{'request.role'} =~ /dc\./) &&
2944: (($trole=~/^au/) || ($trole=~/^in/) ||
2945: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2946: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2947: ($trole=~/^co/))) {
1.898 albertel 2948: $userrolehash
2949: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2950: =$tend.':'.$tstart;
2951: }
1.662 raeburn 2952: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2953: ($trole=~/^li/) || ($trole=~/^li/) ||
2954: ($trole=~/^au/) || ($trole=~/^dg/) ||
2955: ($trole=~/^sc/)) {
2956: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2957: $domainrolehash
2958: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2959: = $tend.':'.$tstart;
2960: }
1.351 www 2961: }
2962:
1.957 raeburn 2963: sub courserolelog {
2964: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2965: if (($trole eq 'cc') || ($trole eq 'in') ||
2966: ($trole eq 'ep') || ($trole eq 'ad') ||
2967: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2968: ($trole=~/^cr/) || ($trole eq 'gr') ||
2969: ($trole eq 'co')) {
1.957 raeburn 2970: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2971: my $cdom = $1;
2972: my $cnum = $2;
2973: my $sec = $3;
2974: my $namespace = 'rolelog';
2975: my %storehash = (
2976: role => $trole,
2977: start => $tstart,
2978: end => $tend,
2979: selfenroll => $selfenroll,
2980: context => $context,
2981: );
2982: if ($trole eq 'gr') {
2983: $namespace = 'groupslog';
2984: $storehash{'group'} = $sec;
2985: } else {
2986: $storehash{'section'} = $sec;
2987: }
2988: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2989: if (($trole ne 'st') || ($sec ne '')) {
2990: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2991: }
1.957 raeburn 2992: }
2993: }
2994: return;
2995: }
2996:
1.351 www 2997: sub get_course_adv_roles {
1.948 raeburn 2998: my ($cid,$codes) = @_;
1.620 albertel 2999: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3000: my %coursehash=&coursedescription($cid);
1.988 raeburn 3001: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3002: my %nothide=();
1.800 albertel 3003: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3004: if ($user !~ /:/) {
3005: $nothide{join(':',split(/[\@]/,$user))}=1;
3006: } else {
3007: $nothide{$user}=1;
3008: }
1.470 www 3009: }
1.351 www 3010: my %returnhash=();
3011: my %dumphash=
3012: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3013: my $now=time;
1.997 raeburn 3014: my %privileged;
1.1000 raeburn 3015: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3016: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3017: if (($tstart) && ($tstart<0)) { next; }
3018: if (($tend) && ($tend<$now)) { next; }
3019: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3020: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3021: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3022: unless (ref($privileged{$domain}) eq 'HASH') {
3023: my %dompersonnel =
1.998 raeburn 3024: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3025: $privileged{$domain} = {};
3026: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3027: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3028: foreach my $user (keys(%{$dompersonnel{$server}})) {
3029: my ($trole,$uname,$udom) = split(/:/,$user);
3030: $privileged{$udom}{$uname} = 1;
3031: }
3032: }
3033: }
3034: }
3035: if ((exists($privileged{$domain}{$username})) &&
3036: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3037: if ($role eq 'cr') { next; }
1.948 raeburn 3038: if ($codes) {
3039: if ($section) { $role .= ':'.$section; }
3040: if ($returnhash{$role}) {
3041: $returnhash{$role}.=','.$username.':'.$domain;
3042: } else {
3043: $returnhash{$role}=$username.':'.$domain;
3044: }
1.351 www 3045: } else {
1.988 raeburn 3046: my $key=&plaintext($role,$crstype);
1.973 bisitz 3047: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3048: if ($returnhash{$key}) {
3049: $returnhash{$key}.=','.$username.':'.$domain;
3050: } else {
3051: $returnhash{$key}=$username.':'.$domain;
3052: }
1.351 www 3053: }
1.948 raeburn 3054: }
1.400 www 3055: return %returnhash;
3056: }
3057:
3058: sub get_my_roles {
1.937 raeburn 3059: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3060: unless (defined($uname)) { $uname=$env{'user.name'}; }
3061: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3062: my (%dumphash,%nothide);
1.858 raeburn 3063: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3064: my $extra = &freeze_escape({'skipcheck' => 1});
3065: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3066: } else {
3067: %dumphash=
1.400 www 3068: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3069: if ($hidepriv) {
3070: my %coursehash=&coursedescription($udom.'_'.$uname);
3071: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3072: if ($user !~ /:/) {
3073: $nothide{join(':',split(/[\@]/,$user))} = 1;
3074: } else {
3075: $nothide{$user} = 1;
3076: }
3077: }
3078: }
1.858 raeburn 3079: }
1.400 www 3080: my %returnhash=();
3081: my $now=time;
1.999 raeburn 3082: my %privileged;
1.800 albertel 3083: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3084: my ($role,$tend,$tstart);
3085: if ($context eq 'userroles') {
3086: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3087: } else {
3088: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3089: }
1.400 www 3090: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3091: my $status = 'active';
1.939 raeburn 3092: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3093: $status = 'previous';
3094: }
3095: if (($tstart) && ($now<$tstart)) {
3096: $status = 'future';
3097: }
3098: if (ref($types) eq 'ARRAY') {
3099: if (!grep(/^\Q$status\E$/,@{$types})) {
3100: next;
3101: }
3102: } else {
3103: if ($status ne 'active') {
3104: next;
3105: }
3106: }
1.867 raeburn 3107: my ($rolecode,$username,$domain,$section,$area);
3108: if ($context eq 'userroles') {
3109: ($area,$rolecode) = split(/_/,$entry);
3110: (undef,$domain,$username,$section) = split(/\//,$area);
3111: } else {
3112: ($role,$username,$domain,$section) = split(/\:/,$entry);
3113: }
1.832 raeburn 3114: if (ref($roledoms) eq 'ARRAY') {
3115: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3116: next;
3117: }
3118: }
3119: if (ref($roles) eq 'ARRAY') {
3120: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3121: if ($role =~ /^cr\//) {
3122: if (!grep(/^cr$/,@{$roles})) {
3123: next;
3124: }
3125: } else {
3126: next;
3127: }
1.832 raeburn 3128: }
1.867 raeburn 3129: }
1.937 raeburn 3130: if ($hidepriv) {
1.999 raeburn 3131: if ($context eq 'userroles') {
3132: if ((&privileged($username,$domain)) &&
3133: (!$nothide{$username.':'.$domain})) {
3134: next;
3135: }
3136: } else {
3137: unless (ref($privileged{$domain}) eq 'HASH') {
3138: my %dompersonnel =
3139: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3140: $privileged{$domain} = {};
3141: if (keys(%dompersonnel)) {
3142: foreach my $server (keys(%dompersonnel)) {
3143: if (ref($dompersonnel{$server}) eq 'HASH') {
3144: foreach my $user (keys(%{$dompersonnel{$server}})) {
3145: my ($trole,$uname,$udom) = split(/:/,$user);
3146: $privileged{$udom}{$uname} = $trole;
3147: }
3148: }
3149: }
3150: }
3151: }
3152: if (exists($privileged{$domain}{$username})) {
3153: if (!$nothide{$username.':'.$domain}) {
3154: next;
3155: }
3156: }
1.937 raeburn 3157: }
3158: }
1.933 raeburn 3159: if ($withsec) {
3160: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3161: $tstart.':'.$tend;
3162: } else {
3163: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3164: }
1.832 raeburn 3165: }
1.373 www 3166: return %returnhash;
1.399 www 3167: }
3168:
3169: # ----------------------------------------------------- Frontpage Announcements
3170: #
3171: #
3172:
3173: sub postannounce {
3174: my ($server,$text)=@_;
1.844 albertel 3175: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3176: unless ($text=~/\w/) { $text=''; }
3177: return &reply('setannounce:'.&escape($text),$server);
3178: }
3179:
3180: sub getannounce {
1.448 albertel 3181:
3182: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3183: my $announcement='';
1.800 albertel 3184: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3185: close($fh);
1.399 www 3186: if ($announcement=~/\w/) {
3187: return
3188: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3189: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3190: } else {
3191: return '';
3192: }
3193: } else {
3194: return '';
3195: }
1.351 www 3196: }
1.353 www 3197:
3198: # ---------------------------------------------------------- Course ID routines
3199: # Deal with domain's nohist_courseid.db files
3200: #
3201:
3202: sub courseidput {
1.921 raeburn 3203: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3204: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3205: my $outcome;
3206: if ($caller eq 'timeonly') {
3207: my $cids = '';
3208: foreach my $item (keys(%$storehash)) {
3209: $cids.=&escape($item).'&';
3210: }
3211: $cids=~s/\&$//;
3212: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3213: $coursehome);
3214: } else {
3215: my $items = '';
3216: foreach my $item (keys(%$storehash)) {
3217: $items.= &escape($item).'='.
3218: &freeze_escape($$storehash{$item}).'&';
3219: }
3220: $items=~s/\&$//;
3221: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3222: $coursehome);
1.918 raeburn 3223: }
3224: if ($outcome eq 'unknown_cmd') {
3225: my $what;
3226: foreach my $cid (keys(%$storehash)) {
3227: $what .= &escape($cid).'=';
1.921 raeburn 3228: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3229: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3230: }
3231: $what =~ s/\:$/&/;
3232: }
3233: $what =~ s/\&$//;
3234: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3235: } else {
3236: return $outcome;
3237: }
1.353 www 3238: }
3239:
3240: sub courseiddump {
1.921 raeburn 3241: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3242: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3243: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3244: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3245: my $as_hash = 1;
3246: my %returnhash;
3247: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3248: my %libserv = &all_library();
3249: foreach my $tryserver (keys(%libserv)) {
3250: if ( ( $hostidflag == 1
3251: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3252: || (!defined($hostidflag)) ) {
3253:
1.918 raeburn 3254: if (($domfilter eq '') ||
3255: (&host_domain($tryserver) eq $domfilter)) {
3256: my $rep =
3257: &reply('courseiddump:'.&host_domain($tryserver).':'.
3258: $sincefilter.':'.&escape($descfilter).':'.
3259: &escape($instcodefilter).':'.&escape($ownerfilter).
3260: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3261: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3262: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3263: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3264: &escape($cc_clone).':'.$cloneonly.':'.
3265: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3266: &escape($creationcontext).':'.$domcloner,
3267: $tryserver);
1.918 raeburn 3268: my @pairs=split(/\&/,$rep);
3269: foreach my $item (@pairs) {
3270: my ($key,$value)=split(/\=/,$item,2);
3271: $key = &unescape($key);
3272: next if ($key =~ /^error: 2 /);
3273: my $result = &thaw_unescape($value);
3274: if (ref($result) eq 'HASH') {
3275: $returnhash{$key}=$result;
3276: } else {
1.921 raeburn 3277: my @responses = split(/:/,$value);
3278: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3279: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3280: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3281: }
1.1008 raeburn 3282: }
1.353 www 3283: }
3284: }
3285: }
3286: }
3287: return %returnhash;
3288: }
3289:
1.1055 raeburn 3290: sub courselastaccess {
3291: my ($cdom,$cnum,$hostidref) = @_;
3292: my %returnhash;
3293: if ($cdom && $cnum) {
3294: my $chome = &homeserver($cnum,$cdom);
3295: if ($chome ne 'no_host') {
3296: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3297: &extract_lastaccess(\%returnhash,$rep);
3298: }
3299: } else {
3300: if (!$cdom) { $cdom=''; }
3301: my %libserv = &all_library();
3302: foreach my $tryserver (keys(%libserv)) {
3303: if (ref($hostidref) eq 'ARRAY') {
3304: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3305: }
3306: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3307: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3308: &extract_lastaccess(\%returnhash,$rep);
3309: }
3310: }
3311: }
3312: return %returnhash;
3313: }
3314:
3315: sub extract_lastaccess {
3316: my ($returnhash,$rep) = @_;
3317: if (ref($returnhash) eq 'HASH') {
3318: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3319: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3320: $rep eq '') {
3321: my @pairs=split(/\&/,$rep);
3322: foreach my $item (@pairs) {
3323: my ($key,$value)=split(/\=/,$item,2);
3324: $key = &unescape($key);
3325: next if ($key =~ /^error: 2 /);
3326: $returnhash->{$key} = &thaw_unescape($value);
3327: }
3328: }
3329: }
3330: return;
3331: }
3332:
1.658 raeburn 3333: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3334:
3335: sub dcmailput {
1.685 raeburn 3336: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3337: my $status = &Apache::lonnet::critical(
1.740 www 3338: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3339: &escape($message),$server);
1.662 raeburn 3340: return $status;
3341: }
3342:
1.658 raeburn 3343: sub dcmaildump {
3344: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3345: my %returnhash=();
1.846 albertel 3346:
3347: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3348: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3349: &escape($enddate).':';
3350: my @esc_senders=map { &escape($_)} @$senders;
3351: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3352: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3353: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3354: if (($key) && ($value)) {
3355: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3356: }
3357: }
3358: }
3359: return %returnhash;
3360: }
1.662 raeburn 3361: # ---------------------------------------------------------- Domain roles
3362:
3363: sub get_domain_roles {
3364: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3365: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3366: $startdate = '.';
3367: }
1.1018 raeburn 3368: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3369: $enddate = '.';
3370: }
1.922 raeburn 3371: my $rolelist;
3372: if (ref($roles) eq 'ARRAY') {
3373: $rolelist = join(':',@{$roles});
3374: }
1.662 raeburn 3375: my %personnel = ();
1.841 albertel 3376:
3377: my %servers = &get_servers($dom,'library');
3378: foreach my $tryserver (keys(%servers)) {
3379: %{$personnel{$tryserver}}=();
3380: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3381: &escape($startdate).':'.
3382: &escape($enddate).':'.
3383: &escape($rolelist), $tryserver))) {
3384: my ($key,$value) = split(/\=/,$line,2);
3385: if (($key) && ($value)) {
3386: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3387: }
3388: }
1.662 raeburn 3389: }
3390: return %personnel;
3391: }
1.658 raeburn 3392:
1.149 www 3393: # ----------------------------------------------------------- Check out an item
3394:
1.504 albertel 3395: sub get_first_access {
3396: my ($type,$argsymb)=@_;
1.790 albertel 3397: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3398: if ($argsymb) { $symb=$argsymb; }
3399: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3400: if ($type eq 'course') {
3401: $res='course';
3402: } elsif ($type eq 'map') {
1.588 albertel 3403: $res=&symbread($map);
3404: } else {
3405: $res=$symb;
3406: }
3407: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3408: return $times{"$courseid\0$res"};
1.504 albertel 3409: }
3410:
3411: sub set_first_access {
3412: my ($type)=@_;
1.790 albertel 3413: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3414: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3415: if ($type eq 'course') {
3416: $res='course';
3417: } elsif ($type eq 'map') {
1.588 albertel 3418: $res=&symbread($map);
3419: } else {
3420: $res=$symb;
3421: }
3422: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3423: if (!$firstaccess) {
1.588 albertel 3424: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3425: }
3426: return 'already_set';
1.504 albertel 3427: }
3428:
1.149 www 3429: sub checkout {
3430: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3431: my $now=time;
3432: my $lonhost=$perlvar{'lonHostID'};
3433: my $infostr=&escape(
1.234 www 3434: 'CHECKOUTTOKEN&'.
1.149 www 3435: $tuname.'&'.
3436: $tudom.'&'.
3437: $tcrsid.'&'.
3438: $symb.'&'.
3439: $now.'&'.$ENV{'REMOTE_ADDR'});
3440: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3441: if ($token=~/^error\:/) {
1.672 albertel 3442: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3443: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3444: "</font>");
3445: return '';
3446: }
3447:
1.149 www 3448: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3449: $token=~tr/a-z/A-Z/;
3450:
1.153 www 3451: my %infohash=('resource.0.outtoken' => $token,
3452: 'resource.0.checkouttime' => $now,
3453: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3454:
3455: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3456: return '';
1.151 www 3457: } else {
1.672 albertel 3458: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3459: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3460: "</font>");
1.149 www 3461: }
3462:
3463: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3464: &escape('Checkout '.$infostr.' - '.
3465: $token)) ne 'ok') {
3466: return '';
1.151 www 3467: } else {
1.672 albertel 3468: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3469: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3470: "</font>");
1.149 www 3471: }
1.151 www 3472: return $token;
1.149 www 3473: }
3474:
3475: # ------------------------------------------------------------ Check in an item
3476:
3477: sub checkin {
3478: my $token=shift;
1.150 www 3479: my $now=time;
3480: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3481: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3482: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3483: $dtoken=~s/\W/\_/g;
1.234 www 3484: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3485: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3486:
1.154 www 3487: unless (($tuname) && ($tudom)) {
3488: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3489: return '';
3490: }
3491:
3492: unless (&allowed('mgr',$tcrsid)) {
3493: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3494: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3495: return '';
3496: }
3497:
1.153 www 3498: my %infohash=('resource.0.intoken' => $token,
3499: 'resource.0.checkintime' => $now,
3500: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3501:
3502: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3503: return '';
3504: }
3505:
3506: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3507: &escape('Checkin - '.$token)) ne 'ok') {
3508: return '';
3509: }
3510:
3511: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3512: }
3513:
3514: # --------------------------------------------- Set Expire Date for Spreadsheet
3515:
3516: sub expirespread {
3517: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3518: my $cid=$env{'request.course.id'};
1.110 www 3519: if ($cid) {
3520: my $now=time;
3521: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3522: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3523: $env{'course.'.$cid.'.num'}.
1.110 www 3524: ':nohist_expirationdates:'.
3525: &escape($key).'='.$now,
1.620 albertel 3526: $env{'course.'.$cid.'.home'})
1.110 www 3527: }
3528: return 'ok';
1.14 www 3529: }
3530:
1.109 www 3531: # ----------------------------------------------------- Devalidate Spreadsheets
3532:
3533: sub devalidate {
1.325 www 3534: my ($symb,$uname,$udom)=@_;
1.620 albertel 3535: my $cid=$env{'request.course.id'};
1.109 www 3536: if ($cid) {
1.391 matthew 3537: # delete the stored spreadsheets for
3538: # - the student level sheet of this user in course's homespace
3539: # - the assessment level sheet for this resource
3540: # for this user in user's homespace
1.553 albertel 3541: # - current conditional state info
1.325 www 3542: my $key=$uname.':'.$udom.':';
1.109 www 3543: my $status=
1.299 matthew 3544: &del('nohist_calculatedsheets',
1.391 matthew 3545: [$key.'studentcalc:'],
1.620 albertel 3546: $env{'course.'.$cid.'.domain'},
3547: $env{'course.'.$cid.'.num'})
1.133 albertel 3548: .' '.
3549: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3550: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3551: unless ($status eq 'ok ok') {
3552: &logthis('Could not devalidate spreadsheet '.
1.325 www 3553: $uname.' at '.$udom.' for '.
1.109 www 3554: $symb.': '.$status);
1.133 albertel 3555: }
1.553 albertel 3556: &delenv('user.state.'.$cid);
1.109 www 3557: }
3558: }
3559:
1.265 albertel 3560: sub get_scalar {
3561: my ($string,$end) = @_;
3562: my $value;
3563: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3564: $value = $1;
3565: } elsif ($$string =~ s/^([^&]*?)&//) {
3566: $value = $1;
3567: }
3568: return &unescape($value);
3569: }
3570:
3571: sub array2str {
3572: my (@array) = @_;
3573: my $result=&arrayref2str(\@array);
3574: $result=~s/^__ARRAY_REF__//;
3575: $result=~s/__END_ARRAY_REF__$//;
3576: return $result;
3577: }
3578:
1.204 albertel 3579: sub arrayref2str {
3580: my ($arrayref) = @_;
1.265 albertel 3581: my $result='__ARRAY_REF__';
1.204 albertel 3582: foreach my $elem (@$arrayref) {
1.265 albertel 3583: if(ref($elem) eq 'ARRAY') {
3584: $result.=&arrayref2str($elem).'&';
3585: } elsif(ref($elem) eq 'HASH') {
3586: $result.=&hashref2str($elem).'&';
3587: } elsif(ref($elem)) {
3588: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3589: } else {
3590: $result.=&escape($elem).'&';
3591: }
3592: }
3593: $result=~s/\&$//;
1.265 albertel 3594: $result .= '__END_ARRAY_REF__';
1.204 albertel 3595: return $result;
3596: }
3597:
1.168 albertel 3598: sub hash2str {
1.204 albertel 3599: my (%hash) = @_;
3600: my $result=&hashref2str(\%hash);
1.265 albertel 3601: $result=~s/^__HASH_REF__//;
3602: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3603: return $result;
3604: }
3605:
3606: sub hashref2str {
3607: my ($hashref)=@_;
1.265 albertel 3608: my $result='__HASH_REF__';
1.800 albertel 3609: foreach my $key (sort(keys(%$hashref))) {
3610: if (ref($key) eq 'ARRAY') {
3611: $result.=&arrayref2str($key).'=';
3612: } elsif (ref($key) eq 'HASH') {
3613: $result.=&hashref2str($key).'=';
3614: } elsif (ref($key)) {
1.265 albertel 3615: $result.='=';
1.800 albertel 3616: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3617: } else {
1.800 albertel 3618: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3619: }
3620:
1.800 albertel 3621: if(ref($hashref->{$key}) eq 'ARRAY') {
3622: $result.=&arrayref2str($hashref->{$key}).'&';
3623: } elsif(ref($hashref->{$key}) eq 'HASH') {
3624: $result.=&hashref2str($hashref->{$key}).'&';
3625: } elsif(ref($hashref->{$key})) {
1.265 albertel 3626: $result.='&';
1.800 albertel 3627: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3628: } else {
1.800 albertel 3629: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3630: }
3631: }
1.168 albertel 3632: $result=~s/\&$//;
1.265 albertel 3633: $result .= '__END_HASH_REF__';
1.168 albertel 3634: return $result;
3635: }
3636:
3637: sub str2hash {
1.265 albertel 3638: my ($string)=@_;
3639: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3640: return %$hash;
3641: }
3642:
3643: sub str2hashref {
1.168 albertel 3644: my ($string) = @_;
1.265 albertel 3645:
3646: my %hash;
3647:
3648: if($string !~ /^__HASH_REF__/) {
3649: if (! ($string eq '' || !defined($string))) {
3650: $hash{'error'}='Not hash reference';
3651: }
3652: return (\%hash, $string);
3653: }
3654:
3655: $string =~ s/^__HASH_REF__//;
3656:
3657: while($string !~ /^__END_HASH_REF__/) {
3658: #key
3659: my $key='';
3660: if($string =~ /^__HASH_REF__/) {
3661: ($key, $string)=&str2hashref($string);
3662: if(defined($key->{'error'})) {
3663: $hash{'error'}='Bad data';
3664: return (\%hash, $string);
3665: }
3666: } elsif($string =~ /^__ARRAY_REF__/) {
3667: ($key, $string)=&str2arrayref($string);
3668: if($key->[0] eq 'Array reference error') {
3669: $hash{'error'}='Bad data';
3670: return (\%hash, $string);
3671: }
3672: } else {
3673: $string =~ s/^(.*?)=//;
1.267 albertel 3674: $key=&unescape($1);
1.265 albertel 3675: }
3676: $string =~ s/^=//;
3677:
3678: #value
3679: my $value='';
3680: if($string =~ /^__HASH_REF__/) {
3681: ($value, $string)=&str2hashref($string);
3682: if(defined($value->{'error'})) {
3683: $hash{'error'}='Bad data';
3684: return (\%hash, $string);
3685: }
3686: } elsif($string =~ /^__ARRAY_REF__/) {
3687: ($value, $string)=&str2arrayref($string);
3688: if($value->[0] eq 'Array reference error') {
3689: $hash{'error'}='Bad data';
3690: return (\%hash, $string);
3691: }
3692: } else {
3693: $value=&get_scalar(\$string,'__END_HASH_REF__');
3694: }
3695: $string =~ s/^&//;
3696:
3697: $hash{$key}=$value;
1.204 albertel 3698: }
1.265 albertel 3699:
3700: $string =~ s/^__END_HASH_REF__//;
3701:
3702: return (\%hash, $string);
1.204 albertel 3703: }
3704:
3705: sub str2array {
1.265 albertel 3706: my ($string)=@_;
3707: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3708: return @$array;
3709: }
3710:
3711: sub str2arrayref {
1.204 albertel 3712: my ($string) = @_;
1.265 albertel 3713: my @array;
3714:
3715: if($string !~ /^__ARRAY_REF__/) {
3716: if (! ($string eq '' || !defined($string))) {
3717: $array[0]='Array reference error';
3718: }
3719: return (\@array, $string);
3720: }
3721:
3722: $string =~ s/^__ARRAY_REF__//;
3723:
3724: while($string !~ /^__END_ARRAY_REF__/) {
3725: my $value='';
3726: if($string =~ /^__HASH_REF__/) {
3727: ($value, $string)=&str2hashref($string);
3728: if(defined($value->{'error'})) {
3729: $array[0] ='Array reference error';
3730: return (\@array, $string);
3731: }
3732: } elsif($string =~ /^__ARRAY_REF__/) {
3733: ($value, $string)=&str2arrayref($string);
3734: if($value->[0] eq 'Array reference error') {
3735: $array[0] ='Array reference error';
3736: return (\@array, $string);
3737: }
3738: } else {
3739: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3740: }
3741: $string =~ s/^&//;
3742:
3743: push(@array, $value);
1.191 harris41 3744: }
1.265 albertel 3745:
3746: $string =~ s/^__END_ARRAY_REF__//;
3747:
3748: return (\@array, $string);
1.168 albertel 3749: }
3750:
1.167 albertel 3751: # -------------------------------------------------------------------Temp Store
3752:
1.168 albertel 3753: sub tmpreset {
3754: my ($symb,$namespace,$domain,$stuname) = @_;
3755: if (!$symb) {
3756: $symb=&symbread();
1.620 albertel 3757: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3758: }
3759: $symb=escape($symb);
3760:
1.620 albertel 3761: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3762: $namespace=~s/\//\_/g;
3763: $namespace=~s/\W//g;
3764:
1.620 albertel 3765: if (!$domain) { $domain=$env{'user.domain'}; }
3766: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3767: if ($domain eq 'public' && $stuname eq 'public') {
3768: $stuname=$ENV{'REMOTE_ADDR'};
3769: }
1.168 albertel 3770: my $path=$perlvar{'lonDaemons'}.'/tmp';
3771: my %hash;
3772: if (tie(%hash,'GDBM_File',
3773: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3774: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3775: foreach my $key (keys(%hash)) {
1.180 albertel 3776: if ($key=~ /:$symb/) {
1.168 albertel 3777: delete($hash{$key});
3778: }
3779: }
3780: }
3781: }
3782:
1.167 albertel 3783: sub tmpstore {
1.168 albertel 3784: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3785:
3786: if (!$symb) {
3787: $symb=&symbread();
1.620 albertel 3788: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3789: }
3790: $symb=escape($symb);
3791:
3792: if (!$namespace) {
3793: # I don't think we would ever want to store this for a course.
3794: # it seems this will only be used if we don't have a course.
1.620 albertel 3795: #$namespace=$env{'request.course.id'};
1.168 albertel 3796: #if (!$namespace) {
1.620 albertel 3797: $namespace=$env{'request.state'};
1.168 albertel 3798: #}
3799: }
3800: $namespace=~s/\//\_/g;
3801: $namespace=~s/\W//g;
1.620 albertel 3802: if (!$domain) { $domain=$env{'user.domain'}; }
3803: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3804: if ($domain eq 'public' && $stuname eq 'public') {
3805: $stuname=$ENV{'REMOTE_ADDR'};
3806: }
1.168 albertel 3807: my $now=time;
3808: my %hash;
3809: my $path=$perlvar{'lonDaemons'}.'/tmp';
3810: if (tie(%hash,'GDBM_File',
3811: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3812: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3813: $hash{"version:$symb"}++;
3814: my $version=$hash{"version:$symb"};
3815: my $allkeys='';
3816: foreach my $key (keys(%$storehash)) {
3817: $allkeys.=$key.':';
1.591 albertel 3818: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3819: }
3820: $hash{"$version:$symb:timestamp"}=$now;
3821: $allkeys.='timestamp';
3822: $hash{"$version:keys:$symb"}=$allkeys;
3823: if (untie(%hash)) {
3824: return 'ok';
3825: } else {
3826: return "error:$!";
3827: }
3828: } else {
3829: return "error:$!";
3830: }
3831: }
1.167 albertel 3832:
1.168 albertel 3833: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3834:
1.168 albertel 3835: sub tmprestore {
3836: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3837:
1.168 albertel 3838: if (!$symb) {
3839: $symb=&symbread();
1.620 albertel 3840: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3841: }
3842: $symb=escape($symb);
3843:
1.620 albertel 3844: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3845:
1.620 albertel 3846: if (!$domain) { $domain=$env{'user.domain'}; }
3847: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3848: if ($domain eq 'public' && $stuname eq 'public') {
3849: $stuname=$ENV{'REMOTE_ADDR'};
3850: }
1.168 albertel 3851: my %returnhash;
3852: $namespace=~s/\//\_/g;
3853: $namespace=~s/\W//g;
3854: my %hash;
3855: my $path=$perlvar{'lonDaemons'}.'/tmp';
3856: if (tie(%hash,'GDBM_File',
3857: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3858: &GDBM_READER(),0640)) {
1.168 albertel 3859: my $version=$hash{"version:$symb"};
3860: $returnhash{'version'}=$version;
3861: my $scope;
3862: for ($scope=1;$scope<=$version;$scope++) {
3863: my $vkeys=$hash{"$scope:keys:$symb"};
3864: my @keys=split(/:/,$vkeys);
3865: my $key;
3866: $returnhash{"$scope:keys"}=$vkeys;
3867: foreach $key (@keys) {
1.591 albertel 3868: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3869: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3870: }
3871: }
1.168 albertel 3872: if (!(untie(%hash))) {
3873: return "error:$!";
3874: }
3875: } else {
3876: return "error:$!";
3877: }
3878: return %returnhash;
1.167 albertel 3879: }
3880:
1.9 www 3881: # ----------------------------------------------------------------------- Store
3882:
3883: sub store {
1.124 www 3884: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3885: my $home='';
3886:
1.168 albertel 3887: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3888:
1.213 www 3889: $symb=&symbclean($symb);
1.122 albertel 3890: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3891:
1.620 albertel 3892: if (!$domain) { $domain=$env{'user.domain'}; }
3893: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3894:
3895: &devalidate($symb,$stuname,$domain);
1.109 www 3896:
3897: $symb=escape($symb);
1.187 www 3898: if (!$namespace) {
1.620 albertel 3899: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3900: return '';
3901: }
3902: }
1.620 albertel 3903: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3904:
3905: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3906: $$storehash{'host'}=$perlvar{'lonHostID'};
3907:
1.12 www 3908: my $namevalue='';
1.800 albertel 3909: foreach my $key (keys(%$storehash)) {
3910: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3911: }
1.12 www 3912: $namevalue=~s/\&$//;
1.187 www 3913: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3914: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3915: }
3916:
1.47 www 3917: # -------------------------------------------------------------- Critical Store
3918:
3919: sub cstore {
1.124 www 3920: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3921: my $home='';
3922:
1.168 albertel 3923: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3924:
1.213 www 3925: $symb=&symbclean($symb);
1.122 albertel 3926: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3927:
1.620 albertel 3928: if (!$domain) { $domain=$env{'user.domain'}; }
3929: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3930:
3931: &devalidate($symb,$stuname,$domain);
1.109 www 3932:
3933: $symb=escape($symb);
1.187 www 3934: if (!$namespace) {
1.620 albertel 3935: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3936: return '';
3937: }
3938: }
1.620 albertel 3939: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3940:
3941: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3942: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3943:
1.47 www 3944: my $namevalue='';
1.800 albertel 3945: foreach my $key (keys(%$storehash)) {
3946: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3947: }
1.47 www 3948: $namevalue=~s/\&$//;
1.187 www 3949: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3950: return critical
3951: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3952: }
3953:
1.9 www 3954: # --------------------------------------------------------------------- Restore
3955:
3956: sub restore {
1.124 www 3957: my ($symb,$namespace,$domain,$stuname) = @_;
3958: my $home='';
3959:
1.168 albertel 3960: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3961:
1.122 albertel 3962: if (!$symb) {
3963: unless ($symb=escape(&symbread())) { return ''; }
3964: } else {
1.213 www 3965: $symb=&escape(&symbclean($symb));
1.122 albertel 3966: }
1.188 www 3967: if (!$namespace) {
1.620 albertel 3968: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3969: return '';
3970: }
3971: }
1.620 albertel 3972: if (!$domain) { $domain=$env{'user.domain'}; }
3973: if (!$stuname) { $stuname=$env{'user.name'}; }
3974: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3975: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3976:
1.12 www 3977: my %returnhash=();
1.800 albertel 3978: foreach my $line (split(/\&/,$answer)) {
3979: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3980: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3981: }
1.75 www 3982: my $version;
3983: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3984: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3985: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3986: }
1.75 www 3987: }
1.13 www 3988: return %returnhash;
1.34 www 3989: }
3990:
3991: # ---------------------------------------------------------- Course Description
3992:
3993: sub coursedescription {
1.731 albertel 3994: my ($courseid,$args)=@_;
1.34 www 3995: $courseid=~s/^\///;
1.49 www 3996: $courseid=~s/\_/\//g;
1.34 www 3997: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3998: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3999: my $normalid=$cdomain.'_'.$cnum;
4000: # need to always cache even if we get errors otherwise we keep
4001: # trying and trying and trying to get the course description.
4002: my %envhash=();
4003: my %returnhash=();
1.731 albertel 4004:
4005: my $expiretime=600;
4006: if ($env{'request.course.id'} eq $normalid) {
4007: $expiretime=120;
4008: }
4009:
4010: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4011: if (!$args->{'freshen_cache'}
4012: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4013: foreach my $key (keys(%env)) {
4014: next if ($key !~ /^\Q$prefix\E(.*)/);
4015: my ($setting) = $1;
4016: $returnhash{$setting} = $env{$key};
4017: }
4018: return %returnhash;
4019: }
4020:
4021: # get the data agin
4022: if (!$args->{'one_time'}) {
4023: $envhash{'course.'.$normalid.'.last_cache'}=time;
4024: }
1.811 albertel 4025:
1.34 www 4026: if ($chome ne 'no_host') {
1.302 albertel 4027: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4028: if (!exists($returnhash{'con_lost'})) {
4029: $returnhash{'home'}= $chome;
4030: $returnhash{'domain'} = $cdomain;
4031: $returnhash{'num'} = $cnum;
1.741 raeburn 4032: if (!defined($returnhash{'type'})) {
4033: $returnhash{'type'} = 'Course';
4034: }
1.130 albertel 4035: while (my ($name,$value) = each %returnhash) {
1.53 www 4036: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4037: }
1.270 www 4038: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4039: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4040: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4041: $envhash{'course.'.$normalid.'.home'}=$chome;
4042: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4043: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4044: }
4045: }
1.731 albertel 4046: if (!$args->{'one_time'}) {
1.949 raeburn 4047: &appenv(\%envhash);
1.731 albertel 4048: }
1.302 albertel 4049: return %returnhash;
1.461 www 4050: }
4051:
1.1056.4.5 raeburn 4052: sub update_released_required {
4053: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4054: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4055: $cid = $env{'request.course.id'};
4056: $cdom = $env{'course.'.$cid.'.domain'};
4057: $cnum = $env{'course.'.$cid.'.num'};
4058: $chome = $env{'course.'.$cid.'.home'};
4059: }
4060: if ($needsrelease) {
4061: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4062: my $needsupdate;
4063: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4064: $needsupdate = 1;
4065: } else {
4066: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4067: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4068: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4069: $needsupdate = 1;
4070: }
4071: }
4072: if ($needsupdate) {
4073: my %needshash = (
4074: 'internal.releaserequired' => $needsrelease,
4075: );
4076: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4077: if ($putresult eq 'ok') {
4078: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4079: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4080: if (ref($crsinfo{$cid}) eq 'HASH') {
4081: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4082: &courseidput($cdom,\%crsinfo,$chome,'notime');
4083: }
4084: }
4085: }
4086: }
4087: return;
4088: }
4089:
1.461 www 4090: # -------------------------------------------------See if a user is privileged
4091:
4092: sub privileged {
4093: my ($username,$domain)=@_;
4094: my $rolesdump=&reply("dump:$domain:$username:roles",
4095: &homeserver($username,$domain));
1.1033 raeburn 4096: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4097: ($rolesdump =~ /^error:/)) {
4098: return 0;
4099: }
1.461 www 4100: my $now=time;
4101: if ($rolesdump ne '') {
1.800 albertel 4102: foreach my $entry (split(/&/,$rolesdump)) {
4103: if ($entry!~/^rolesdef_/) {
4104: my ($area,$role)=split(/=/,$entry);
1.461 www 4105: $area=~s/\_\w\w$//;
4106: my ($trole,$tend,$tstart)=split(/_/,$role);
4107: if (($trole eq 'dc') || ($trole eq 'su')) {
4108: my $active=1;
4109: if ($tend) {
4110: if ($tend<$now) { $active=0; }
4111: }
4112: if ($tstart) {
4113: if ($tstart>$now) { $active=0; }
4114: }
4115: if ($active) { return 1; }
4116: }
4117: }
4118: }
4119: }
4120: return 0;
1.9 www 4121: }
1.1 albertel 4122:
1.103 harris41 4123: # -------------------------------------------------------- Get user privileges
1.11 www 4124:
4125: sub rolesinit {
4126: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4127: my $now=time;
4128: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4129: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4130: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4131: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4132: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4133: return \%userroles;
4134: }
1.11 www 4135: my %allroles=();
1.678 raeburn 4136: my %allgroups=();
4137: my $group_privs;
1.11 www 4138:
4139: if ($rolesdump ne '') {
1.800 albertel 4140: foreach my $entry (split(/&/,$rolesdump)) {
4141: if ($entry!~/^rolesdef_/) {
4142: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4143: $area=~s/\_\w\w$//;
1.678 raeburn 4144: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4145: if ($role=~/^cr/) {
1.807 albertel 4146: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4147: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4148: ($tend,$tstart)=split('_',$trest);
4149: } else {
4150: $trole=$role;
4151: }
1.678 raeburn 4152: } elsif ($role =~ m|^gr/|) {
4153: ($trole,$tend,$tstart) = split(/_/,$role);
4154: ($trole,$group_privs) = split(/\//,$trole);
4155: $group_privs = &unescape($group_privs);
1.587 albertel 4156: } else {
4157: ($trole,$tend,$tstart)=split(/_/,$role);
4158: }
1.743 albertel 4159: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4160: $username);
4161: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4162: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4163: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4164: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4165: my $spec=$trole.'.'.$area;
4166: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4167: if ($trole =~ /^cr\//) {
1.567 raeburn 4168: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4169: } elsif ($trole eq 'gr') {
4170: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4171: } else {
1.567 raeburn 4172: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4173: }
1.12 www 4174: }
1.662 raeburn 4175: }
1.191 harris41 4176: }
1.743 albertel 4177: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4178: $userroles{'user.adv'} = $adv;
4179: $userroles{'user.author'} = $author;
1.620 albertel 4180: $env{'user.adv'}=$adv;
1.11 www 4181: }
1.743 albertel 4182: return \%userroles;
1.11 www 4183: }
4184:
1.567 raeburn 4185: sub set_arearole {
4186: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4187: # log the associated role with the area
4188: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4189: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4190: }
4191:
4192: sub custom_roleprivs {
4193: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4194: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4195: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4196: if (&hostname($homsvr) ne '') {
1.567 raeburn 4197: my ($rdummy,$roledef)=
4198: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4199: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4200: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4201: if (defined($syspriv)) {
1.1043 raeburn 4202: if ($trest =~ /^$match_community$/) {
4203: $syspriv =~ s/bre\&S//;
4204: }
1.567 raeburn 4205: $$allroles{'cm./'}.=':'.$syspriv;
4206: $$allroles{$spec.'./'}.=':'.$syspriv;
4207: }
4208: if ($tdomain ne '') {
4209: if (defined($dompriv)) {
4210: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4211: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4212: }
4213: if (($trest ne '') && (defined($coursepriv))) {
4214: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4215: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4216: }
4217: }
4218: }
4219: }
4220: }
4221:
1.678 raeburn 4222: sub group_roleprivs {
4223: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4224: my $access = 1;
4225: my $now = time;
4226: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4227: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4228: if ($access) {
1.811 albertel 4229: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4230: $$allgroups{$course}{$group} .=':'.$group_privs;
4231: }
4232: }
1.567 raeburn 4233:
4234: sub standard_roleprivs {
4235: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4236: if (defined($pr{$trole.':s'})) {
4237: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4238: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4239: }
4240: if ($tdomain ne '') {
4241: if (defined($pr{$trole.':d'})) {
4242: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4243: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4244: }
4245: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4246: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4247: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4248: }
4249: }
4250: }
4251:
4252: sub set_userprivs {
1.1056.4.2 raeburn 4253: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4254: my $author=0;
4255: my $adv=0;
1.678 raeburn 4256: my %grouproles = ();
4257: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4258: my @groupkeys;
1.1000 raeburn 4259: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4260: push(@groupkeys,$role);
4261: }
4262: if (ref($groups_roles) eq 'HASH') {
4263: foreach my $key (keys(%{$groups_roles})) {
4264: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4265: push(@groupkeys,$key);
4266: }
4267: }
4268: }
4269: if (@groupkeys > 0) {
4270: foreach my $role (@groupkeys) {
4271: my ($trole,$area,$sec,$extendedarea);
4272: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4273: $trole = $1;
4274: $area = $2;
4275: $sec = $3;
4276: $extendedarea = $area.$sec;
4277: if (exists($$allgroups{$area})) {
4278: foreach my $group (keys(%{$$allgroups{$area}})) {
4279: my $spec = $trole.'.'.$extendedarea;
4280: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4281: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4282: }
1.678 raeburn 4283: }
4284: }
4285: }
4286: }
4287: }
1.800 albertel 4288: foreach my $group (keys(%grouproles)) {
4289: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4290: }
1.800 albertel 4291: foreach my $role (keys(%{$allroles})) {
4292: my %thesepriv;
1.941 raeburn 4293: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4294: foreach my $item (split(/:/,$$allroles{$role})) {
4295: if ($item ne '') {
4296: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4297: if ($restrictions eq '') {
4298: $thesepriv{$privilege}='F';
4299: } elsif ($thesepriv{$privilege} ne 'F') {
4300: $thesepriv{$privilege}.=$restrictions;
4301: }
4302: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4303: }
4304: }
4305: my $thesestr='';
1.800 albertel 4306: foreach my $priv (keys(%thesepriv)) {
4307: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4308: }
4309: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4310: }
4311: return ($author,$adv);
4312: }
4313:
1.994 raeburn 4314: sub role_status {
1.1002 raeburn 4315: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4316: my @pwhere = ();
4317: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4318: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4319: unless (!defined($$role) || $$role eq '') {
4320: $$where=join('.',@pwhere);
4321: $$trolecode=$$role.'.'.$$where;
4322: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4323: $$tstatus='is';
4324: if ($$tstart && $$tstart>$then) {
4325: $$tstatus='future';
1.1034 raeburn 4326: if ($$tstart<$now) {
4327: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4328: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4329: my (%allroles,%allgroups,$group_privs,
4330: %groups_roles,@rolecodes);
1.1002 raeburn 4331: my %userroles = (
4332: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4333: );
1.1056.4.2 raeburn 4334: @rolecodes = ('cm');
1.1002 raeburn 4335: my $spec=$$role.'.'.$$where;
4336: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4337: if ($$role =~ /^cr\//) {
4338: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4339: push(@rolecodes,'cr');
1.1002 raeburn 4340: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4341: push(@rolecodes,$$role);
1.1002 raeburn 4342: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4343: $env{'user.name'});
1.1056.4.2 raeburn 4344: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4345: (undef,my $group_privs) = split(/\//,$trole);
4346: $group_privs = &unescape($group_privs);
4347: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4348: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4349: if (keys(%course_roles) > 0) {
4350: my ($tnum) = ($trest =~ /^($match_courseid)/);
4351: if ($tdomain ne '' && $tnum ne '') {
4352: foreach my $key (keys(%course_roles)) {
4353: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4354: my $crsrole = $1;
4355: my $crssec = $2;
4356: if ($crsrole =~ /^cr/) {
4357: unless (grep(/^cr$/,@rolecodes)) {
4358: push(@rolecodes,'cr');
4359: }
4360: } else {
4361: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4362: push(@rolecodes,$crsrole);
4363: }
4364: }
4365: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4366: if ($crssec ne '') {
4367: $rolekey .= '/'.$crssec;
4368: }
4369: $rolekey .= './';
4370: $groups_roles{$rolekey} = \@rolecodes;
4371: }
4372: }
4373: }
4374: }
1.1002 raeburn 4375: } else {
1.1056.4.2 raeburn 4376: push(@rolecodes,$$role);
1.1002 raeburn 4377: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4378: }
1.1056.4.2 raeburn 4379: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4380: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4381: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4382: }
4383: }
1.1034 raeburn 4384: $$tstatus = 'is';
1.1002 raeburn 4385: }
1.994 raeburn 4386: }
4387: if ($$tend) {
4388: if ($$tend<$then) {
4389: $$tstatus='expired';
4390: } elsif ($$tend<$now) {
4391: $$tstatus='will_not';
4392: }
4393: }
4394: }
4395: }
4396: }
4397:
4398: sub check_adhoc_privs {
1.1002 raeburn 4399: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4400: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4401: if ($env{$cckey}) {
4402: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4403: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4404: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4405: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4406: }
4407: } else {
4408: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4409: }
4410: }
4411:
4412: sub set_adhoc_privileges {
4413: # role can be cc or ca
4414: my ($dcdom,$pickedcourse,$role) = @_;
4415: my $area = '/'.$dcdom.'/'.$pickedcourse;
4416: my $spec = $role.'.'.$area;
4417: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4418: $env{'user.name'});
4419: my %ccrole = ();
4420: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4421: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4422: &appenv(\%userroles,[$role,'cm']);
4423: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4424: &appenv( {'request.role' => $spec,
4425: 'request.role.domain' => $dcdom,
4426: 'request.course.sec' => ''
4427: }
4428: );
4429: my $tadv=0;
4430: if (&allowed('adv') eq 'F') { $tadv=1; }
4431: &appenv({'request.role.adv' => $tadv});
4432: }
4433:
1.12 www 4434: # --------------------------------------------------------------- get interface
4435:
4436: sub get {
1.131 albertel 4437: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4438: my $items='';
1.800 albertel 4439: foreach my $item (@$storearr) {
4440: $items.=&escape($item).'&';
1.191 harris41 4441: }
1.12 www 4442: $items=~s/\&$//;
1.620 albertel 4443: if (!$udomain) { $udomain=$env{'user.domain'}; }
4444: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4445: my $uhome=&homeserver($uname,$udomain);
4446:
1.133 albertel 4447: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4448: my @pairs=split(/\&/,$rep);
1.273 albertel 4449: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4450: return @pairs;
4451: }
1.15 www 4452: my %returnhash=();
1.42 www 4453: my $i=0;
1.800 albertel 4454: foreach my $item (@$storearr) {
4455: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4456: $i++;
1.191 harris41 4457: }
1.15 www 4458: return %returnhash;
1.27 www 4459: }
4460:
4461: # --------------------------------------------------------------- del interface
4462:
4463: sub del {
1.133 albertel 4464: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4465: my $items='';
1.800 albertel 4466: foreach my $item (@$storearr) {
4467: $items.=&escape($item).'&';
1.191 harris41 4468: }
1.984 neumanie 4469:
1.27 www 4470: $items=~s/\&$//;
1.620 albertel 4471: if (!$udomain) { $udomain=$env{'user.domain'}; }
4472: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4473: my $uhome=&homeserver($uname,$udomain);
4474: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4475: }
4476:
4477: # -------------------------------------------------------------- dump interface
4478:
4479: sub dump {
1.1056.4.10 raeburn 4480: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4481: if (!$udomain) { $udomain=$env{'user.domain'}; }
4482: if (!$uname) { $uname=$env{'user.name'}; }
4483: my $uhome=&homeserver($uname,$udomain);
4484: if ($regexp) {
4485: $regexp=&escape($regexp);
4486: } else {
4487: $regexp='.';
4488: }
1.1056.4.10 raeburn 4489: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4490: my @pairs=split(/\&/,$rep);
4491: my %returnhash=();
4492: foreach my $item (@pairs) {
4493: my ($key,$value)=split(/=/,$item,2);
4494: $key = &unescape($key);
4495: next if ($key =~ /^error: 2 /);
4496: $returnhash{$key}=&thaw_unescape($value);
4497: }
4498: return %returnhash;
1.407 www 4499: }
4500:
1.717 albertel 4501: # --------------------------------------------------------- dumpstore interface
4502:
4503: sub dumpstore {
4504: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4505: if (!$udomain) { $udomain=$env{'user.domain'}; }
4506: if (!$uname) { $uname=$env{'user.name'}; }
4507: my $uhome=&homeserver($uname,$udomain);
4508: if ($regexp) {
4509: $regexp=&escape($regexp);
4510: } else {
4511: $regexp='.';
4512: }
4513: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4514: my @pairs=split(/\&/,$rep);
4515: my %returnhash=();
4516: foreach my $item (@pairs) {
4517: my ($key,$value)=split(/=/,$item,2);
4518: next if ($key =~ /^error: 2 /);
4519: $returnhash{$key}=&thaw_unescape($value);
4520: }
4521: return %returnhash;
1.717 albertel 4522: }
4523:
1.407 www 4524: # -------------------------------------------------------------- keys interface
4525:
4526: sub getkeys {
4527: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4528: if (!$udomain) { $udomain=$env{'user.domain'}; }
4529: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4530: my $uhome=&homeserver($uname,$udomain);
4531: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4532: my @keyarray=();
1.800 albertel 4533: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4534: next if ($key =~ /^error: 2 /);
1.800 albertel 4535: push(@keyarray,&unescape($key));
1.407 www 4536: }
4537: return @keyarray;
1.318 matthew 4538: }
4539:
1.319 matthew 4540: # --------------------------------------------------------------- currentdump
4541: sub currentdump {
1.328 matthew 4542: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4543: $courseid = $env{'request.course.id'} if (! defined($courseid));
4544: $sdom = $env{'user.domain'} if (! defined($sdom));
4545: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4546: my $uhome = &homeserver($sname,$sdom);
4547: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4548: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4549: #
1.318 matthew 4550: my %returnhash=();
1.319 matthew 4551: #
4552: if ($rep eq "unknown_cmd") {
4553: # an old lond will not know currentdump
4554: # Do a dump and make it look like a currentdump
1.822 albertel 4555: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4556: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4557: my %hash = @tmp;
4558: @tmp=();
1.424 matthew 4559: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4560: } else {
4561: my @pairs=split(/\&/,$rep);
1.800 albertel 4562: foreach my $pair (@pairs) {
4563: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4564: my ($symb,$param) = split(/:/,$key);
4565: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4566: &thaw_unescape($value);
1.319 matthew 4567: }
1.191 harris41 4568: }
1.12 www 4569: return %returnhash;
1.424 matthew 4570: }
4571:
4572: sub convert_dump_to_currentdump{
4573: my %hash = %{shift()};
4574: my %returnhash;
4575: # Code ripped from lond, essentially. The only difference
4576: # here is the unescaping done by lonnet::dump(). Conceivably
4577: # we might run in to problems with parameter names =~ /^v\./
4578: while (my ($key,$value) = each(%hash)) {
4579: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4580: $symb = &unescape($symb);
4581: $param = &unescape($param);
1.424 matthew 4582: next if ($v eq 'version' || $symb eq 'keys');
4583: next if (exists($returnhash{$symb}) &&
4584: exists($returnhash{$symb}->{$param}) &&
4585: $returnhash{$symb}->{'v.'.$param} > $v);
4586: $returnhash{$symb}->{$param}=$value;
4587: $returnhash{$symb}->{'v.'.$param}=$v;
4588: }
4589: #
4590: # Remove all of the keys in the hashes which keep track of
4591: # the version of the parameter.
4592: while (my ($symb,$param_hash) = each(%returnhash)) {
4593: # use a foreach because we are going to delete from the hash.
4594: foreach my $key (keys(%$param_hash)) {
4595: delete($param_hash->{$key}) if ($key =~ /^v\./);
4596: }
4597: }
4598: return \%returnhash;
1.12 www 4599: }
4600:
1.627 albertel 4601: # ------------------------------------------------------ critical inc interface
4602:
4603: sub cinc {
4604: return &inc(@_,'critical');
4605: }
4606:
1.449 matthew 4607: # --------------------------------------------------------------- inc interface
4608:
4609: sub inc {
1.627 albertel 4610: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4611: if (!$udomain) { $udomain=$env{'user.domain'}; }
4612: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4613: my $uhome=&homeserver($uname,$udomain);
4614: my $items='';
4615: if (! ref($store)) {
4616: # got a single value, so use that instead
4617: $items = &escape($store).'=&';
4618: } elsif (ref($store) eq 'SCALAR') {
4619: $items = &escape($$store).'=&';
4620: } elsif (ref($store) eq 'ARRAY') {
4621: $items = join('=&',map {&escape($_);} @{$store});
4622: } elsif (ref($store) eq 'HASH') {
4623: while (my($key,$value) = each(%{$store})) {
4624: $items.= &escape($key).'='.&escape($value).'&';
4625: }
4626: }
4627: $items=~s/\&$//;
1.627 albertel 4628: if ($critical) {
4629: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4630: } else {
4631: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4632: }
1.449 matthew 4633: }
4634:
1.12 www 4635: # --------------------------------------------------------------- put interface
4636:
4637: sub put {
1.134 albertel 4638: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4639: if (!$udomain) { $udomain=$env{'user.domain'}; }
4640: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4641: my $uhome=&homeserver($uname,$udomain);
1.12 www 4642: my $items='';
1.800 albertel 4643: foreach my $item (keys(%$storehash)) {
4644: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4645: }
1.12 www 4646: $items=~s/\&$//;
1.134 albertel 4647: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4648: }
4649:
1.631 albertel 4650: # ------------------------------------------------------------ newput interface
4651:
4652: sub newput {
4653: my ($namespace,$storehash,$udomain,$uname)=@_;
4654: if (!$udomain) { $udomain=$env{'user.domain'}; }
4655: if (!$uname) { $uname=$env{'user.name'}; }
4656: my $uhome=&homeserver($uname,$udomain);
4657: my $items='';
4658: foreach my $key (keys(%$storehash)) {
4659: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4660: }
4661: $items=~s/\&$//;
4662: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4663: }
4664:
4665: # --------------------------------------------------------- putstore interface
4666:
1.524 raeburn 4667: sub putstore {
1.715 albertel 4668: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4669: if (!$udomain) { $udomain=$env{'user.domain'}; }
4670: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4671: my $uhome=&homeserver($uname,$udomain);
4672: my $items='';
1.715 albertel 4673: foreach my $key (keys(%$storehash)) {
4674: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4675: }
1.715 albertel 4676: $items=~s/\&$//;
1.716 albertel 4677: my $esc_symb=&escape($symb);
4678: my $esc_v=&escape($version);
1.715 albertel 4679: my $reply =
1.716 albertel 4680: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4681: $uhome);
4682: if ($reply eq 'unknown_cmd') {
1.716 albertel 4683: # gfall back to way things use to be done
1.715 albertel 4684: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4685: $uname);
1.524 raeburn 4686: }
1.715 albertel 4687: return $reply;
4688: }
4689:
4690: sub old_putstore {
1.716 albertel 4691: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4692: if (!$udomain) { $udomain=$env{'user.domain'}; }
4693: if (!$uname) { $uname=$env{'user.name'}; }
4694: my $uhome=&homeserver($uname,$udomain);
4695: my %newstorehash;
1.800 albertel 4696: foreach my $item (keys(%$storehash)) {
4697: my $key = $version.':'.&escape($symb).':'.$item;
4698: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4699: }
4700: my $items='';
4701: my %allitems = ();
1.800 albertel 4702: foreach my $item (keys(%newstorehash)) {
4703: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4704: my $key = $1.':keys:'.$2;
4705: $allitems{$key} .= $3.':';
4706: }
1.800 albertel 4707: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4708: }
1.800 albertel 4709: foreach my $item (keys(%allitems)) {
4710: $allitems{$item} =~ s/\:$//;
4711: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4712: }
4713: $items=~s/\&$//;
4714: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4715: }
4716:
1.47 www 4717: # ------------------------------------------------------ critical put interface
4718:
4719: sub cput {
1.134 albertel 4720: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4721: if (!$udomain) { $udomain=$env{'user.domain'}; }
4722: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4723: my $uhome=&homeserver($uname,$udomain);
1.47 www 4724: my $items='';
1.800 albertel 4725: foreach my $item (keys(%$storehash)) {
4726: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4727: }
1.47 www 4728: $items=~s/\&$//;
1.134 albertel 4729: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4730: }
4731:
4732: # -------------------------------------------------------------- eget interface
4733:
4734: sub eget {
1.133 albertel 4735: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4736: my $items='';
1.800 albertel 4737: foreach my $item (@$storearr) {
4738: $items.=&escape($item).'&';
1.191 harris41 4739: }
1.12 www 4740: $items=~s/\&$//;
1.620 albertel 4741: if (!$udomain) { $udomain=$env{'user.domain'}; }
4742: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4743: my $uhome=&homeserver($uname,$udomain);
4744: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4745: my @pairs=split(/\&/,$rep);
4746: my %returnhash=();
1.42 www 4747: my $i=0;
1.800 albertel 4748: foreach my $item (@$storearr) {
4749: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4750: $i++;
1.191 harris41 4751: }
1.12 www 4752: return %returnhash;
4753: }
4754:
1.667 albertel 4755: # ------------------------------------------------------------ tmpput interface
4756: sub tmpput {
1.802 raeburn 4757: my ($storehash,$server,$context)=@_;
1.667 albertel 4758: my $items='';
1.800 albertel 4759: foreach my $item (keys(%$storehash)) {
4760: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4761: }
4762: $items=~s/\&$//;
1.802 raeburn 4763: if (defined($context)) {
4764: $items .= ':'.&escape($context);
4765: }
1.667 albertel 4766: return &reply("tmpput:$items",$server);
4767: }
4768:
4769: # ------------------------------------------------------------ tmpget interface
4770: sub tmpget {
1.688 albertel 4771: my ($token,$server)=@_;
4772: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4773: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4774: my %returnhash;
4775: foreach my $item (split(/\&/,$rep)) {
4776: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4777: next if ($key =~ /^error: 2 /);
1.667 albertel 4778: $returnhash{&unescape($key)}=&thaw_unescape($value);
4779: }
4780: return %returnhash;
4781: }
4782:
1.688 albertel 4783: # ------------------------------------------------------------ tmpget interface
4784: sub tmpdel {
4785: my ($token,$server)=@_;
4786: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4787: return &reply("tmpdel:$token",$server);
4788: }
4789:
1.765 albertel 4790: # -------------------------------------------------- portfolio access checking
4791:
4792: sub portfolio_access {
1.766 albertel 4793: my ($requrl) = @_;
1.765 albertel 4794: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4795: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4796: if ($result) {
4797: my %setters;
4798: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4799: my ($startblock,$endblock) =
4800: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4801: if ($startblock && $endblock) {
4802: return 'B';
4803: }
4804: } else {
4805: my ($startblock,$endblock) =
4806: &Apache::loncommon::blockcheck(\%setters,'port');
4807: if ($startblock && $endblock) {
4808: return 'B';
4809: }
4810: }
4811: }
1.765 albertel 4812: if ($result eq 'ok') {
1.766 albertel 4813: return 'F';
1.765 albertel 4814: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4815: return 'A';
1.765 albertel 4816: }
1.766 albertel 4817: return '';
1.765 albertel 4818: }
4819:
4820: sub get_portfolio_access {
1.767 albertel 4821: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4822:
4823: if (!ref($access_hash)) {
4824: my $current_perms = &get_portfile_permissions($udom,$unum);
4825: my %access_controls = &get_access_controls($current_perms,$group,
4826: $file_name);
4827: $access_hash = $access_controls{$file_name};
4828: }
4829:
1.765 albertel 4830: my ($public,$guest,@domains,@users,@courses,@groups);
4831: my $now = time;
4832: if (ref($access_hash) eq 'HASH') {
4833: foreach my $key (keys(%{$access_hash})) {
4834: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4835: if ($start > $now) {
4836: next;
4837: }
4838: if ($end && $end<$now) {
4839: next;
4840: }
4841: if ($scope eq 'public') {
4842: $public = $key;
4843: last;
4844: } elsif ($scope eq 'guest') {
4845: $guest = $key;
4846: } elsif ($scope eq 'domains') {
4847: push(@domains,$key);
4848: } elsif ($scope eq 'users') {
4849: push(@users,$key);
4850: } elsif ($scope eq 'course') {
4851: push(@courses,$key);
4852: } elsif ($scope eq 'group') {
4853: push(@groups,$key);
4854: }
4855: }
4856: if ($public) {
4857: return 'ok';
4858: }
4859: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4860: if ($guest) {
4861: return $guest;
4862: }
4863: } else {
4864: if (@domains > 0) {
4865: foreach my $domkey (@domains) {
4866: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4867: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4868: return 'ok';
4869: }
4870: }
4871: }
4872: }
4873: if (@users > 0) {
4874: foreach my $userkey (@users) {
1.865 raeburn 4875: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4876: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4877: if (ref($item) eq 'HASH') {
4878: if (($item->{'uname'} eq $env{'user.name'}) &&
4879: ($item->{'udom'} eq $env{'user.domain'})) {
4880: return 'ok';
4881: }
4882: }
4883: }
4884: }
1.765 albertel 4885: }
4886: }
4887: my %roleshash;
4888: my @courses_and_groups = @courses;
4889: push(@courses_and_groups,@groups);
4890: if (@courses_and_groups > 0) {
4891: my (%allgroups,%allroles);
4892: my ($start,$end,$role,$sec,$group);
4893: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4894: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4895: my $cid = $2.'_'.$3;
4896: if ($1 eq 'gr') {
4897: $group = $4;
4898: $allgroups{$cid}{$group} = $env{$envkey};
4899: } else {
4900: if ($4 eq '') {
4901: $sec = 'none';
4902: } else {
4903: $sec = $4;
4904: }
4905: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4906: }
1.811 albertel 4907: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4908: my $cid = $2.'_'.$3;
4909: if ($4 eq '') {
4910: $sec = 'none';
4911: } else {
4912: $sec = $4;
4913: }
4914: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4915: }
4916: }
4917: if (keys(%allroles) == 0) {
4918: return;
4919: }
4920: foreach my $key (@courses_and_groups) {
4921: my %content = %{$$access_hash{$key}};
4922: my $cnum = $content{'number'};
4923: my $cdom = $content{'domain'};
4924: my $cid = $cdom.'_'.$cnum;
4925: if (!exists($allroles{$cid})) {
4926: next;
4927: }
4928: foreach my $role_id (keys(%{$content{'roles'}})) {
4929: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4930: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4931: my @status = @{$content{'roles'}{$role_id}{'access'}};
4932: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4933: foreach my $role (keys(%{$allroles{$cid}})) {
4934: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4935: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4936: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4937: if (grep/^all$/,@sections) {
4938: return 'ok';
4939: } else {
4940: if (grep/^$sec$/,@sections) {
4941: return 'ok';
4942: }
4943: }
4944: }
4945: }
4946: if (keys(%{$allgroups{$cid}}) == 0) {
4947: if (grep/^none$/,@groups) {
4948: return 'ok';
4949: }
4950: } else {
4951: if (grep/^all$/,@groups) {
4952: return 'ok';
4953: }
4954: foreach my $group (keys(%{$allgroups{$cid}})) {
4955: if (grep/^$group$/,@groups) {
4956: return 'ok';
4957: }
4958: }
4959: }
4960: }
4961: }
4962: }
4963: }
4964: }
4965: if ($guest) {
4966: return $guest;
4967: }
4968: }
4969: }
4970: return;
4971: }
4972:
4973: sub course_group_datechecker {
4974: my ($dates,$now,$status) = @_;
4975: my ($start,$end) = split(/\./,$dates);
4976: if (!$start && !$end) {
4977: return 'ok';
4978: }
4979: if (grep/^active$/,@{$status}) {
4980: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4981: return 'ok';
4982: }
4983: }
4984: if (grep/^previous$/,@{$status}) {
4985: if ($end > $now ) {
4986: return 'ok';
4987: }
4988: }
4989: if (grep/^future$/,@{$status}) {
4990: if ($start > $now) {
4991: return 'ok';
4992: }
4993: }
4994: return;
4995: }
4996:
4997: sub parse_portfolio_url {
4998: my ($url) = @_;
4999:
5000: my ($type,$udom,$unum,$group,$file_name);
5001:
1.823 albertel 5002: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5003: $type = 1;
5004: $udom = $1;
5005: $unum = $2;
5006: $file_name = $3;
1.823 albertel 5007: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5008: $type = 2;
5009: $udom = $1;
5010: $unum = $2;
5011: $group = $3;
5012: $file_name = $3.'/'.$4;
5013: }
5014: if (wantarray) {
5015: return ($type,$udom,$unum,$file_name,$group);
5016: }
5017: return $type;
5018: }
5019:
5020: sub is_portfolio_url {
5021: my ($url) = @_;
5022: return scalar(&parse_portfolio_url($url));
5023: }
5024:
1.798 raeburn 5025: sub is_portfolio_file {
5026: my ($file) = @_;
1.820 raeburn 5027: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5028: return 1;
5029: }
5030: return;
5031: }
5032:
1.976 raeburn 5033: sub usertools_access {
1.1056.4.9 raeburn 5034: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5035: my ($access,%tools);
5036: if ($context eq '') {
5037: $context = 'tools';
5038: }
5039: if ($context eq 'requestcourses') {
5040: %tools = (
5041: official => 1,
5042: unofficial => 1,
1.1006 raeburn 5043: community => 1,
1.985 raeburn 5044: );
5045: } else {
5046: %tools = (
5047: aboutme => 1,
5048: blog => 1,
5049: portfolio => 1,
5050: );
5051: }
1.976 raeburn 5052: return if (!defined($tools{$tool}));
5053:
5054: if ((!defined($udom)) || (!defined($uname))) {
5055: $udom = $env{'user.domain'};
5056: $uname = $env{'user.name'};
5057: }
5058:
1.978 raeburn 5059: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5060: if ($action ne 'reload') {
1.985 raeburn 5061: if ($context eq 'requestcourses') {
5062: return $env{'environment.canrequest.'.$tool};
5063: } else {
5064: return $env{'environment.availabletools.'.$tool};
5065: }
5066: }
1.976 raeburn 5067: }
5068:
5069: my ($toolstatus,$inststatus);
5070:
1.985 raeburn 5071: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5072: ($action ne 'reload')) {
5073: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5074: $inststatus = $env{'environment.inststatus'};
5075: } else {
1.1056.4.9 raeburn 5076: if (ref($userenvref) eq 'HASH') {
5077: $toolstatus = $userenvref->{$context.'.'.$tool};
5078: $inststatus = $userenvref->{'inststatus'};
5079: } else {
5080: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5081: $toolstatus = $userenv{$context.'.'.$tool};
5082: $inststatus = $userenv{'inststatus'};
5083: }
1.976 raeburn 5084: }
5085:
5086: if ($toolstatus ne '') {
5087: if ($toolstatus) {
5088: $access = 1;
5089: } else {
5090: $access = 0;
5091: }
5092: return $access;
5093: }
5094:
1.1056.4.9 raeburn 5095: my ($is_adv,%domdef);
5096: if (ref($is_advref) eq 'HASH') {
5097: $is_adv = $is_advref->{'is_adv'};
5098: } else {
5099: $is_adv = &is_advanced_user($udom,$uname);
5100: }
5101: if (ref($domdefref) eq 'HASH') {
5102: %domdef = %{$domdefref};
5103: } else {
5104: %domdef = &get_domain_defaults($udom);
5105: }
1.976 raeburn 5106: if (ref($domdef{$tool}) eq 'HASH') {
5107: if ($is_adv) {
5108: if ($domdef{$tool}{'_LC_adv'} ne '') {
5109: if ($domdef{$tool}{'_LC_adv'}) {
5110: $access = 1;
5111: } else {
5112: $access = 0;
5113: }
5114: return $access;
5115: }
5116: }
5117: if ($inststatus ne '') {
5118: my ($hasaccess,$hasnoaccess);
5119: foreach my $affiliation (split(/:/,$inststatus)) {
5120: if ($domdef{$tool}{$affiliation} ne '') {
5121: if ($domdef{$tool}{$affiliation}) {
5122: $hasaccess = 1;
5123: } else {
5124: $hasnoaccess = 1;
5125: }
5126: }
5127: }
5128: if ($hasaccess || $hasnoaccess) {
5129: if ($hasaccess) {
5130: $access = 1;
5131: } elsif ($hasnoaccess) {
5132: $access = 0;
5133: }
5134: return $access;
5135: }
5136: } else {
5137: if ($domdef{$tool}{'default'} ne '') {
5138: if ($domdef{$tool}{'default'}) {
5139: $access = 1;
5140: } elsif ($domdef{$tool}{'default'} == 0) {
5141: $access = 0;
5142: }
5143: return $access;
5144: }
5145: }
5146: } else {
1.985 raeburn 5147: if ($context eq 'tools') {
5148: $access = 1;
5149: } else {
5150: $access = 0;
5151: }
1.976 raeburn 5152: return $access;
5153: }
5154: }
5155:
1.1050 raeburn 5156: sub is_course_owner {
5157: my ($cdom,$cnum,$udom,$uname) = @_;
5158: if (($udom eq '') || ($uname eq '')) {
5159: $udom = $env{'user.domain'};
5160: $uname = $env{'user.name'};
5161: }
5162: unless (($udom eq '') || ($uname eq '')) {
5163: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5164: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5165: return 1;
5166: } else {
5167: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5168: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5169: return 1;
5170: }
5171: }
5172: }
5173: }
5174: return;
5175: }
5176:
1.976 raeburn 5177: sub is_advanced_user {
5178: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5179: if ($udom ne '' && $uname ne '') {
5180: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5181: return $env{'user.adv'};
5182: }
5183: }
1.976 raeburn 5184: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5185: my %allroles;
5186: my $is_adv;
5187: foreach my $role (keys(%roleshash)) {
5188: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5189: my $area = '/'.$tdomain.'/'.$trest;
5190: if ($sec ne '') {
5191: $area .= '/'.$sec;
5192: }
5193: if (($area ne '') && ($trole ne '')) {
5194: my $spec=$trole.'.'.$area;
5195: if ($trole =~ /^cr\//) {
5196: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5197: } elsif ($trole ne 'gr') {
5198: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5199: }
5200: }
5201: }
5202: foreach my $role (keys(%allroles)) {
5203: last if ($is_adv);
5204: foreach my $item (split(/:/,$allroles{$role})) {
5205: if ($item ne '') {
5206: my ($privilege,$restrictions)=split(/&/,$item);
5207: if ($privilege eq 'adv') {
5208: $is_adv = 1;
5209: last;
5210: }
5211: }
5212: }
5213: }
5214: return $is_adv;
5215: }
1.798 raeburn 5216:
1.1035 raeburn 5217: sub check_can_request {
1.1036 raeburn 5218: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5219: my $canreq = 0;
5220: my ($types,$typename) = &Apache::loncommon::course_types();
5221: my @options = ('approval','validate','autolimit');
5222: my $optregex = join('|',@options);
5223: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5224: foreach my $type (@{$types}) {
5225: if (&usertools_access($env{'user.name'},
5226: $env{'user.domain'},
5227: $type,undef,'requestcourses')) {
5228: $canreq ++;
1.1036 raeburn 5229: if (ref($request_domains) eq 'HASH') {
5230: push(@{$request_domains->{$type}},$env{'user.domain'});
5231: }
1.1035 raeburn 5232: if ($dom eq $env{'user.domain'}) {
5233: $can_request->{$type} = 1;
5234: }
5235: }
5236: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5237: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5238: if (@curr > 0) {
1.1036 raeburn 5239: foreach my $item (@curr) {
5240: if (ref($request_domains) eq 'HASH') {
5241: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5242: if ($otherdom ne '') {
5243: if (ref($request_domains->{$type}) eq 'ARRAY') {
5244: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5245: push(@{$request_domains->{$type}},$otherdom);
5246: }
5247: } else {
5248: push(@{$request_domains->{$type}},$otherdom);
5249: }
5250: }
5251: }
5252: }
5253: unless($dom eq $env{'user.domain'}) {
5254: $canreq ++;
1.1035 raeburn 5255: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5256: $can_request->{$type} = 1;
5257: }
5258: }
5259: }
5260: }
5261: }
5262: }
5263: return $canreq;
5264: }
5265:
1.341 www 5266: # ---------------------------------------------- Custom access rule evaluation
5267:
5268: sub customaccess {
5269: my ($priv,$uri)=@_;
1.807 albertel 5270: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5271: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5272: $udom = &LONCAPA::clean_domain($udom);
5273: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5274: my $access=0;
1.800 albertel 5275: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5276: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5277: if ($type eq 'user') {
5278: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5279: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5280: if ($tdom) {
5281: if ($tdom ne $env{'user.domain'}) { next; }
5282: }
1.896 albertel 5283: if ($tuname) {
5284: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5285: }
5286: $access=($effect eq 'allow');
5287: last;
5288: }
5289: } else {
5290: if ($role) {
5291: if ($role ne $urole) { next; }
5292: }
5293: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5294: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5295: if ($tdom) {
5296: if ($tdom ne $udom) { next; }
5297: }
5298: if ($tcrs) {
5299: if ($tcrs ne $ucrs) { next; }
5300: }
5301: if ($tsec) {
5302: if ($tsec ne $usec) { next; }
5303: }
5304: $access=($effect eq 'allow');
5305: last;
5306: }
5307: if ($realm eq '' && $role eq '') {
5308: $access=($effect eq 'allow');
5309: }
1.402 bowersj2 5310: }
1.341 www 5311: }
5312: return $access;
5313: }
5314:
1.103 harris41 5315: # ------------------------------------------------- Check for a user privilege
1.12 www 5316:
5317: sub allowed {
1.810 raeburn 5318: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5319: my $ver_orguri=$uri;
1.439 www 5320: $uri=&deversion($uri);
1.152 www 5321: my $orguri=$uri;
1.52 www 5322: $uri=&declutter($uri);
1.809 raeburn 5323:
1.810 raeburn 5324: if ($priv eq 'evb') {
5325: # Evade communication block restrictions for specified role in a course
5326: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5327: return $1;
5328: } else {
5329: return;
5330: }
5331: }
5332:
1.620 albertel 5333: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5334: # Free bre access to adm and meta resources
1.775 albertel 5335: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5336: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5337: && ($priv eq 'bre')) {
1.14 www 5338: return 'F';
1.159 www 5339: }
5340:
1.545 banghart 5341: # Free bre access to user's own portfolio contents
1.714 raeburn 5342: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5343: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5344: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5345: my %setters;
5346: my ($startblock,$endblock) =
5347: &Apache::loncommon::blockcheck(\%setters,'port');
5348: if ($startblock && $endblock) {
5349: return 'B';
5350: } else {
5351: return 'F';
5352: }
1.545 banghart 5353: }
5354:
1.762 raeburn 5355: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5356: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5357: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5358: if (exists($env{'request.course.id'})) {
5359: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5360: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5361: if (($domain eq $cdom) && ($name eq $cnum)) {
5362: my $courseprivid=$env{'request.course.id'};
5363: $courseprivid=~s/\_/\//;
5364: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5365: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5366: return $1;
1.762 raeburn 5367: } else {
5368: if ($env{'request.course.sec'}) {
5369: $courseprivid.='/'.$env{'request.course.sec'};
5370: }
5371: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5372: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5373: return $2;
5374: }
1.714 raeburn 5375: }
5376: }
5377: }
5378: }
5379:
1.159 www 5380: # Free bre to public access
5381:
5382: if ($priv eq 'bre') {
1.238 www 5383: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5384: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5385: return 'F';
5386: }
1.238 www 5387: if ($copyright eq 'priv') {
5388: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5389: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5390: return '';
5391: }
5392: }
5393: if ($copyright eq 'domain') {
5394: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5395: unless (($env{'user.domain'} eq $1) ||
5396: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5397: return '';
5398: }
1.262 matthew 5399: }
1.620 albertel 5400: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5401: # Library role, so allow browsing of resources in this domain.
5402: return 'F';
1.238 www 5403: }
1.341 www 5404: if ($copyright eq 'custom') {
5405: unless (&customaccess($priv,$uri)) { return ''; }
5406: }
1.14 www 5407: }
1.264 matthew 5408: # Domain coordinator is trying to create a course
1.620 albertel 5409: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5410: # uri is the requested domain in this case.
5411: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5412: # a role of dc for the domain in question.
1.620 albertel 5413: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5414: }
1.29 www 5415:
1.52 www 5416: my $thisallowed='';
5417: my $statecond=0;
5418: my $courseprivid='';
5419:
1.1039 raeburn 5420: my $ownaccess;
1.1043 raeburn 5421: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5422: if (($priv eq 'bro') && ($env{'user.author'})) {
5423: if ($uri eq '') {
5424: $ownaccess = 1;
5425: } else {
5426: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5427: my $udom = $env{'user.domain'};
5428: my $uname = $env{'user.name'};
5429: if ($uri =~ m{^\Q$udom\E/?$}) {
5430: $ownaccess = 1;
1.1040 raeburn 5431: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5432: unless ($uri =~ m{\.\./}) {
5433: $ownaccess = 1;
5434: }
5435: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5436: my $now = time;
5437: if ($uri =~ m{^([^/]+)/?$}) {
5438: my $adom = $1;
5439: foreach my $key (keys(%env)) {
1.1042 raeburn 5440: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5441: my ($start,$end) = split('.',$env{$key});
5442: if (($now >= $start) && (!$end || $end < $now)) {
5443: $ownaccess = 1;
5444: last;
5445: }
5446: }
5447: }
5448: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5449: my $adom = $1;
5450: my $aname = $2;
1.1042 raeburn 5451: foreach my $role ('ca','aa') {
5452: if ($env{"user.role.$role./$adom/$aname"}) {
5453: my ($start,$end) =
5454: split('.',$env{"user.role.$role./$adom/$aname"});
5455: if (($now >= $start) && (!$end || $end < $now)) {
5456: $ownaccess = 1;
5457: last;
5458: }
1.1039 raeburn 5459: }
5460: }
5461: }
5462: }
5463: }
5464: }
5465: }
5466:
1.52 www 5467: # Course
5468:
1.620 albertel 5469: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5470: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5471: $thisallowed.=$1;
5472: }
1.52 www 5473: }
1.29 www 5474:
1.52 www 5475: # Domain
5476:
1.620 albertel 5477: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5478: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5479: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5480: $thisallowed.=$1;
5481: }
1.12 www 5482: }
1.52 www 5483:
5484: # Course: uri itself is a course
1.66 www 5485: my $courseuri=$uri;
5486: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5487: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5488:
1.620 albertel 5489: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5490: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5491: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5492: $thisallowed.=$1;
5493: }
1.12 www 5494: }
1.29 www 5495:
1.665 albertel 5496: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5497: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5498: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5499: $thisallowed='';
1.671 raeburn 5500: my ($match)=&is_on_map($uri);
5501: if ($match) {
5502: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5503: =~/\Q$priv\E\&([^\:]*)/) {
5504: $thisallowed.=$1;
5505: }
5506: } else {
1.705 albertel 5507: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5508: if ($refuri) {
5509: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5510: $thisallowed='F';
1.671 raeburn 5511: } else {
5512: $refuri=&declutter($refuri);
5513: my ($match) = &is_on_map($refuri);
5514: if ($match) {
5515: $thisallowed='F';
5516: }
1.669 raeburn 5517: }
1.671 raeburn 5518: }
5519: }
1.314 www 5520: }
1.492 albertel 5521:
1.766 albertel 5522: if ($priv eq 'bre'
5523: && $thisallowed ne 'F'
5524: && $thisallowed ne '2'
5525: && &is_portfolio_url($uri)) {
5526: $thisallowed = &portfolio_access($uri);
5527: }
5528:
1.52 www 5529: # Full access at system, domain or course-wide level? Exit.
1.29 www 5530: if ($thisallowed=~/F/) {
5531: return 'F';
5532: }
5533:
1.52 www 5534: # If this is generating or modifying users, exit with special codes
1.29 www 5535:
1.643 www 5536: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5537: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5538: my ($audom,$auname)=split('/',$uri);
1.643 www 5539: # no author name given, so this just checks on the general right to make a co-author in this domain
5540: unless ($auname) { return $thisallowed; }
5541: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5542: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5543: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5544: ($audom ne $env{'request.role.domain'}))) { return ''; }
5545: }
1.52 www 5546: return $thisallowed;
5547: }
5548: #
1.103 harris41 5549: # Gathered so far: system, domain and course wide privileges
1.52 www 5550: #
5551: # Course: See if uri or referer is an individual resource that is part of
5552: # the course
5553:
1.620 albertel 5554: if ($env{'request.course.id'}) {
1.232 www 5555:
1.620 albertel 5556: $courseprivid=$env{'request.course.id'};
5557: if ($env{'request.course.sec'}) {
5558: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5559: }
5560: $courseprivid=~s/\_/\//;
5561: my $checkreferer=1;
1.232 www 5562: my ($match,$cond)=&is_on_map($uri);
5563: if ($match) {
5564: $statecond=$cond;
1.620 albertel 5565: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5566: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5567: $thisallowed.=$1;
5568: $checkreferer=0;
5569: }
1.29 www 5570: }
1.83 www 5571:
1.148 www 5572: if ($checkreferer) {
1.620 albertel 5573: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5574: unless ($refuri) {
1.800 albertel 5575: foreach my $key (keys(%env)) {
5576: if ($key=~/^httpref\..*\*/) {
5577: my $pattern=$key;
1.156 www 5578: $pattern=~s/^httpref\.\/res\///;
1.148 www 5579: $pattern=~s/\*/\[\^\/\]\+/g;
5580: $pattern=~s/\//\\\//g;
1.152 www 5581: if ($orguri=~/$pattern/) {
1.800 albertel 5582: $refuri=$env{$key};
1.148 www 5583: }
5584: }
1.191 harris41 5585: }
1.148 www 5586: }
1.232 www 5587:
1.148 www 5588: if ($refuri) {
1.152 www 5589: $refuri=&declutter($refuri);
1.232 www 5590: my ($match,$cond)=&is_on_map($refuri);
5591: if ($match) {
5592: my $refstatecond=$cond;
1.620 albertel 5593: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5594: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5595: $thisallowed.=$1;
1.53 www 5596: $uri=$refuri;
5597: $statecond=$refstatecond;
1.52 www 5598: }
5599: }
1.148 www 5600: }
1.29 www 5601: }
1.52 www 5602: }
1.29 www 5603:
1.52 www 5604: #
1.103 harris41 5605: # Gathered now: all privileges that could apply, and condition number
1.52 www 5606: #
5607: #
5608: # Full or no access?
5609: #
1.29 www 5610:
1.52 www 5611: if ($thisallowed=~/F/) {
5612: return 'F';
5613: }
1.29 www 5614:
1.52 www 5615: unless ($thisallowed) {
5616: return '';
5617: }
1.29 www 5618:
1.52 www 5619: # Restrictions exist, deal with them
5620: #
5621: # C:according to course preferences
5622: # R:according to resource settings
5623: # L:unless locked
5624: # X:according to user session state
5625: #
5626:
5627: # Possibly locked functionality, check all courses
1.54 www 5628: # Locks might take effect only after 10 minutes cache expiration for other
5629: # courses, and 2 minutes for current course
1.52 www 5630:
5631: my $envkey;
5632: if ($thisallowed=~/L/) {
1.1000 raeburn 5633: foreach $envkey (keys(%env)) {
1.54 www 5634: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5635: my $courseid=$2;
5636: my $roleid=$1.'.'.$2;
1.92 www 5637: $courseid=~s/^\///;
1.54 www 5638: my $expiretime=600;
1.620 albertel 5639: if ($env{'request.role'} eq $roleid) {
1.54 www 5640: $expiretime=120;
5641: }
5642: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5643: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5644: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5645: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5646: }
1.620 albertel 5647: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5648: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5649: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5650: &log($env{'user.domain'},$env{'user.name'},
5651: $env{'user.home'},
1.57 www 5652: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5653: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5654: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5655: return '';
5656: }
5657: }
1.620 albertel 5658: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5659: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5660: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5661: &log($env{'user.domain'},$env{'user.name'},
5662: $env{'user.home'},
1.57 www 5663: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5664: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5665: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5666: return '';
5667: }
5668: }
5669: }
1.29 www 5670: }
1.52 www 5671: }
5672:
5673: #
5674: # Rest of the restrictions depend on selected course
5675: #
5676:
1.620 albertel 5677: unless ($env{'request.course.id'}) {
1.766 albertel 5678: if ($thisallowed eq 'A') {
5679: return 'A';
1.814 raeburn 5680: } elsif ($thisallowed eq 'B') {
5681: return 'B';
1.766 albertel 5682: } else {
5683: return '1';
5684: }
1.52 www 5685: }
1.29 www 5686:
1.52 www 5687: #
5688: # Now user is definitely in a course
5689: #
1.53 www 5690:
5691:
5692: # Course preferences
5693:
5694: if ($thisallowed=~/C/) {
1.620 albertel 5695: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5696: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5697: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5698: =~/\Q$rolecode\E/) {
1.689 albertel 5699: if ($priv ne 'pch') {
5700: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5701: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5702: $env{'request.course.id'});
5703: }
1.237 www 5704: return '';
5705: }
5706:
1.620 albertel 5707: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5708: =~/\Q$unamedom\E/) {
1.689 albertel 5709: if ($priv ne 'pch') {
5710: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5711: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5712: $env{'request.course.id'});
5713: }
1.54 www 5714: return '';
5715: }
1.53 www 5716: }
5717:
5718: # Resource preferences
5719:
5720: if ($thisallowed=~/R/) {
1.620 albertel 5721: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5722: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5723: if ($priv ne 'pch') {
5724: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5725: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5726: }
5727: return '';
1.54 www 5728: }
1.53 www 5729: }
1.30 www 5730:
1.246 www 5731: # Restricted by state or randomout?
1.30 www 5732:
1.52 www 5733: if ($thisallowed=~/X/) {
1.620 albertel 5734: if ($env{'acc.randomout'}) {
1.579 albertel 5735: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5736: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5737: return '';
5738: }
1.247 www 5739: }
5740: if (&condval($statecond)) {
1.52 www 5741: return '2';
5742: } else {
5743: return '';
5744: }
5745: }
1.30 www 5746:
1.766 albertel 5747: if ($thisallowed eq 'A') {
5748: return 'A';
1.814 raeburn 5749: } elsif ($thisallowed eq 'B') {
5750: return 'B';
1.766 albertel 5751: }
1.52 www 5752: return 'F';
1.232 www 5753: }
5754:
1.710 albertel 5755: sub split_uri_for_cond {
5756: my $uri=&deversion(&declutter(shift));
5757: my @uriparts=split(/\//,$uri);
5758: my $filename=pop(@uriparts);
5759: my $pathname=join('/',@uriparts);
5760: return ($pathname,$filename);
5761: }
1.232 www 5762: # --------------------------------------------------- Is a resource on the map?
5763:
5764: sub is_on_map {
1.710 albertel 5765: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5766: #Trying to find the conditional for the file
1.620 albertel 5767: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5768: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5769: if ($match) {
1.289 bowersj2 5770: return (1,$1);
5771: } else {
1.434 www 5772: return (0,0);
1.289 bowersj2 5773: }
1.12 www 5774: }
5775:
1.427 www 5776: # --------------------------------------------------------- Get symb from alias
5777:
5778: sub get_symb_from_alias {
5779: my $symb=shift;
5780: my ($map,$resid,$url)=&decode_symb($symb);
5781: # Already is a symb
5782: if ($url) { return $symb; }
5783: # Must be an alias
5784: my $aliassymb='';
5785: my %bighash;
1.620 albertel 5786: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5787: &GDBM_READER(),0640)) {
5788: my $rid=$bighash{'mapalias_'.$symb};
5789: if ($rid) {
5790: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5791: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5792: $resid,$bighash{'src_'.$rid});
1.427 www 5793: }
5794: untie %bighash;
5795: }
5796: return $aliassymb;
5797: }
5798:
1.12 www 5799: # ----------------------------------------------------------------- Define Role
5800:
5801: sub definerole {
5802: if (allowed('mcr','/')) {
5803: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5804: foreach my $role (split(':',$sysrole)) {
5805: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5806: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5807: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5808: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5809: return "refused:s:$crole&$cqual";
5810: }
5811: }
1.191 harris41 5812: }
1.800 albertel 5813: foreach my $role (split(':',$domrole)) {
5814: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5815: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5816: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5817: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5818: return "refused:d:$crole&$cqual";
5819: }
5820: }
1.191 harris41 5821: }
1.800 albertel 5822: foreach my $role (split(':',$courole)) {
5823: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5824: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5825: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5826: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5827: return "refused:c:$crole&$cqual";
5828: }
5829: }
1.191 harris41 5830: }
1.620 albertel 5831: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5832: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5833: "rolesdef_$rolename=".
5834: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5835: return reply($command,$env{'user.home'});
1.12 www 5836: } else {
5837: return 'refused';
5838: }
1.105 harris41 5839: }
5840:
5841: # ---------------- Make a metadata query against the network of library servers
5842:
5843: sub metadata_query {
1.244 matthew 5844: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5845: my %rhash;
1.845 albertel 5846: my %libserv = &all_library();
1.244 matthew 5847: my @server_list = (defined($server_array) ? @$server_array
5848: : keys(%libserv) );
5849: for my $server (@server_list) {
1.118 harris41 5850: unless ($custom or $customshow) {
5851: my $reply=&reply("querysend:".&escape($query),$server);
5852: $rhash{$server}=$reply;
5853: }
5854: else {
5855: my $reply=&reply("querysend:".&escape($query).':'.
5856: &escape($custom).':'.&escape($customshow),
5857: $server);
5858: $rhash{$server}=$reply;
5859: }
1.112 harris41 5860: }
1.118 harris41 5861: return \%rhash;
1.240 www 5862: }
5863:
5864: # ----------------------------------------- Send log queries and wait for reply
5865:
5866: sub log_query {
5867: my ($uname,$udom,$query,%filters)=@_;
5868: my $uhome=&homeserver($uname,$udom);
5869: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5870: my $uhost=&hostname($uhome);
1.800 albertel 5871: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5872: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5873: $uhome);
1.479 albertel 5874: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5875: return get_query_reply($queryid);
5876: }
5877:
1.818 raeburn 5878: # -------------------------- Update MySQL table for portfolio file
5879:
5880: sub update_portfolio_table {
1.821 raeburn 5881: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5882: if ($group ne '') {
5883: $file_name =~s /^\Q$group\E//;
5884: }
1.818 raeburn 5885: my $homeserver = &homeserver($uname,$udom);
5886: my $queryid=
1.821 raeburn 5887: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5888: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5889: my $reply = &get_query_reply($queryid);
5890: return $reply;
5891: }
5892:
1.899 raeburn 5893: # -------------------------- Update MySQL allusers table
5894:
5895: sub update_allusers_table {
5896: my ($uname,$udom,$names) = @_;
5897: my $homeserver = &homeserver($uname,$udom);
5898: my $queryid=
5899: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5900: 'lastname='.&escape($names->{'lastname'}).'%%'.
5901: 'firstname='.&escape($names->{'firstname'}).'%%'.
5902: 'middlename='.&escape($names->{'middlename'}).'%%'.
5903: 'generation='.&escape($names->{'generation'}).'%%'.
5904: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5905: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 5906: return;
1.899 raeburn 5907: }
5908:
1.508 raeburn 5909: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5910:
5911: sub fetch_enrollment_query {
1.511 raeburn 5912: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5913: my $homeserver;
1.547 raeburn 5914: my $maxtries = 1;
1.508 raeburn 5915: if ($context eq 'automated') {
5916: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5917: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5918: } else {
5919: $homeserver = &homeserver($cnum,$dom);
5920: }
1.838 albertel 5921: my $host=&hostname($homeserver);
1.506 raeburn 5922: my $cmd = '';
1.1000 raeburn 5923: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5924: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5925: }
5926: $cmd =~ s/%%$//;
5927: $cmd = &escape($cmd);
5928: my $query = 'fetchenrollment';
1.620 albertel 5929: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5930: unless ($queryid=~/^\Q$host\E\_/) {
5931: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5932: return 'error: '.$queryid;
5933: }
1.506 raeburn 5934: my $reply = &get_query_reply($queryid);
1.547 raeburn 5935: my $tries = 1;
5936: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5937: $reply = &get_query_reply($queryid);
5938: $tries ++;
5939: }
1.526 raeburn 5940: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5941: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5942: } else {
1.901 albertel 5943: my @responses = split(/:/,$reply);
1.515 raeburn 5944: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5945: foreach my $line (@responses) {
5946: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5947: $$replyref{$key} = $value;
5948: }
5949: } else {
1.506 raeburn 5950: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5951: foreach my $line (@responses) {
5952: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5953: $$replyref{$key} = $value;
5954: if ($value > 0) {
1.800 albertel 5955: foreach my $item (@{$$affiliatesref{$key}}) {
5956: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5957: my $destname = $pathname.'/'.$filename;
5958: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5959: if ($xml_classlist =~ /^error/) {
5960: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5961: } else {
1.506 raeburn 5962: if ( open(FILE,">$destname") ) {
5963: print FILE &unescape($xml_classlist);
5964: close(FILE);
1.526 raeburn 5965: } else {
5966: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5967: }
5968: }
5969: }
5970: }
5971: }
5972: }
5973: return 'ok';
5974: }
5975: return 'error';
5976: }
5977:
1.242 www 5978: sub get_query_reply {
5979: my $queryid=shift;
1.240 www 5980: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5981: my $reply='';
5982: for (1..100) {
5983: sleep 2;
5984: if (-e $replyfile.'.end') {
1.448 albertel 5985: if (open(my $fh,$replyfile)) {
1.904 albertel 5986: $reply = join('',<$fh>);
5987: close($fh);
1.240 www 5988: } else { return 'error: reply_file_error'; }
1.242 www 5989: return &unescape($reply);
5990: }
1.240 www 5991: }
1.242 www 5992: return 'timeout:'.$queryid;
1.240 www 5993: }
5994:
5995: sub courselog_query {
1.241 www 5996: #
5997: # possible filters:
5998: # url: url or symb
5999: # username
6000: # domain
6001: # action: view, submit, grade
6002: # start: timestamp
6003: # end: timestamp
6004: #
1.240 www 6005: my (%filters)=@_;
1.620 albertel 6006: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6007: if ($filters{'url'}) {
6008: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6009: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6010: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6011: }
1.620 albertel 6012: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6013: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6014: return &log_query($cname,$cdom,'courselog',%filters);
6015: }
6016:
6017: sub userlog_query {
1.858 raeburn 6018: #
6019: # possible filters:
6020: # action: log check role
6021: # start: timestamp
6022: # end: timestamp
6023: #
1.240 www 6024: my ($uname,$udom,%filters)=@_;
6025: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6026: }
6027:
1.506 raeburn 6028: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6029:
6030: sub auto_run {
1.508 raeburn 6031: my ($cnum,$cdom) = @_;
1.876 raeburn 6032: my $response = 0;
6033: my $settings;
6034: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6035: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6036: $settings = $domconfig{'autoenroll'};
6037: if ($settings->{'run'} eq '1') {
6038: $response = 1;
6039: }
6040: } else {
1.934 raeburn 6041: my $homeserver;
6042: if (&is_course($cdom,$cnum)) {
6043: $homeserver = &homeserver($cnum,$cdom);
6044: } else {
6045: $homeserver = &domain($cdom,'primary');
6046: }
6047: if ($homeserver ne 'no_host') {
6048: $response = &reply('autorun:'.$cdom,$homeserver);
6049: }
1.876 raeburn 6050: }
1.506 raeburn 6051: return $response;
6052: }
1.776 albertel 6053:
1.506 raeburn 6054: sub auto_get_sections {
1.508 raeburn 6055: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6056: my $homeserver;
6057: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6058: $homeserver = &homeserver($cnum,$cdom);
6059: }
6060: if (!defined($homeserver)) {
6061: if ($cdom =~ /^$match_domain$/) {
6062: $homeserver = &domain($cdom,'primary');
6063: }
6064: }
6065: my @secs;
6066: if (defined($homeserver)) {
6067: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6068: unless ($response eq 'refused') {
6069: @secs = split(/:/,$response);
6070: }
1.506 raeburn 6071: }
6072: return @secs;
6073: }
1.776 albertel 6074:
1.506 raeburn 6075: sub auto_new_course {
1.508 raeburn 6076: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
6077: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 6078: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 6079: return $response;
6080: }
1.776 albertel 6081:
1.506 raeburn 6082: sub auto_validate_courseID {
1.508 raeburn 6083: my ($cnum,$cdom,$inst_course_id) = @_;
6084: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6085: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6086: return $response;
6087: }
1.776 albertel 6088:
1.1007 raeburn 6089: sub auto_validate_instcode {
1.1020 raeburn 6090: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6091: my ($homeserver,$response);
6092: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6093: $homeserver = &homeserver($cnum,$cdom);
6094: }
6095: if (!defined($homeserver)) {
6096: if ($cdom =~ /^$match_domain$/) {
6097: $homeserver = &domain($cdom,'primary');
6098: }
6099: }
1.1056.4.2 raeburn 6100: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6101: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6102: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6103: return ($outcome,$description);
1.1007 raeburn 6104: }
6105:
1.506 raeburn 6106: sub auto_create_password {
1.873 raeburn 6107: my ($cnum,$cdom,$authparam,$udom) = @_;
6108: my ($homeserver,$response);
1.506 raeburn 6109: my $create_passwd = 0;
6110: my $authchk = '';
1.873 raeburn 6111: if ($udom =~ /^$match_domain$/) {
6112: $homeserver = &domain($udom,'primary');
6113: }
6114: if ($homeserver eq '') {
6115: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6116: $homeserver = &homeserver($cnum,$cdom);
6117: }
6118: }
6119: if ($homeserver eq '') {
6120: $authchk = 'nodomain';
1.506 raeburn 6121: } else {
1.873 raeburn 6122: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6123: if ($response eq 'refused') {
6124: $authchk = 'refused';
6125: } else {
1.901 albertel 6126: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6127: }
1.506 raeburn 6128: }
6129: return ($authparam,$create_passwd,$authchk);
6130: }
6131:
1.706 raeburn 6132: sub auto_photo_permission {
6133: my ($cnum,$cdom,$students) = @_;
6134: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6135: my ($outcome,$perm_reqd,$conditions) =
6136: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6137: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6138: return (undef,undef);
6139: }
1.706 raeburn 6140: return ($outcome,$perm_reqd,$conditions);
6141: }
6142:
6143: sub auto_checkphotos {
6144: my ($uname,$udom,$pid) = @_;
6145: my $homeserver = &homeserver($uname,$udom);
6146: my ($result,$resulttype);
6147: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6148: &escape($uname).':'.&escape($pid),
6149: $homeserver));
1.709 albertel 6150: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6151: return (undef,undef);
6152: }
1.706 raeburn 6153: if ($outcome) {
6154: ($result,$resulttype) = split(/:/,$outcome);
6155: }
6156: return ($result,$resulttype);
6157: }
6158:
6159: sub auto_photochoice {
6160: my ($cnum,$cdom) = @_;
6161: my $homeserver = &homeserver($cnum,$cdom);
6162: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6163: &escape($cdom),
6164: $homeserver)));
1.709 albertel 6165: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6166: return (undef,undef);
6167: }
1.706 raeburn 6168: return ($update,$comment);
6169: }
6170:
6171: sub auto_photoupdate {
6172: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6173: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6174: my $host=&hostname($homeserver);
1.706 raeburn 6175: my $cmd = '';
6176: my $maxtries = 1;
1.800 albertel 6177: foreach my $affiliate (keys(%{$affiliatesref})) {
6178: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6179: }
6180: $cmd =~ s/%%$//;
6181: $cmd = &escape($cmd);
6182: my $query = 'institutionalphotos';
6183: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6184: unless ($queryid=~/^\Q$host\E\_/) {
6185: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6186: return 'error: '.$queryid;
6187: }
6188: my $reply = &get_query_reply($queryid);
6189: my $tries = 1;
6190: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6191: $reply = &get_query_reply($queryid);
6192: $tries ++;
6193: }
6194: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6195: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6196: } else {
6197: my @responses = split(/:/,$reply);
6198: my $outcome = shift(@responses);
6199: foreach my $item (@responses) {
6200: my ($key,$value) = split(/=/,$item);
6201: $$photo{$key} = $value;
6202: }
6203: return $outcome;
6204: }
6205: return 'error';
6206: }
6207:
1.521 raeburn 6208: sub auto_instcode_format {
1.793 albertel 6209: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6210: $cat_order) = @_;
1.521 raeburn 6211: my $courses = '';
1.772 raeburn 6212: my @homeservers;
1.521 raeburn 6213: if ($caller eq 'global') {
1.841 albertel 6214: my %servers = &get_servers($codedom,'library');
6215: foreach my $tryserver (keys(%servers)) {
6216: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6217: push(@homeservers,$tryserver);
6218: }
1.584 raeburn 6219: }
1.1022 raeburn 6220: } elsif ($caller eq 'requests') {
6221: if ($codedom =~ /^$match_domain$/) {
6222: my $chome = &domain($codedom,'primary');
6223: unless ($chome eq 'no_host') {
6224: push(@homeservers,$chome);
6225: }
6226: }
1.521 raeburn 6227: } else {
1.772 raeburn 6228: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6229: }
1.793 albertel 6230: foreach my $code (keys(%{$instcodes})) {
6231: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6232: }
6233: chop($courses);
1.772 raeburn 6234: my $ok_response = 0;
6235: my $response;
6236: while (@homeservers > 0 && $ok_response == 0) {
6237: my $server = shift(@homeservers);
6238: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6239: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6240: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6241: split(/:/,$response);
1.772 raeburn 6242: %{$codes} = (%{$codes},&str2hash($codes_str));
6243: push(@{$codetitles},&str2array($codetitles_str));
6244: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6245: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6246: $ok_response = 1;
6247: }
6248: }
6249: if ($ok_response) {
1.521 raeburn 6250: return 'ok';
1.772 raeburn 6251: } else {
6252: return $response;
1.521 raeburn 6253: }
6254: }
6255:
1.792 raeburn 6256: sub auto_instcode_defaults {
6257: my ($domain,$returnhash,$code_order) = @_;
6258: my @homeservers;
1.841 albertel 6259:
6260: my %servers = &get_servers($domain,'library');
6261: foreach my $tryserver (keys(%servers)) {
6262: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6263: push(@homeservers,$tryserver);
6264: }
1.792 raeburn 6265: }
1.841 albertel 6266:
1.792 raeburn 6267: my $response;
1.841 albertel 6268: foreach my $server (@homeservers) {
1.792 raeburn 6269: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6270: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6271:
6272: foreach my $pair (split(/\&/,$response)) {
6273: my ($name,$value)=split(/\=/,$pair);
6274: if ($name eq 'code_order') {
6275: @{$code_order} = split(/\&/,&unescape($value));
6276: } else {
6277: $returnhash->{&unescape($name)}=&unescape($value);
6278: }
6279: }
6280: return 'ok';
1.792 raeburn 6281: }
1.841 albertel 6282:
6283: return $response;
1.1003 raeburn 6284: }
6285:
6286: sub auto_possible_instcodes {
1.1007 raeburn 6287: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6288: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6289: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6290: return;
6291: }
1.1003 raeburn 6292: my (@homeservers,$uhome);
6293: if (defined(&domain($domain,'primary'))) {
6294: $uhome=&domain($domain,'primary');
6295: push(@homeservers,&domain($domain,'primary'));
6296: } else {
6297: my %servers = &get_servers($domain,'library');
6298: foreach my $tryserver (keys(%servers)) {
6299: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6300: push(@homeservers,$tryserver);
6301: }
6302: }
6303: }
6304: my $response;
6305: foreach my $server (@homeservers) {
6306: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6307: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6308: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6309: split(':',$response);
6310: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6311: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6312: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6313: my ($name,$value)=split('=',$item);
6314: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6315: }
6316: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6317: my ($name,$value)=split('=',$item);
6318: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6319: }
6320: return 'ok';
6321: }
6322: return $response;
6323: }
1.792 raeburn 6324:
1.1010 raeburn 6325: sub auto_courserequest_checks {
6326: my ($dom) = @_;
1.1020 raeburn 6327: my ($homeserver,%validations);
6328: if ($dom =~ /^$match_domain$/) {
6329: $homeserver = &domain($dom,'primary');
6330: }
6331: unless ($homeserver eq 'no_host') {
6332: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6333: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6334: my @items = split(/&/,$response);
6335: foreach my $item (@items) {
6336: my ($key,$value) = split('=',$item);
6337: $validations{&unescape($key)} = &thaw_unescape($value);
6338: }
6339: }
6340: }
1.1010 raeburn 6341: return %validations;
6342: }
6343:
1.1020 raeburn 6344: sub auto_courserequest_validation {
6345: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6346: my ($homeserver,$response);
6347: if ($dom =~ /^$match_domain$/) {
6348: $homeserver = &domain($dom,'primary');
6349: }
6350: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6351:
1.1020 raeburn 6352: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6353: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6354: ':'.&escape($instcode).':'.&escape($instseclist),
6355: $homeserver));
6356: }
6357: return $response;
6358: }
6359:
1.777 albertel 6360: sub auto_validate_class_sec {
1.918 raeburn 6361: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6362: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6363: my $ownerlist;
6364: if (ref($owners) eq 'ARRAY') {
6365: $ownerlist = join(',',@{$owners});
6366: } else {
6367: $ownerlist = $owners;
6368: }
1.773 raeburn 6369: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6370: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6371: return $response;
6372: }
6373:
1.679 raeburn 6374: # ------------------------------------------------------- Course Group routines
6375:
6376: sub get_coursegroups {
1.809 raeburn 6377: my ($cdom,$cnum,$group,$namespace) = @_;
6378: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6379: }
6380:
1.679 raeburn 6381: sub modify_coursegroup {
6382: my ($cdom,$cnum,$groupsettings) = @_;
6383: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6384: }
6385:
1.809 raeburn 6386: sub toggle_coursegroup_status {
6387: my ($cdom,$cnum,$group,$action) = @_;
6388: my ($from_namespace,$to_namespace);
6389: if ($action eq 'delete') {
6390: $from_namespace = 'coursegroups';
6391: $to_namespace = 'deleted_groups';
6392: } else {
6393: $from_namespace = 'deleted_groups';
6394: $to_namespace = 'coursegroups';
6395: }
6396: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6397: if (my $tmp = &error(%curr_group)) {
6398: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6399: return ('read error',$tmp);
6400: } else {
6401: my %savedsettings = %curr_group;
1.809 raeburn 6402: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6403: my $deloutcome;
6404: if ($result eq 'ok') {
1.809 raeburn 6405: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6406: } else {
6407: return ('write error',$result);
6408: }
6409: if ($deloutcome eq 'ok') {
6410: return 'ok';
6411: } else {
6412: return ('delete error',$deloutcome);
6413: }
6414: }
6415: }
6416:
1.679 raeburn 6417: sub modify_group_roles {
1.957 raeburn 6418: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6419: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6420: my $role = 'gr/'.&escape($userprivs);
6421: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6422: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6423: if ($result eq 'ok') {
6424: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6425: }
1.679 raeburn 6426: return $result;
6427: }
6428:
6429: sub modify_coursegroup_membership {
6430: my ($cdom,$cnum,$membership) = @_;
6431: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6432: return $result;
6433: }
6434:
1.682 raeburn 6435: sub get_active_groups {
6436: my ($udom,$uname,$cdom,$cnum) = @_;
6437: my $now = time;
6438: my %groups = ();
6439: foreach my $key (keys(%env)) {
1.811 albertel 6440: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6441: my ($start,$end) = split(/\./,$env{$key});
6442: if (($end!=0) && ($end<$now)) { next; }
6443: if (($start!=0) && ($start>$now)) { next; }
6444: if ($1 eq $cdom && $2 eq $cnum) {
6445: $groups{$3} = $env{$key} ;
6446: }
6447: }
6448: }
6449: return %groups;
6450: }
6451:
1.683 raeburn 6452: sub get_group_membership {
6453: my ($cdom,$cnum,$group) = @_;
6454: return(&dump('groupmembership',$cdom,$cnum,$group));
6455: }
6456:
6457: sub get_users_groups {
6458: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6459: my @usersgroups;
1.683 raeburn 6460: my $cachetime=1800;
6461:
6462: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6463: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6464: if (defined($cached)) {
1.734 albertel 6465: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6466: } else {
6467: $grouplist = '';
1.816 raeburn 6468: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6469: my $extra = &freeze_escape({'skipcheck' => 1});
6470: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6471: my $access_end = $env{'course.'.$courseid.
6472: '.default_enrollment_end_date'};
6473: my $now = time;
6474: foreach my $key (keys(%roleshash)) {
6475: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6476: my $group = $1;
6477: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6478: my $start = $2;
6479: my $end = $1;
6480: if ($start == -1) { next; } # deleted from group
6481: if (($start!=0) && ($start>$now)) { next; }
6482: if (($end!=0) && ($end<$now)) {
6483: if ($access_end && $access_end < $now) {
6484: if ($access_end - $end < 86400) {
6485: push(@usersgroups,$group);
1.733 raeburn 6486: }
6487: }
1.817 raeburn 6488: next;
1.733 raeburn 6489: }
1.817 raeburn 6490: push(@usersgroups,$group);
1.683 raeburn 6491: }
6492: }
6493: }
1.817 raeburn 6494: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6495: $grouplist = join(':',@usersgroups);
6496: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6497: }
1.733 raeburn 6498: return @usersgroups;
1.683 raeburn 6499: }
6500:
6501: sub devalidate_getgroups_cache {
6502: my ($udom,$uname,$cdom,$cnum)=@_;
6503: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6504:
1.683 raeburn 6505: my $hashid="$udom:$uname:$courseid";
6506: &devalidate_cache_new('getgroups',$hashid);
6507: }
6508:
1.12 www 6509: # ------------------------------------------------------------------ Plain Text
6510:
6511: sub plaintext {
1.988 raeburn 6512: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6513: if ($short =~ m{^cr/}) {
1.758 albertel 6514: return (split('/',$short))[-1];
6515: }
1.742 raeburn 6516: if (!defined($cid)) {
6517: $cid = $env{'request.course.id'};
6518: }
6519: my %rolenames = (
1.1008 raeburn 6520: Course => 'std',
6521: Community => 'alt1',
1.742 raeburn 6522: );
1.1037 raeburn 6523: if ($cid ne '') {
6524: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6525: unless ($forcedefault) {
6526: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6527: &Apache::lonlocal::mt_escape(\$roletext);
6528: return &Apache::lonlocal::mt($roletext);
6529: }
6530: }
6531: }
6532: if ((defined($type)) && (defined($rolenames{$type})) &&
6533: (defined($rolenames{$type})) &&
6534: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6535: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6536: } elsif ($cid ne '') {
6537: my $crstype = $env{'course.'.$cid.'.type'};
6538: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6539: (defined($prp{$short}{$rolenames{$crstype}}))) {
6540: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6541: }
1.742 raeburn 6542: }
1.1037 raeburn 6543: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6544: }
6545:
6546: # ----------------------------------------------------------------- Assign Role
6547:
6548: sub assignrole {
1.957 raeburn 6549: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6550: $context)=@_;
1.21 www 6551: my $mrole;
6552: if ($role =~ /^cr\//) {
1.393 www 6553: my $cwosec=$url;
1.811 albertel 6554: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6555: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6556: my $refused = 1;
6557: if ($context eq 'requestcourses') {
6558: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6559: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6560: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6561: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6562: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6563: if ($crsenv{'internal.courseowner'} eq
6564: $env{'user.name'}.':'.$env{'user.domain'}) {
6565: $refused = '';
6566: }
6567: }
6568: }
6569: }
6570: }
6571: if ($refused) {
6572: &logthis('Refused custom assignrole: '.
6573: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6574: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6575: return 'refused';
6576: }
1.104 www 6577: }
1.21 www 6578: $mrole='cr';
1.678 raeburn 6579: } elsif ($role =~ /^gr\//) {
6580: my $cwogrp=$url;
1.811 albertel 6581: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6582: unless (&allowed('mdg',$cwogrp)) {
6583: &logthis('Refused group assignrole: '.
6584: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6585: $env{'user.name'}.' at '.$env{'user.domain'});
6586: return 'refused';
6587: }
6588: $mrole='gr';
1.21 www 6589: } else {
1.82 www 6590: my $cwosec=$url;
1.811 albertel 6591: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6592: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6593: my $refused;
6594: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6595: if (!(&allowed('c'.$role,$url))) {
6596: $refused = 1;
6597: }
6598: } else {
6599: $refused = 1;
6600: }
1.947 raeburn 6601: if ($refused) {
1.1045 raeburn 6602: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6603: if (!$selfenroll && $context eq 'course') {
6604: my %crsenv;
6605: if ($role eq 'cc' || $role eq 'co') {
6606: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6607: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6608: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6609: if ($crsenv{'internal.courseowner'} eq
6610: $env{'user.name'}.':'.$env{'user.domain'}) {
6611: $refused = '';
6612: }
6613: }
6614: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6615: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6616: if ($crsenv{'internal.courseowner'} eq
6617: $env{'user.name'}.':'.$env{'user.domain'}) {
6618: $refused = '';
6619: }
6620: }
6621: }
6622: }
6623: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6624: $refused = '';
1.1017 raeburn 6625: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6626: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6627: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6628: my $wrongcc;
6629: if ($cnum =~ /^$match_community$/) {
6630: $wrongcc = 1 if ($role eq 'cc');
6631: } else {
6632: $wrongcc = 1 if ($role eq 'co');
6633: }
6634: unless ($wrongcc) {
6635: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6636: if ($crsenv{'internal.courseowner'} eq
6637: $env{'user.name'}.':'.$env{'user.domain'}) {
6638: $refused = '';
6639: }
1.1017 raeburn 6640: }
6641: }
6642: }
6643: if ($refused) {
1.947 raeburn 6644: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6645: ' '.$role.' '.$end.' '.$start.' by '.
6646: $env{'user.name'}.' at '.$env{'user.domain'});
6647: return 'refused';
6648: }
1.932 raeburn 6649: }
1.104 www 6650: }
1.21 www 6651: $mrole=$role;
6652: }
1.620 albertel 6653: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6654: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6655: if ($end) { $command.='_'.$end; }
1.21 www 6656: if ($start) {
6657: if ($end) {
1.81 www 6658: $command.='_'.$start;
1.21 www 6659: } else {
1.81 www 6660: $command.='_0_'.$start;
1.21 www 6661: }
6662: }
1.739 raeburn 6663: my $origstart = $start;
6664: my $origend = $end;
1.957 raeburn 6665: my $delflag;
1.357 www 6666: # actually delete
6667: if ($deleteflag) {
1.373 www 6668: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6669: # modify command to delete the role
1.620 albertel 6670: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6671: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6672: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6673: # set start and finish to negative values for userrolelog
6674: $start=-1;
6675: $end=-1;
1.957 raeburn 6676: $delflag = 1;
1.357 www 6677: }
6678: }
6679: # send command
1.349 www 6680: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6681: # log new user role if status is ok
1.349 www 6682: if ($answer eq 'ok') {
1.663 raeburn 6683: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6684: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6685: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6686: unless ($role =~ /^gr/) {
6687: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6688: $origstart,$selfenroll,$context);
1.739 raeburn 6689: }
1.1053 raeburn 6690: if ($role eq 'cc') {
6691: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6692: }
1.349 www 6693: }
6694: return $answer;
1.169 harris41 6695: }
6696:
1.1053 raeburn 6697: sub autoupdate_coowners {
6698: my ($url,$end,$start,$uname,$udom) = @_;
6699: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6700: if (($cdom ne '') && ($cnum ne '')) {
6701: my $now = time;
6702: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6703: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6704: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6705: my $instcode = $coursehash{'internal.coursecode'};
6706: if ($instcode ne '') {
1.1056 raeburn 6707: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6708: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6709: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6710: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6711: if ($result eq 'valid') {
6712: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6713: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6714: push(@newcoowners,$coowner);
6715: }
6716: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6717: push(@newcoowners,$uname.':'.$udom);
6718: }
6719: @newcoowners = sort(@newcoowners);
6720: } else {
6721: push(@newcoowners,$uname.':'.$udom);
6722: }
6723: } else {
6724: if ($coursehash{'internal.co-owners'}) {
6725: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6726: unless ($coowner eq $uname.':'.$udom) {
6727: push(@newcoowners,$coowner);
6728: }
6729: }
6730: unless (@newcoowners > 0) {
6731: $delcoowners = 1;
6732: $coowners = '';
6733: }
6734: }
6735: }
6736: if (@newcoowners || $delcoowners) {
6737: &store_coowners($cdom,$cnum,$coursehash{'home'},
6738: $delcoowners,@newcoowners);
6739: }
6740: }
6741: }
6742: }
6743: }
6744: }
6745: }
6746:
6747: sub store_coowners {
6748: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6749: my $cid = $cdom.'_'.$cnum;
6750: my ($coowners,$delresult,$putresult);
6751: if (@newcoowners) {
6752: $coowners = join(',',@newcoowners);
6753: my %coownershash = (
6754: 'internal.co-owners' => $coowners,
6755: );
6756: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6757: if ($putresult eq 'ok') {
6758: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6759: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6760: }
6761: }
6762: }
6763: if ($delcoowners) {
6764: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6765: if ($delresult eq 'ok') {
6766: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6767: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6768: }
6769: }
6770: }
6771: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6772: my %crsinfo =
6773: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6774: if (ref($crsinfo{$cid}) eq 'HASH') {
6775: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6776: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6777: }
6778: }
6779: }
6780:
1.169 harris41 6781: # -------------------------------------------------- Modify user authentication
1.197 www 6782: # Overrides without validation
6783:
1.169 harris41 6784: sub modifyuserauth {
6785: my ($udom,$uname,$umode,$upass)=@_;
6786: my $uhome=&homeserver($uname,$udom);
1.197 www 6787: unless (&allowed('mau',$udom)) { return 'refused'; }
6788: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6789: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6790: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6791: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6792: &escape($upass),$uhome);
1.620 albertel 6793: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6794: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6795: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6796: &log($udom,,$uname,$uhome,
1.620 albertel 6797: 'Authentication changed by '.$env{'user.domain'}.', '.
6798: $env{'user.name'}.', '.$umode.
1.197 www 6799: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6800: unless ($reply eq 'ok') {
1.197 www 6801: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6802: return 'error: '.$reply;
6803: }
1.170 harris41 6804: return 'ok';
1.80 www 6805: }
6806:
1.81 www 6807: # --------------------------------------------------------------- Modify a user
1.80 www 6808:
1.81 www 6809: sub modifyuser {
1.206 matthew 6810: my ($udom, $uname, $uid,
6811: $umode, $upass, $first,
6812: $middle, $last, $gene,
1.1056.4.1 raeburn 6813: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6814: $udom= &LONCAPA::clean_domain($udom);
6815: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6816: my $showcandelete = 'none';
6817: if (ref($candelete) eq 'ARRAY') {
6818: if (@{$candelete} > 0) {
6819: $showcandelete = join(', ',@{$candelete});
6820: }
6821: }
1.81 www 6822: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6823: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6824: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6825: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6826: ' desiredhome not specified').
1.620 albertel 6827: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6828: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6829: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6830: my $newuser;
6831: if ($uhome eq 'no_host') {
6832: $newuser = 1;
6833: }
1.80 www 6834: # ----------------------------------------------------------------- Create User
1.406 albertel 6835: if (($uhome eq 'no_host') &&
6836: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6837: my $unhome='';
1.844 albertel 6838: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6839: $unhome = $desiredhome;
1.620 albertel 6840: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6841: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6842: } else { # load balancing routine for determining $unhome
1.81 www 6843: my $loadm=10000000;
1.841 albertel 6844: my %servers = &get_servers($udom,'library');
6845: foreach my $tryserver (keys(%servers)) {
6846: my $answer=reply('load',$tryserver);
6847: if (($answer=~/\d+/) && ($answer<$loadm)) {
6848: $loadm=$answer;
6849: $unhome=$tryserver;
6850: }
1.80 www 6851: }
6852: }
6853: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6854: return 'error: unable to find a home server for '.$uname.
6855: ' in domain '.$udom;
1.80 www 6856: }
6857: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6858: &escape($upass),$unhome);
6859: unless ($reply eq 'ok') {
6860: return 'error: '.$reply;
6861: }
1.230 stredwic 6862: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6863: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6864: return 'error: unable verify users home machine.';
1.80 www 6865: }
1.209 matthew 6866: } # End of creation of new user
1.80 www 6867: # ---------------------------------------------------------------------- Add ID
6868: if ($uid) {
6869: $uid=~tr/A-Z/a-z/;
6870: my %uidhash=&idrget($udom,$uname);
1.196 www 6871: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6872: && (!$forceid)) {
1.80 www 6873: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6874: return 'error: user id "'.$uid.'" does not match '.
6875: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6876: }
6877: } else {
6878: &idput($udom,($uname => $uid));
6879: }
6880: }
6881: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6882: my @tmp=&get('environment',
1.899 raeburn 6883: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6884: 'permanentemail','inststatus'],
1.134 albertel 6885: $udom,$uname);
1.1056.4.4 raeburn 6886: my (%names,%oldnames);
1.313 matthew 6887: if ($tmp[0] =~ m/^error:.*/) {
6888: %names=();
6889: } else {
6890: %names = @tmp;
1.1056.4.4 raeburn 6891: %oldnames = %names;
1.313 matthew 6892: }
1.1056.4.6 raeburn 6893: #
1.1056.4.1 raeburn 6894: # If name, email and/or uid are blank (e.g., because an uploaded file
6895: # of users did not contain them), do not overwrite existing values
6896: # unless field is in $candelete array ref.
6897: #
6898:
6899: my @fields = ('firstname','middlename','lastname','generation',
6900: 'permanentemail','id');
6901: my %newvalues;
6902: if (ref($candelete) eq 'ARRAY') {
6903: foreach my $field (@fields) {
6904: if (grep(/^\Q$field\E$/,@{$candelete})) {
6905: if ($field eq 'firstname') {
6906: $names{$field} = $first;
6907: } elsif ($field eq 'middlename') {
6908: $names{$field} = $middle;
6909: } elsif ($field eq 'lastname') {
6910: $names{$field} = $last;
6911: } elsif ($field eq 'generation') {
6912: $names{$field} = $gene;
6913: } elsif ($field eq 'permanentemail') {
6914: $names{$field} = $email;
6915: } elsif ($field eq 'id') {
6916: $names{$field} = $uid;
6917: }
6918: }
6919: }
6920: }
1.388 www 6921: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6922: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6923: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6924: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6925: if ($email) {
6926: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6927: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6928: }
1.899 raeburn 6929: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6930: if (defined($inststatus)) {
6931: $names{'inststatus'} = '';
6932: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6933: if (ref($usertypes) eq 'HASH') {
6934: my @okstatuses;
6935: foreach my $item (split(/:/,$inststatus)) {
6936: if (defined($usertypes->{$item})) {
6937: push(@okstatuses,$item);
6938: }
6939: }
6940: if (@okstatuses) {
6941: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6942: }
6943: }
6944: }
1.1056.4.4 raeburn 6945: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6946: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 6947: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6948: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6949: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6950: } else {
6951: $logmsg .= ' during self creation';
6952: }
1.1056.4.4 raeburn 6953: my $changed;
6954: if ($newuser) {
6955: $changed = 1;
6956: } else {
6957: foreach my $field (@fields) {
6958: if ($names{$field} ne $oldnames{$field}) {
6959: $changed = 1;
6960: last;
6961: }
6962: }
6963: }
6964: unless ($changed) {
6965: $logmsg = 'No changes in user information needed for: '.$logmsg;
6966: &logthis($logmsg);
6967: return 'ok';
6968: }
6969: my $reply = &put('environment', \%names, $udom,$uname);
6970: if ($reply ne 'ok') {
6971: return 'error: '.$reply;
6972: }
1.1056.4.11! raeburn 6973: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
! 6974: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
! 6975: }
1.1056.4.4 raeburn 6976: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6977: &devalidate_cache_new('namescache',$uname.':'.$udom);
6978: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6979: &logthis($logmsg);
1.134 albertel 6980: return 'ok';
1.80 www 6981: }
6982:
1.81 www 6983: # -------------------------------------------------------------- Modify student
1.80 www 6984:
1.81 www 6985: sub modifystudent {
6986: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6987: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6988: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6989: if (!$cid) {
1.620 albertel 6990: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6991: return 'not_in_class';
6992: }
1.80 www 6993: }
6994: # --------------------------------------------------------------- Make the user
1.81 www 6995: my $reply=&modifyuser
1.209 matthew 6996: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6997: $desiredhome,$email,$inststatus);
1.80 www 6998: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6999: # This will cause &modify_student_enrollment to get the uid from the
7000: # students environment
7001: $uid = undef if (!$forceid);
1.455 albertel 7002: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7003: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7004: return $reply;
7005: }
7006:
7007: sub modify_student_enrollment {
1.957 raeburn 7008: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7009: my ($cdom,$cnum,$chome);
7010: if (!$cid) {
1.620 albertel 7011: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7012: return 'not_in_class';
7013: }
1.620 albertel 7014: $cdom=$env{'course.'.$cid.'.domain'};
7015: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7016: } else {
7017: ($cdom,$cnum)=split(/_/,$cid);
7018: }
1.620 albertel 7019: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7020: if (!$chome) {
1.457 raeburn 7021: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7022: }
1.455 albertel 7023: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7024: # Make sure the user exists
1.81 www 7025: my $uhome=&homeserver($uname,$udom);
7026: if (($uhome eq '') || ($uhome eq 'no_host')) {
7027: return 'error: no such user';
7028: }
1.297 matthew 7029: # Get student data if we were not given enough information
7030: if (!defined($first) || $first eq '' ||
7031: !defined($last) || $last eq '' ||
7032: !defined($uid) || $uid eq '' ||
7033: !defined($middle) || $middle eq '' ||
7034: !defined($gene) || $gene eq '') {
1.294 matthew 7035: # They did not supply us with enough data to enroll the student, so
7036: # we need to pick up more information.
1.297 matthew 7037: my %tmp = &get('environment',
1.294 matthew 7038: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7039: ,$udom,$uname);
7040:
1.800 albertel 7041: #foreach my $key (keys(%tmp)) {
7042: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7043: #}
1.294 matthew 7044: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7045: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7046: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7047: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7048: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7049: }
1.556 albertel 7050: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7051: my $reply=cput('classlist',
7052: {"$uname:$udom" =>
1.515 raeburn 7053: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7054: $cdom,$cnum);
1.81 www 7055: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7056: return 'error: '.$reply;
1.652 albertel 7057: } else {
7058: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7059: }
1.297 matthew 7060: # Add student role to user
1.83 www 7061: my $uurl='/'.$cid;
1.81 www 7062: $uurl=~s/\_/\//g;
7063: if ($usec) {
7064: $uurl.='/'.$usec;
7065: }
1.957 raeburn 7066: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7067: }
7068:
1.556 albertel 7069: sub format_name {
7070: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7071: my $name;
7072: if ($first ne 'lastname') {
7073: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7074: } else {
7075: if ($lastname=~/\S/) {
7076: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7077: $name=~s/\s+,/,/;
7078: } else {
7079: $name.= $firstname.' '.$middlename.' '.$generation;
7080: }
7081: }
7082: $name=~s/^\s+//;
7083: $name=~s/\s+$//;
7084: $name=~s/\s+/ /g;
7085: return $name;
7086: }
7087:
1.84 www 7088: # ------------------------------------------------- Write to course preferences
7089:
7090: sub writecoursepref {
7091: my ($courseid,%prefs)=@_;
7092: $courseid=~s/^\///;
7093: $courseid=~s/\_/\//g;
7094: my ($cdomain,$cnum)=split(/\//,$courseid);
7095: my $chome=homeserver($cnum,$cdomain);
7096: if (($chome eq '') || ($chome eq 'no_host')) {
7097: return 'error: no such course';
7098: }
7099: my $cstring='';
1.800 albertel 7100: foreach my $pref (keys(%prefs)) {
7101: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7102: }
1.84 www 7103: $cstring=~s/\&$//;
7104: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7105: }
7106:
7107: # ---------------------------------------------------------- Make/modify course
7108:
7109: sub createcourse {
1.741 raeburn 7110: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7111: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7112: $url=&declutter($url);
7113: my $cid='';
1.1028 raeburn 7114: if ($context eq 'requestcourses') {
7115: my $can_create = 0;
7116: my ($ownername,$ownerdom) = split(':',$course_owner);
7117: if ($udom eq $ownerdom) {
7118: if (&usertools_access($ownername,$ownerdom,$category,undef,
7119: $context)) {
7120: $can_create = 1;
7121: }
7122: } else {
7123: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7124: $category);
7125: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7126: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7127: if (@curr > 0) {
7128: my @options = qw(approval validate autolimit);
7129: my $optregex = join('|',@options);
7130: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7131: $can_create = 1;
7132: }
7133: }
7134: }
7135: }
7136: if ($can_create) {
7137: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7138: unless (&allowed('ccc',$udom)) {
7139: return 'refused';
7140: }
1.1017 raeburn 7141: }
7142: } else {
7143: return 'refused';
7144: }
1.1028 raeburn 7145: } elsif (!&allowed('ccc',$udom)) {
7146: return 'refused';
1.84 www 7147: }
1.1011 raeburn 7148: # --------------------------------------------------------------- Get Unique ID
7149: my $uname;
7150: if ($cnum =~ /^$match_courseid$/) {
7151: my $chome=&homeserver($cnum,$udom,'true');
7152: if (($chome eq '') || ($chome eq 'no_host')) {
7153: $uname = $cnum;
7154: } else {
1.1038 raeburn 7155: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7156: }
7157: } else {
1.1038 raeburn 7158: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7159: }
7160: return $uname if ($uname =~ /^error/);
7161: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7162: if (!defined($course_server)) {
7163: if (defined(&domain($udom,'primary'))) {
7164: $course_server = &domain($udom,'primary');
7165: } else {
7166: $course_server = $env{'user.home'};
7167: }
7168: }
7169: my %host_servers =
7170: &Apache::lonnet::get_servers($udom,'library');
7171: unless ($host_servers{$course_server}) {
7172: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7173: }
1.84 www 7174: # ------------------------------------------------------------- Make the course
7175: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7176: $course_server);
1.84 www 7177: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7178: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7179: if (($uhome eq '') || ($uhome eq 'no_host')) {
7180: return 'error: no such course';
7181: }
1.271 www 7182: # ----------------------------------------------------------------- Course made
1.516 raeburn 7183: # log existence
1.1029 raeburn 7184: my $now = time;
1.918 raeburn 7185: my $newcourse = {
7186: $udom.'_'.$uname => {
1.921 raeburn 7187: description => $description,
7188: inst_code => $inst_code,
7189: owner => $course_owner,
7190: type => $crstype,
1.1029 raeburn 7191: creator => $env{'user.name'}.':'.
7192: $env{'user.domain'},
7193: created => $now,
7194: context => $context,
1.918 raeburn 7195: },
7196: };
1.921 raeburn 7197: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7198: # set toplevel url
1.271 www 7199: my $topurl=$url;
7200: unless ($nonstandard) {
7201: # ------------------------------------------ For standard courses, make top url
7202: my $mapurl=&clutter($url);
1.278 www 7203: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7204: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7205: <map>
7206: <resource id="1" type="start"></resource>
7207: <resource id="2" src="$mapurl"></resource>
7208: <resource id="3" type="finish"></resource>
7209: <link index="1" from="1" to="2"></link>
7210: <link index="2" from="2" to="3"></link>
7211: </map>
7212: ENDINITMAP
7213: $topurl=&declutter(
1.638 albertel 7214: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7215: );
7216: }
7217: # ----------------------------------------------------------- Write preferences
1.84 www 7218: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7219: ('description' => $description,
7220: 'url' => $topurl,
7221: 'internal.creator' => $env{'user.name'}.':'.
7222: $env{'user.domain'},
7223: 'internal.created' => $now,
7224: 'internal.creationcontext' => $context)
7225: );
1.84 www 7226: return '/'.$udom.'/'.$uname;
7227: }
7228:
1.1011 raeburn 7229: # ------------------------------------------------------------------- Create ID
7230: sub generate_coursenum {
1.1038 raeburn 7231: my ($udom,$crstype) = @_;
1.1011 raeburn 7232: my $domdesc = &domain($udom);
7233: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7234: my $first;
7235: if ($crstype eq 'Community') {
7236: $first = '0';
7237: } else {
7238: $first = int(1+rand(9));
7239: }
7240: my $uname=$first.
1.1011 raeburn 7241: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7242: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7243: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7244: # ----------------------------------------------- Make sure that does not exist
7245: my $uhome=&homeserver($uname,$udom,'true');
7246: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7247: if ($crstype eq 'Community') {
7248: $first = '0';
7249: } else {
7250: $first = int(1+rand(9));
7251: }
7252: $uname=$first.
1.1011 raeburn 7253: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7254: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7255: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7256: $uhome=&homeserver($uname,$udom,'true');
7257: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7258: return 'error: unable to generate unique course-ID';
7259: }
7260: }
7261: return $uname;
7262: }
7263:
1.813 albertel 7264: sub is_course {
7265: my ($cdom,$cnum) = @_;
7266: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7267: undef,'.');
1.813 albertel 7268: if (exists($courses{$cdom.'_'.$cnum})) {
7269: return 1;
7270: }
7271: return 0;
7272: }
7273:
1.1015 raeburn 7274: sub store_userdata {
7275: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7276: my $result;
1.1016 raeburn 7277: if ($datakey ne '') {
1.1013 raeburn 7278: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7279: if ($udom eq '' || $uname eq '') {
7280: $udom = $env{'user.domain'};
7281: $uname = $env{'user.name'};
7282: }
7283: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7284: if (($uhome eq '') || ($uhome eq 'no_host')) {
7285: $result = 'error: no_host';
7286: } else {
7287: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7288: $storehash->{'host'} = $perlvar{'lonHostID'};
7289:
7290: my $namevalue='';
7291: foreach my $key (keys(%{$storehash})) {
7292: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7293: }
7294: $namevalue=~s/\&$//;
7295: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7296: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7297: }
7298: } else {
7299: $result = 'error: data to store was not a hash reference';
7300: }
7301: } else {
7302: $result= 'error: invalid requestkey';
7303: }
7304: return $result;
7305: }
7306:
1.21 www 7307: # ---------------------------------------------------------- Assign Custom Role
7308:
7309: sub assigncustomrole {
1.957 raeburn 7310: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7311: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7312: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7313: }
7314:
7315: # ----------------------------------------------------------------- Revoke Role
7316:
7317: sub revokerole {
1.957 raeburn 7318: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7319: my $now=time;
1.965 raeburn 7320: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7321: }
7322:
7323: # ---------------------------------------------------------- Revoke Custom Role
7324:
7325: sub revokecustomrole {
1.957 raeburn 7326: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7327: my $now=time;
1.357 www 7328: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7329: $deleteflag,$selfenroll,$context);
1.17 www 7330: }
7331:
1.533 banghart 7332: # ------------------------------------------------------------ Disk usage
1.535 albertel 7333: sub diskusage {
1.955 raeburn 7334: my ($udom,$uname,$directorypath,$getpropath)=@_;
7335: $directorypath =~ s/\/$//;
7336: my $listing=&reply('du2:'.&escape($directorypath).':'
7337: .&escape($getpropath).':'.&escape($uname).':'
7338: .&escape($udom),homeserver($uname,$udom));
7339: if ($listing eq 'unknown_cmd') {
7340: if ($getpropath) {
7341: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7342: }
7343: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7344: }
1.514 albertel 7345: return $listing;
1.512 banghart 7346: }
7347:
1.566 banghart 7348: sub is_locked {
7349: my ($file_name, $domain, $user) = @_;
7350: my @check;
7351: my $is_locked;
7352: push @check, $file_name;
1.613 albertel 7353: my %locked = &get('file_permissions',\@check,
1.620 albertel 7354: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7355: my ($tmp)=keys(%locked);
7356: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7357:
1.566 banghart 7358: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7359: $is_locked = 'false';
7360: foreach my $entry (@{$locked{$file_name}}) {
7361: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7362: $is_locked = 'true';
7363: last;
1.745 raeburn 7364: }
7365: }
1.566 banghart 7366: } else {
7367: $is_locked = 'false';
7368: }
7369: }
7370:
1.759 albertel 7371: sub declutter_portfile {
7372: my ($file) = @_;
1.833 albertel 7373: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7374: return $file;
7375: }
7376:
1.559 banghart 7377: # ------------------------------------------------------------- Mark as Read Only
7378:
7379: sub mark_as_readonly {
7380: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7381: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7382: my ($tmp)=keys(%current_permissions);
7383: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7384: foreach my $file (@{$files}) {
1.759 albertel 7385: $file = &declutter_portfile($file);
1.561 banghart 7386: push(@{$current_permissions{$file}},$what);
1.559 banghart 7387: }
1.613 albertel 7388: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7389: return;
7390: }
7391:
1.572 banghart 7392: # ------------------------------------------------------------Save Selected Files
7393:
7394: sub save_selected_files {
7395: my ($user, $path, @files) = @_;
7396: my $filename = $user."savedfiles";
1.573 banghart 7397: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7398: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7399: foreach my $file (@files) {
1.620 albertel 7400: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7401: }
7402: foreach my $file (@other_files) {
1.574 banghart 7403: print (OUT $file."\n");
1.572 banghart 7404: }
1.574 banghart 7405: close (OUT);
1.572 banghart 7406: return 'ok';
7407: }
7408:
1.574 banghart 7409: sub clear_selected_files {
7410: my ($user) = @_;
7411: my $filename = $user."savedfiles";
7412: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7413: print (OUT undef);
7414: close (OUT);
7415: return ("ok");
7416: }
7417:
1.572 banghart 7418: sub files_in_path {
7419: my ($user, $path) = @_;
7420: my $filename = $user."savedfiles";
7421: my %return_files;
1.574 banghart 7422: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7423: while (my $line_in = <IN>) {
1.574 banghart 7424: chomp ($line_in);
7425: my @paths_and_file = split (m!/!, $line_in);
7426: my $file_part = pop (@paths_and_file);
7427: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7428: $path_part.='/';
7429: my $path_and_file = $path_part.$file_part;
7430: if ($path_part eq $path) {
7431: $return_files{$file_part}= 'selected';
7432: }
7433: }
1.574 banghart 7434: close (IN);
7435: return (\%return_files);
1.572 banghart 7436: }
7437:
7438: # called in portfolio select mode, to show files selected NOT in current directory
7439: sub files_not_in_path {
7440: my ($user, $path) = @_;
7441: my $filename = $user."savedfiles";
7442: my @return_files;
7443: my $path_part;
1.800 albertel 7444: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7445: while (my $line = <IN>) {
1.572 banghart 7446: #ok, I know it's clunky, but I want it to work
1.800 albertel 7447: my @paths_and_file = split(m|/|, $line);
7448: my $file_part = pop(@paths_and_file);
7449: chomp($file_part);
7450: my $path_part = join('/', @paths_and_file);
1.572 banghart 7451: $path_part .= '/';
7452: my $path_and_file = $path_part.$file_part;
7453: if ($path_part ne $path) {
1.800 albertel 7454: push(@return_files, ($path_and_file));
1.572 banghart 7455: }
7456: }
1.800 albertel 7457: close(OUT);
1.574 banghart 7458: return (@return_files);
1.572 banghart 7459: }
7460:
1.745 raeburn 7461: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7462:
1.745 raeburn 7463: sub get_portfile_permissions {
7464: my ($domain,$user) = @_;
1.613 albertel 7465: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7466: my ($tmp)=keys(%current_permissions);
7467: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7468: return \%current_permissions;
7469: }
7470:
7471: #---------------------------------------------Get portfolio file access controls
7472:
1.749 raeburn 7473: sub get_access_controls {
1.745 raeburn 7474: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7475: my %access;
7476: my $real_file = $file;
7477: $file =~ s/\.meta$//;
1.745 raeburn 7478: if (defined($file)) {
1.749 raeburn 7479: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7480: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7481: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7482: }
7483: }
1.745 raeburn 7484: } else {
1.749 raeburn 7485: foreach my $key (keys(%{$current_permissions})) {
7486: if ($key =~ /\0accesscontrol$/) {
7487: if (defined($group)) {
7488: if ($key !~ m-^\Q$group\E/-) {
7489: next;
7490: }
7491: }
7492: my ($fullpath) = split(/\0/,$key);
7493: if (ref($$current_permissions{$key}) eq 'HASH') {
7494: foreach my $control (keys(%{$$current_permissions{$key}})) {
7495: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7496: }
7497: }
7498: }
7499: }
7500: }
7501: return %access;
7502: }
7503:
7504: sub modify_access_controls {
7505: my ($file_name,$changes,$domain,$user)=@_;
7506: my ($outcome,$deloutcome);
7507: my %store_permissions;
7508: my %new_values;
7509: my %new_control;
7510: my %translation;
7511: my @deletions = ();
7512: my $now = time;
7513: if (exists($$changes{'activate'})) {
7514: if (ref($$changes{'activate'}) eq 'HASH') {
7515: my @newitems = sort(keys(%{$$changes{'activate'}}));
7516: my $numnew = scalar(@newitems);
7517: for (my $i=0; $i<$numnew; $i++) {
7518: my $newkey = $newitems[$i];
7519: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7520: if ($newkey =~ /^\d+:/) {
7521: $newkey =~ s/^(\d+)/$newid/;
7522: $translation{$1} = $newid;
7523: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7524: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7525: $translation{$1} = $newid;
7526: }
1.749 raeburn 7527: $new_values{$file_name."\0".$newkey} =
7528: $$changes{'activate'}{$newitems[$i]};
7529: $new_control{$newkey} = $now;
7530: }
7531: }
7532: }
7533: my %todelete;
7534: my %changed_items;
7535: foreach my $action ('delete','update') {
7536: if (exists($$changes{$action})) {
7537: if (ref($$changes{$action}) eq 'HASH') {
7538: foreach my $key (keys(%{$$changes{$action}})) {
7539: my ($itemnum) = ($key =~ /^([^:]+):/);
7540: if ($action eq 'delete') {
7541: $todelete{$itemnum} = 1;
7542: } else {
7543: $changed_items{$itemnum} = $key;
7544: }
7545: }
1.745 raeburn 7546: }
7547: }
1.749 raeburn 7548: }
7549: # get lock on access controls for file.
7550: my $lockhash = {
7551: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7552: ':'.$env{'user.domain'},
7553: };
7554: my $tries = 0;
7555: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7556:
7557: while (($gotlock ne 'ok') && $tries <3) {
7558: $tries ++;
7559: sleep 1;
7560: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7561: }
7562: if ($gotlock eq 'ok') {
7563: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7564: my ($tmp)=keys(%curr_permissions);
7565: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7566: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7567: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7568: if (ref($curr_controls) eq 'HASH') {
7569: foreach my $control_item (keys(%{$curr_controls})) {
7570: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7571: if (defined($todelete{$itemnum})) {
7572: push(@deletions,$file_name."\0".$control_item);
7573: } else {
7574: if (defined($changed_items{$itemnum})) {
7575: $new_control{$changed_items{$itemnum}} = $now;
7576: push(@deletions,$file_name."\0".$control_item);
7577: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7578: } else {
7579: $new_control{$control_item} = $$curr_controls{$control_item};
7580: }
7581: }
1.745 raeburn 7582: }
7583: }
7584: }
1.970 raeburn 7585: my ($group);
7586: if (&is_course($domain,$user)) {
7587: ($group,my $file) = split(/\//,$file_name,2);
7588: }
1.749 raeburn 7589: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7590: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7591: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7592: # remove lock
7593: my @del_lock = ($file_name."\0".'locked_access_records');
7594: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7595: my $sqlresult =
1.970 raeburn 7596: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7597: $group);
1.749 raeburn 7598: } else {
7599: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7600: }
1.749 raeburn 7601: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7602: }
7603:
1.827 raeburn 7604: sub make_public_indefinitely {
7605: my ($requrl) = @_;
7606: my $now = time;
7607: my $action = 'activate';
7608: my $aclnum = 0;
7609: if (&is_portfolio_url($requrl)) {
7610: my (undef,$udom,$unum,$file_name,$group) =
7611: &parse_portfolio_url($requrl);
7612: my $current_perms = &get_portfile_permissions($udom,$unum);
7613: my %access_controls = &get_access_controls($current_perms,
7614: $group,$file_name);
7615: foreach my $key (keys(%{$access_controls{$file_name}})) {
7616: my ($num,$scope,$end,$start) =
7617: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7618: if ($scope eq 'public') {
7619: if ($start <= $now && $end == 0) {
7620: $action = 'none';
7621: } else {
7622: $action = 'update';
7623: $aclnum = $num;
7624: }
7625: last;
7626: }
7627: }
7628: if ($action eq 'none') {
7629: return 'ok';
7630: } else {
7631: my %changes;
7632: my $newend = 0;
7633: my $newstart = $now;
7634: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7635: $changes{$action}{$newkey} = {
7636: type => 'public',
7637: time => {
7638: start => $newstart,
7639: end => $newend,
7640: },
7641: };
7642: my ($outcome,$deloutcome,$new_values,$translation) =
7643: &modify_access_controls($file_name,\%changes,$udom,$unum);
7644: return $outcome;
7645: }
7646: } else {
7647: return 'invalid';
7648: }
7649: }
7650:
1.745 raeburn 7651: #------------------------------------------------------Get Marked as Read Only
7652:
7653: sub get_marked_as_readonly {
7654: my ($domain,$user,$what,$group) = @_;
7655: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7656: my @readonly_files;
1.629 banghart 7657: my $cmp1=$what;
7658: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7659: while (my ($file_name,$value) = each(%{$current_permissions})) {
7660: if (defined($group)) {
7661: if ($file_name !~ m-^\Q$group\E/-) {
7662: next;
7663: }
7664: }
1.561 banghart 7665: if (ref($value) eq "ARRAY"){
7666: foreach my $stored_what (@{$value}) {
1.629 banghart 7667: my $cmp2=$stored_what;
1.759 albertel 7668: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7669: $cmp2=join('',@{$stored_what});
1.745 raeburn 7670: }
1.629 banghart 7671: if ($cmp1 eq $cmp2) {
1.561 banghart 7672: push(@readonly_files, $file_name);
1.745 raeburn 7673: last;
1.563 banghart 7674: } elsif (!defined($what)) {
7675: push(@readonly_files, $file_name);
1.745 raeburn 7676: last;
1.561 banghart 7677: }
7678: }
1.745 raeburn 7679: }
1.561 banghart 7680: }
7681: return @readonly_files;
7682: }
1.577 banghart 7683: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7684:
1.577 banghart 7685: sub get_marked_as_readonly_hash {
1.745 raeburn 7686: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7687: my %readonly_files;
1.745 raeburn 7688: while (my ($file_name,$value) = each(%{$current_permissions})) {
7689: if (defined($group)) {
7690: if ($file_name !~ m-^\Q$group\E/-) {
7691: next;
7692: }
7693: }
1.577 banghart 7694: if (ref($value) eq "ARRAY"){
7695: foreach my $stored_what (@{$value}) {
1.745 raeburn 7696: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7697: foreach my $lock_descriptor(@{$stored_what}) {
7698: if ($lock_descriptor eq 'graded') {
7699: $readonly_files{$file_name} = 'graded';
7700: } elsif ($lock_descriptor eq 'handback') {
7701: $readonly_files{$file_name} = 'handback';
7702: } else {
7703: if (!exists($readonly_files{$file_name})) {
7704: $readonly_files{$file_name} = 'locked';
7705: }
7706: }
1.745 raeburn 7707: }
1.750 banghart 7708: }
1.577 banghart 7709: }
7710: }
7711: }
7712: return %readonly_files;
7713: }
1.559 banghart 7714: # ------------------------------------------------------------ Unmark as Read Only
7715:
7716: sub unmark_as_readonly {
1.629 banghart 7717: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7718: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7719: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7720: $file_name = &declutter_portfile($file_name);
1.634 albertel 7721: my $symb_crs = $what;
7722: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7723: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7724: my ($tmp)=keys(%current_permissions);
7725: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7726: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7727: foreach my $file (@readonly_files) {
1.759 albertel 7728: my $clean_file = &declutter_portfile($file);
7729: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7730: my $current_locks = $current_permissions{$file};
1.563 banghart 7731: my @new_locks;
7732: my @del_keys;
7733: if (ref($current_locks) eq "ARRAY"){
7734: foreach my $locker (@{$current_locks}) {
1.632 albertel 7735: my $compare=$locker;
1.749 raeburn 7736: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7737: $compare=join('',@{$locker});
1.746 raeburn 7738: if ($compare ne $symb_crs) {
7739: push(@new_locks, $locker);
7740: }
1.563 banghart 7741: }
7742: }
1.650 albertel 7743: if (scalar(@new_locks) > 0) {
1.563 banghart 7744: $current_permissions{$file} = \@new_locks;
7745: } else {
7746: push(@del_keys, $file);
1.613 albertel 7747: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7748: delete($current_permissions{$file});
1.563 banghart 7749: }
7750: }
1.561 banghart 7751: }
1.613 albertel 7752: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7753: return;
7754: }
1.512 banghart 7755:
1.17 www 7756: # ------------------------------------------------------------ Directory lister
7757:
7758: sub dirlist {
1.955 raeburn 7759: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7760: $uri=~s/^\///;
7761: $uri=~s/\/$//;
1.253 stredwic 7762: my ($udom, $uname);
1.955 raeburn 7763: if ($getuserdir) {
1.253 stredwic 7764: $udom = $userdomain;
7765: $uname = $username;
1.955 raeburn 7766: } else {
7767: (undef,$udom,$uname)=split(/\//,$uri);
7768: if(defined($userdomain)) {
7769: $udom = $userdomain;
7770: }
7771: if(defined($username)) {
7772: $uname = $username;
7773: }
1.253 stredwic 7774: }
1.955 raeburn 7775: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7776:
1.955 raeburn 7777: $dirRoot = $perlvar{'lonDocRoot'};
7778: if (defined($getpropath)) {
7779: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7780: $dirRoot =~ s/\/$//;
1.955 raeburn 7781: } elsif (defined($getuserdir)) {
7782: my $subdir=$uname.'__';
7783: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7784: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7785: ."/$udom/$subdir/$uname";
7786: } elsif (defined($alternateRoot)) {
7787: $dirRoot = $alternateRoot;
1.751 banghart 7788: }
1.253 stredwic 7789:
7790: if($udom) {
7791: if($uname) {
1.955 raeburn 7792: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7793: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7794: .':'.&escape($uname).':'.&escape($udom),
7795: &homeserver($uname,$udom));
7796: if ($listing eq 'unknown_cmd') {
7797: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7798: &homeserver($uname,$udom));
7799: } else {
7800: @listing_results = map { &unescape($_); } split(/:/,$listing);
7801: }
1.605 matthew 7802: if ($listing eq 'unknown_cmd') {
1.800 albertel 7803: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7804: &homeserver($uname,$udom));
1.605 matthew 7805: @listing_results = split(/:/,$listing);
7806: } else {
7807: @listing_results = map { &unescape($_); } split(/:/,$listing);
7808: }
7809: return @listing_results;
1.955 raeburn 7810: } elsif(!$alternateRoot) {
1.800 albertel 7811: my %allusers;
1.841 albertel 7812: my %servers = &get_servers($udom,'library');
1.955 raeburn 7813: foreach my $tryserver (keys(%servers)) {
7814: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7815: &escape($udom),$tryserver);
7816: if ($listing eq 'unknown_cmd') {
7817: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7818: $udom, $tryserver);
7819: } else {
7820: @listing_results = map { &unescape($_); } split(/:/,$listing);
7821: }
1.841 albertel 7822: if ($listing eq 'unknown_cmd') {
7823: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7824: $udom, $tryserver);
7825: @listing_results = split(/:/,$listing);
7826: } else {
7827: @listing_results =
7828: map { &unescape($_); } split(/:/,$listing);
7829: }
7830: if ($listing_results[0] ne 'no_such_dir' &&
7831: $listing_results[0] ne 'empty' &&
7832: $listing_results[0] ne 'con_lost') {
7833: foreach my $line (@listing_results) {
7834: my ($entry) = split(/&/,$line,2);
7835: $allusers{$entry} = 1;
7836: }
7837: }
1.253 stredwic 7838: }
7839: my $alluserstr='';
1.800 albertel 7840: foreach my $user (sort(keys(%allusers))) {
7841: $alluserstr.=$user.'&user:';
1.253 stredwic 7842: }
7843: $alluserstr=~s/:$//;
7844: return split(/:/,$alluserstr);
7845: } else {
1.800 albertel 7846: return ('missing user name');
1.253 stredwic 7847: }
1.955 raeburn 7848: } elsif(!defined($getpropath)) {
1.841 albertel 7849: my @all_domains = sort(&all_domains());
1.955 raeburn 7850: foreach my $domain (@all_domains) {
7851: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7852: }
7853: return @all_domains;
7854: } else {
1.800 albertel 7855: return ('missing domain');
1.275 stredwic 7856: }
7857: }
7858:
7859: # --------------------------------------------- GetFileTimestamp
7860: # This function utilizes dirlist and returns the date stamp for
7861: # when it was last modified. It will also return an error of -1
7862: # if an error occurs
7863:
7864: sub GetFileTimestamp {
1.955 raeburn 7865: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7866: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7867: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7868: my ($fileStat) =
7869: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7870: undef,$getuserdir);
1.275 stredwic 7871: my @stats = split('&', $fileStat);
7872: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7873: # @stats contains first the filename, then the stat output
7874: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7875: } else {
7876: return -1;
1.253 stredwic 7877: }
1.26 www 7878: }
7879:
1.712 albertel 7880: sub stat_file {
7881: my ($uri) = @_;
1.787 albertel 7882: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7883:
1.955 raeburn 7884: my ($udom,$uname,$file);
1.712 albertel 7885: if ($uri =~ m-^/(uploaded|editupload)/-) {
7886: ($udom,$uname,$file) =
1.811 albertel 7887: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7888: $file = 'userfiles/'.$file;
7889: }
7890: if ($uri =~ m-^/res/-) {
7891: ($udom,$uname) =
1.807 albertel 7892: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7893: $file = $uri;
7894: }
7895:
7896: if (!$udom || !$uname || !$file) {
7897: # unable to handle the uri
7898: return ();
7899: }
1.956 raeburn 7900: my $getpropath;
7901: if ($file =~ /^userfiles\//) {
7902: $getpropath = 1;
7903: }
1.955 raeburn 7904: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7905: my @stats = split('&', $result);
1.721 banghart 7906:
1.712 albertel 7907: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7908: shift(@stats); #filename is first
7909: return @stats;
7910: }
7911: return ();
7912: }
7913:
1.26 www 7914: # -------------------------------------------------------- Value of a Condition
7915:
1.713 albertel 7916: # gets the value of a specific preevaluated condition
7917: # stored in the string $env{user.state.<cid>}
7918: # or looks up a condition reference in the bighash and if if hasn't
7919: # already been evaluated recurses into docondval to get the value of
7920: # the condition, then memoizing it to
7921: # $env{user.state.<cid>.<condition>}
1.40 www 7922: sub directcondval {
7923: my $number=shift;
1.620 albertel 7924: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7925: &Apache::lonuserstate::evalstate();
7926: }
1.713 albertel 7927: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7928: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7929: } elsif ($number =~ /^_/) {
7930: my $sub_condition;
7931: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7932: &GDBM_READER(),0640)) {
7933: $sub_condition=$bighash{'conditions'.$number};
7934: untie(%bighash);
7935: }
7936: my $value = &docondval($sub_condition);
1.949 raeburn 7937: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7938: return $value;
7939: }
1.620 albertel 7940: if ($env{'user.state.'.$env{'request.course.id'}}) {
7941: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7942: } else {
7943: return 2;
7944: }
7945: }
7946:
1.713 albertel 7947: # get the collection of conditions for this resource
1.26 www 7948: sub condval {
7949: my $condidx=shift;
1.54 www 7950: my $allpathcond='';
1.713 albertel 7951: foreach my $cond (split(/\|/,$condidx)) {
7952: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7953: $allpathcond.=
7954: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7955: }
1.191 harris41 7956: }
1.54 www 7957: $allpathcond=~s/\|$//;
1.713 albertel 7958: return &docondval($allpathcond);
7959: }
7960:
7961: #evaluates an expression of conditions
7962: sub docondval {
7963: my ($allpathcond) = @_;
7964: my $result=0;
7965: if ($env{'request.course.id'}
7966: && defined($allpathcond)) {
7967: my $operand='|';
7968: my @stack;
7969: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7970: if ($chunk eq '(') {
7971: push @stack,($operand,$result);
7972: } elsif ($chunk eq ')') {
7973: my $before=pop @stack;
7974: if (pop @stack eq '&') {
7975: $result=$result>$before?$before:$result;
7976: } else {
7977: $result=$result>$before?$result:$before;
7978: }
7979: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7980: $operand=$chunk;
7981: } else {
7982: my $new=directcondval($chunk);
7983: if ($operand eq '&') {
7984: $result=$result>$new?$new:$result;
7985: } else {
7986: $result=$result>$new?$result:$new;
7987: }
7988: }
7989: }
1.26 www 7990: }
7991: return $result;
1.421 albertel 7992: }
7993:
7994: # ---------------------------------------------------- Devalidate courseresdata
7995:
7996: sub devalidatecourseresdata {
7997: my ($coursenum,$coursedomain)=@_;
7998: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7999: &devalidate_cache_new('courseres',$hashid);
1.28 www 8000: }
8001:
1.763 www 8002:
1.200 www 8003: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8004: #
8005: # Parameters:
8006: # $coursenum - Number of the course.
8007: # $coursedomain - Domain at which the course was created.
8008: # Returns:
8009: # A hash of the course parameters along (I think) with timestamps
8010: # and version info.
1.877 foxr 8011:
1.624 albertel 8012: sub get_courseresdata {
8013: my ($coursenum,$coursedomain)=@_;
1.200 www 8014: my $coursehom=&homeserver($coursenum,$coursedomain);
8015: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8016: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8017: my %dumpreply;
1.417 albertel 8018: unless (defined($cached)) {
1.624 albertel 8019: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8020: $result=\%dumpreply;
1.251 albertel 8021: my ($tmp) = keys(%dumpreply);
8022: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8023: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8024: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8025: return $tmp;
1.416 albertel 8026: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8027: $result=undef;
1.599 albertel 8028: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8029: }
8030: }
1.624 albertel 8031: return $result;
8032: }
8033:
1.633 albertel 8034: sub devalidateuserresdata {
8035: my ($uname,$udom)=@_;
8036: my $hashid="$udom:$uname";
8037: &devalidate_cache_new('userres',$hashid);
8038: }
8039:
1.624 albertel 8040: sub get_userresdata {
8041: my ($uname,$udom)=@_;
8042: #most student don\'t have any data set, check if there is some data
8043: if (&EXT_cache_status($udom,$uname)) { return undef; }
8044:
8045: my $hashid="$udom:$uname";
8046: my ($result,$cached)=&is_cached_new('userres',$hashid);
8047: if (!defined($cached)) {
8048: my %resourcedata=&dump('resourcedata',$udom,$uname);
8049: $result=\%resourcedata;
8050: &do_cache_new('userres',$hashid,$result,600);
8051: }
8052: my ($tmp)=keys(%$result);
8053: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8054: return $result;
8055: }
8056: #error 2 occurs when the .db doesn't exist
8057: if ($tmp!~/error: 2 /) {
1.672 albertel 8058: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8059: " Trying to get resource data for ".
8060: $uname." at ".$udom.": ".
8061: $tmp."</font>");
8062: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8063: #&EXT_cache_set($udom,$uname);
8064: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8065: undef($tmp); # not really an error so don't send it back
1.624 albertel 8066: }
8067: return $tmp;
8068: }
1.879 foxr 8069: #----------------------------------------------- resdata - return resource data
8070: # Purpose:
8071: # Return resource data for either users or for a course.
8072: # Parameters:
8073: # $name - Course/user name.
8074: # $domain - Name of the domain the user/course is registered on.
8075: # $type - Type of thing $name is (must be 'course' or 'user'
8076: # @which - Array of names of resources desired.
8077: # Returns:
8078: # The value of the first reasource in @which that is found in the
8079: # resource hash.
8080: # Exceptional Conditions:
8081: # If the $type passed in is not valid (not the string 'course' or
8082: # 'user', an undefined reference is returned.
8083: # If none of the resources are found, an undef is returned
1.624 albertel 8084: sub resdata {
8085: my ($name,$domain,$type,@which)=@_;
8086: my $result;
8087: if ($type eq 'course') {
8088: $result=&get_courseresdata($name,$domain);
8089: } elsif ($type eq 'user') {
8090: $result=&get_userresdata($name,$domain);
8091: }
8092: if (!ref($result)) { return $result; }
1.251 albertel 8093: foreach my $item (@which) {
1.927 albertel 8094: if (defined($result->{$item->[0]})) {
8095: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8096: }
1.250 albertel 8097: }
1.291 albertel 8098: return undef;
1.200 www 8099: }
8100:
1.379 matthew 8101: #
8102: # EXT resource caching routines
8103: #
8104:
8105: sub clear_EXT_cache_status {
1.383 albertel 8106: &delenv('cache.EXT.');
1.379 matthew 8107: }
8108:
8109: sub EXT_cache_status {
8110: my ($target_domain,$target_user) = @_;
1.383 albertel 8111: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8112: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8113: # We know already the user has no data
8114: return 1;
8115: } else {
8116: return 0;
8117: }
8118: }
8119:
8120: sub EXT_cache_set {
8121: my ($target_domain,$target_user) = @_;
1.383 albertel 8122: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8123: #&appenv({$cachename => time});
1.379 matthew 8124: }
8125:
1.28 www 8126: # --------------------------------------------------------- Value of a Variable
1.58 www 8127: sub EXT {
1.715 albertel 8128:
1.395 albertel 8129: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8130: unless ($varname) { return ''; }
1.218 albertel 8131: #get real user name/domain, courseid and symb
8132: my $courseid;
1.359 albertel 8133: my $publicuser;
1.427 www 8134: if ($symbparm) {
8135: $symbparm=&get_symb_from_alias($symbparm);
8136: }
1.218 albertel 8137: if (!($uname && $udom)) {
1.790 albertel 8138: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8139: if (!$symbparm) { $symbparm=$cursymb; }
8140: } else {
1.620 albertel 8141: $courseid=$env{'request.course.id'};
1.218 albertel 8142: }
1.48 www 8143: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8144: my $rest;
1.320 albertel 8145: if (defined($therest[0])) {
1.48 www 8146: $rest=join('.',@therest);
8147: } else {
8148: $rest='';
8149: }
1.320 albertel 8150:
1.57 www 8151: my $qualifierrest=$qualifier;
8152: if ($rest) { $qualifierrest.='.'.$rest; }
8153: my $spacequalifierrest=$space;
8154: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8155: if ($realm eq 'user') {
1.48 www 8156: # --------------------------------------------------------------- user.resource
8157: if ($space eq 'resource') {
1.651 albertel 8158: if ( (defined($Apache::lonhomework::parsing_a_problem)
8159: || defined($Apache::lonhomework::parsing_a_task))
8160: &&
1.744 albertel 8161: ($symbparm eq &symbread()) ) {
8162: # if we are in the middle of processing the resource the
8163: # get the value we are planning on committing
8164: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8165: return $Apache::lonhomework::results{$qualifierrest};
8166: } else {
8167: return $Apache::lonhomework::history{$qualifierrest};
8168: }
1.335 albertel 8169: } else {
1.359 albertel 8170: my %restored;
1.620 albertel 8171: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8172: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8173: } else {
8174: %restored=&restore($symbparm,$courseid,$udom,$uname);
8175: }
1.335 albertel 8176: return $restored{$qualifierrest};
8177: }
1.48 www 8178: # ----------------------------------------------------------------- user.access
8179: } elsif ($space eq 'access') {
1.218 albertel 8180: # FIXME - not supporting calls for a specific user
1.48 www 8181: return &allowed($qualifier,$rest);
8182: # ------------------------------------------ user.preferences, user.environment
8183: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8184: if (($uname eq $env{'user.name'}) &&
8185: ($udom eq $env{'user.domain'})) {
8186: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8187: } else {
1.359 albertel 8188: my %returnhash;
8189: if (!$publicuser) {
8190: %returnhash=&userenvironment($udom,$uname,
8191: $qualifierrest);
8192: }
1.218 albertel 8193: return $returnhash{$qualifierrest};
8194: }
1.48 www 8195: # ----------------------------------------------------------------- user.course
8196: } elsif ($space eq 'course') {
1.218 albertel 8197: # FIXME - not supporting calls for a specific user
1.620 albertel 8198: return $env{join('.',('request.course',$qualifier))};
1.48 www 8199: # ------------------------------------------------------------------- user.role
8200: } elsif ($space eq 'role') {
1.218 albertel 8201: # FIXME - not supporting calls for a specific user
1.620 albertel 8202: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8203: if ($qualifier eq 'value') {
8204: return $role;
8205: } elsif ($qualifier eq 'extent') {
8206: return $where;
8207: }
8208: # ----------------------------------------------------------------- user.domain
8209: } elsif ($space eq 'domain') {
1.218 albertel 8210: return $udom;
1.48 www 8211: # ------------------------------------------------------------------- user.name
8212: } elsif ($space eq 'name') {
1.218 albertel 8213: return $uname;
1.48 www 8214: # ---------------------------------------------------- Any other user namespace
1.29 www 8215: } else {
1.359 albertel 8216: my %reply;
8217: if (!$publicuser) {
8218: %reply=&get($space,[$qualifierrest],$udom,$uname);
8219: }
8220: return $reply{$qualifierrest};
1.48 www 8221: }
1.236 www 8222: } elsif ($realm eq 'query') {
8223: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8224: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8225: [$spacequalifierrest]);
1.620 albertel 8226: return $env{'form.'.$spacequalifierrest};
1.236 www 8227: } elsif ($realm eq 'request') {
1.48 www 8228: # ------------------------------------------------------------- request.browser
8229: if ($space eq 'browser') {
1.430 www 8230: if ($qualifier eq 'textremote') {
1.676 albertel 8231: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8232: return 1;
8233: } else {
8234: return 0;
8235: }
8236: } else {
1.620 albertel 8237: return $env{'browser.'.$qualifier};
1.430 www 8238: }
1.57 www 8239: # ------------------------------------------------------------ request.filename
8240: } else {
1.620 albertel 8241: return $env{'request.'.$spacequalifierrest};
1.29 www 8242: }
1.28 www 8243: } elsif ($realm eq 'course') {
1.48 www 8244: # ---------------------------------------------------------- course.description
1.620 albertel 8245: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8246: } elsif ($realm eq 'resource') {
1.165 www 8247:
1.620 albertel 8248: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8249: if (!$symbparm) { $symbparm=&symbread(); }
8250: }
1.693 albertel 8251:
8252: if ($space eq 'title') {
8253: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8254: return &gettitle($symbparm);
8255: }
8256:
8257: if ($space eq 'map') {
8258: my ($map) = &decode_symb($symbparm);
8259: return &symbread($map);
8260: }
1.905 albertel 8261: if ($space eq 'filename') {
8262: if ($symbparm) {
8263: return &clutter((&decode_symb($symbparm))[2]);
8264: }
8265: return &hreflocation('',$env{'request.filename'});
8266: }
1.693 albertel 8267:
8268: my ($section, $group, @groups);
1.593 albertel 8269: my ($courselevelm,$courselevel);
1.539 albertel 8270: if ($symbparm && defined($courseid) &&
1.620 albertel 8271: $courseid eq $env{'request.course.id'}) {
1.165 www 8272:
1.218 albertel 8273: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8274:
1.60 www 8275: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8276: my $symbp=$symbparm;
1.735 albertel 8277: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8278:
8279: my $symbparm=$symbp.'.'.$spacequalifierrest;
8280: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8281:
1.620 albertel 8282: if (($env{'user.name'} eq $uname) &&
8283: ($env{'user.domain'} eq $udom)) {
8284: $section=$env{'request.course.sec'};
1.733 raeburn 8285: @groups = split(/:/,$env{'request.course.groups'});
8286: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8287: } else {
1.539 albertel 8288: if (! defined($usection)) {
1.551 albertel 8289: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8290: } else {
8291: $section = $usection;
8292: }
1.733 raeburn 8293: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8294: }
8295:
8296: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8297: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8298: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8299:
1.593 albertel 8300: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8301: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8302: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8303:
1.60 www 8304: # ----------------------------------------------------------- first, check user
1.624 albertel 8305:
8306: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8307: ([$courselevelr,'resource'],
8308: [$courselevelm,'map' ],
8309: [$courselevel, 'course' ]));
1.931 albertel 8310: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8311:
1.594 albertel 8312: # ------------------------------------------------ second, check some of course
1.684 raeburn 8313: my $coursereply;
1.691 raeburn 8314: if (@groups > 0) {
8315: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8316: $mapparm,$spacequalifierrest);
1.927 albertel 8317: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8318: }
1.96 www 8319:
1.684 raeburn 8320: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8321: $env{'course.'.$courseid.'.domain'},
8322: 'course',
8323: ([$seclevelr, 'resource'],
8324: [$seclevelm, 'map' ],
8325: [$seclevel, 'course' ],
8326: [$courselevelr,'resource']));
8327: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8328:
1.60 www 8329: # ------------------------------------------------------ third, check map parms
1.218 albertel 8330: my %parmhash=();
8331: my $thisparm='';
8332: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8333: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8334: &GDBM_READER(),0640)) {
1.218 albertel 8335: $thisparm=$parmhash{$symbparm};
8336: untie(%parmhash);
8337: }
1.927 albertel 8338: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8339: }
1.594 albertel 8340: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8341:
1.218 albertel 8342: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8343: my $filename;
8344: if (!$symbparm) { $symbparm=&symbread(); }
8345: if ($symbparm) {
1.409 www 8346: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8347: } else {
1.620 albertel 8348: $filename=$env{'request.filename'};
1.282 albertel 8349: }
8350: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8351: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8352: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8353: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8354:
1.927 albertel 8355: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8356: if ($symbparm && defined($courseid) &&
1.620 albertel 8357: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8358: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8359: $env{'course.'.$courseid.'.domain'},
8360: 'course',
1.927 albertel 8361: ([$courselevelm,'map' ],
8362: [$courselevel, 'course']));
8363: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8364: }
1.145 www 8365: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8366: unless ($space eq '0') {
1.336 albertel 8367: my @parts=split(/_/,$space);
8368: my $id=pop(@parts);
8369: my $part=join('_',@parts);
8370: if ($part eq '') { $part='0'; }
1.927 albertel 8371: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8372: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8373: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8374: }
1.395 albertel 8375: if ($recurse) { return undef; }
8376: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8377: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8378: # ---------------------------------------------------- Any other user namespace
8379: } elsif ($realm eq 'environment') {
8380: # ----------------------------------------------------------------- environment
1.620 albertel 8381: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8382: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8383: } else {
1.770 albertel 8384: if ($uname eq 'anonymous' && $udom eq '') {
8385: return '';
8386: }
1.219 albertel 8387: my %returnhash=&userenvironment($udom,$uname,
8388: $spacequalifierrest);
8389: return $returnhash{$spacequalifierrest};
8390: }
1.28 www 8391: } elsif ($realm eq 'system') {
1.48 www 8392: # ----------------------------------------------------------------- system.time
8393: if ($space eq 'time') {
8394: return time;
8395: }
1.696 albertel 8396: } elsif ($realm eq 'server') {
8397: # ----------------------------------------------------------------- system.time
8398: if ($space eq 'name') {
8399: return $ENV{'SERVER_NAME'};
8400: }
1.28 www 8401: }
1.48 www 8402: return '';
1.61 www 8403: }
8404:
1.927 albertel 8405: sub get_reply {
8406: my ($reply_value) = @_;
1.940 raeburn 8407: if (ref($reply_value) eq 'ARRAY') {
8408: if (wantarray) {
8409: return @$reply_value;
8410: }
8411: return $reply_value->[0];
8412: } else {
8413: return $reply_value;
1.927 albertel 8414: }
8415: }
8416:
1.691 raeburn 8417: sub check_group_parms {
8418: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8419: my @groupitems = ();
8420: my $resultitem;
1.927 albertel 8421: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8422: foreach my $group (@{$groups}) {
8423: foreach my $level (@levels) {
1.927 albertel 8424: my $item = $courseid.'.['.$group.'].'.$level->[0];
8425: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8426: }
8427: }
8428: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8429: $env{'course.'.$courseid.'.domain'},
8430: 'course',@groupitems);
8431: return $coursereply;
8432: }
8433:
8434: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8435: my ($courseid,@groups) = @_;
8436: @groups = sort(@groups);
1.691 raeburn 8437: return @groups;
8438: }
8439:
1.395 albertel 8440: sub packages_tab_default {
8441: my ($uri,$varname)=@_;
8442: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8443:
8444: my (@extension,@specifics,$do_default);
8445: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8446: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8447: if ($pack_type eq 'default') {
8448: $do_default=1;
8449: } elsif ($pack_type eq 'extension') {
8450: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8451: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8452: # only look at packages defaults for packages that this id is
1.738 albertel 8453: push(@specifics,[$package,$pack_type,$pack_part]);
8454: }
8455: }
8456: # first look for a package that matches the requested part id
8457: foreach my $package (@specifics) {
8458: my (undef,$pack_type,$pack_part)=@{$package};
8459: next if ($pack_part ne $part);
8460: if (defined($packagetab{"$pack_type&$name&default"})) {
8461: return $packagetab{"$pack_type&$name&default"};
8462: }
8463: }
8464: # look for any possible matching non extension_ package
8465: foreach my $package (@specifics) {
8466: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8467: if (defined($packagetab{"$pack_type&$name&default"})) {
8468: return $packagetab{"$pack_type&$name&default"};
8469: }
1.585 albertel 8470: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8471: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8472: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8473: }
8474: }
1.738 albertel 8475: # look for any posible extension_ match
8476: foreach my $package (@extension) {
8477: my ($package,$pack_type)=@{$package};
8478: if (defined($packagetab{"$pack_type&$name&default"})) {
8479: return $packagetab{"$pack_type&$name&default"};
8480: }
8481: if (defined($packagetab{$package."&$name&default"})) {
8482: return $packagetab{$package."&$name&default"};
8483: }
8484: }
8485: # look for a global default setting
8486: if ($do_default && defined($packagetab{"default&$name&default"})) {
8487: return $packagetab{"default&$name&default"};
8488: }
1.395 albertel 8489: return undef;
8490: }
8491:
1.334 albertel 8492: sub add_prefix_and_part {
8493: my ($prefix,$part)=@_;
8494: my $keyroot;
8495: if (defined($prefix) && $prefix !~ /^__/) {
8496: # prefix that has a part already
8497: $keyroot=$prefix;
8498: } elsif (defined($prefix)) {
8499: # prefix that is missing a part
8500: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8501: } else {
8502: # no prefix at all
8503: if (defined($part)) { $keyroot='_'.$part; }
8504: }
8505: return $keyroot;
8506: }
8507:
1.71 www 8508: # ---------------------------------------------------------------- Get metadata
8509:
1.599 albertel 8510: my %metaentry;
1.71 www 8511: sub metadata {
1.176 www 8512: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8513: $uri=&declutter($uri);
1.288 albertel 8514: # if it is a non metadata possible uri return quickly
1.529 albertel 8515: if (($uri eq '') ||
8516: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8517: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8518: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8519: return undef;
8520: }
8521: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8522: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8523: return undef;
1.288 albertel 8524: }
1.73 www 8525: my $filename=$uri;
8526: $uri=~s/\.meta$//;
1.172 www 8527: #
8528: # Is the metadata already cached?
1.177 www 8529: # Look at timestamp of caching
1.172 www 8530: # Everything is cached by the main uri, libraries are never directly cached
8531: #
1.428 albertel 8532: if (!defined($liburi)) {
1.599 albertel 8533: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8534: if (defined($cached)) { return $result->{':'.$what}; }
8535: }
8536: {
1.172 www 8537: #
8538: # Is this a recursive call for a library?
8539: #
1.599 albertel 8540: # if (! exists($metacache{$uri})) {
8541: # $metacache{$uri}={};
8542: # }
1.924 albertel 8543: my $cachetime = 60*60;
1.171 www 8544: if ($liburi) {
8545: $liburi=&declutter($liburi);
8546: $filename=$liburi;
1.401 bowersj2 8547: } else {
1.599 albertel 8548: &devalidate_cache_new('meta',$uri);
8549: undef(%metaentry);
1.401 bowersj2 8550: }
1.140 www 8551: my %metathesekeys=();
1.73 www 8552: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8553: my $metastring;
1.924 albertel 8554: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8555: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8556: $metastring =
1.929 albertel 8557: &Apache::lonnet::ssi_body($which,
1.924 albertel 8558: ('grade_target' => 'meta'));
8559: $cachetime = 1; # only want this cached in the child not long term
8560: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8561: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8562: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8563: $metastring=&getfile($file);
1.489 albertel 8564: }
1.208 albertel 8565: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8566: my $token;
1.140 www 8567: undef %metathesekeys;
1.71 www 8568: while ($token=$parser->get_token) {
1.339 albertel 8569: if ($token->[0] eq 'S') {
8570: if (defined($token->[2]->{'package'})) {
1.172 www 8571: #
8572: # This is a package - get package info
8573: #
1.339 albertel 8574: my $package=$token->[2]->{'package'};
8575: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8576: if (defined($token->[2]->{'id'})) {
8577: $keyroot.='_'.$token->[2]->{'id'};
8578: }
1.599 albertel 8579: if ($metaentry{':packages'}) {
8580: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8581: } else {
1.599 albertel 8582: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8583: }
1.736 albertel 8584: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8585: my $part=$keyroot;
8586: $part=~s/^\_//;
1.736 albertel 8587: if ($pack_entry=~/^\Q$package\E\&/ ||
8588: $pack_entry=~/^\Q$package\E_0\&/) {
8589: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8590: # ignore package.tab specified default values
8591: # here &package_tab_default() will fetch those
8592: if ($subp eq 'default') { next; }
1.736 albertel 8593: my $value=$packagetab{$pack_entry};
1.432 albertel 8594: my $unikey;
8595: if ($pack =~ /_0$/) {
8596: $unikey='parameter_0_'.$name;
8597: $part=0;
8598: } else {
8599: $unikey='parameter'.$keyroot.'_'.$name;
8600: }
1.339 albertel 8601: if ($subp eq 'display') {
8602: $value.=' [Part: '.$part.']';
8603: }
1.599 albertel 8604: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8605: $metathesekeys{$unikey}=1;
1.599 albertel 8606: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8607: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8608: }
1.599 albertel 8609: if (defined($metaentry{':'.$unikey.'.default'})) {
8610: $metaentry{':'.$unikey}=
8611: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8612: }
1.339 albertel 8613: }
8614: }
8615: } else {
1.172 www 8616: #
8617: # This is not a package - some other kind of start tag
1.339 albertel 8618: #
8619: my $entry=$token->[1];
8620: my $unikey;
8621: if ($entry eq 'import') {
8622: $unikey='';
8623: } else {
8624: $unikey=$entry;
8625: }
8626: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8627:
8628: if (defined($token->[2]->{'id'})) {
8629: $unikey.='_'.$token->[2]->{'id'};
8630: }
1.175 www 8631:
1.339 albertel 8632: if ($entry eq 'import') {
1.175 www 8633: #
8634: # Importing a library here
1.339 albertel 8635: #
8636: if ($depthcount<20) {
8637: my $location=$parser->get_text('/import');
8638: my $dir=$filename;
8639: $dir=~s|[^/]*$||;
8640: $location=&filelocation($dir,$location);
1.736 albertel 8641: my $metadata =
8642: &metadata($uri,'keys', $location,$unikey,
8643: $depthcount+1);
8644: foreach my $meta (split(',',$metadata)) {
8645: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8646: $metathesekeys{$meta}=1;
1.339 albertel 8647: }
8648: }
8649: } else {
8650: if (defined($token->[2]->{'name'})) {
8651: $unikey.='_'.$token->[2]->{'name'};
8652: }
8653: $metathesekeys{$unikey}=1;
1.736 albertel 8654: foreach my $param (@{$token->[3]}) {
8655: $metaentry{':'.$unikey.'.'.$param} =
8656: $token->[2]->{$param};
1.339 albertel 8657: }
8658: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8659: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8660: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8661: # only ws inside the tag, and not in default, so use default
8662: # as value
1.599 albertel 8663: $metaentry{':'.$unikey}=$default;
1.908 albertel 8664: } elsif ( $internaltext =~ /\S/ ) {
8665: # something interesting inside the tag
8666: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8667: } else {
1.908 albertel 8668: # no interesting values, don't set a default
1.339 albertel 8669: }
1.172 www 8670: # end of not-a-package not-a-library import
1.339 albertel 8671: }
1.172 www 8672: # end of not-a-package start tag
1.339 albertel 8673: }
1.172 www 8674: # the next is the end of "start tag"
1.339 albertel 8675: }
8676: }
1.483 albertel 8677: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8678: $extension = lc($extension);
8679: if ($extension eq 'htm') { $extension='html'; }
8680:
1.737 albertel 8681: foreach my $key (keys(%packagetab)) {
1.483 albertel 8682: #no specific packages #how's our extension
8683: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8684: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8685: \%metathesekeys);
8686: }
1.883 albertel 8687:
8688: if (!exists($metaentry{':packages'})
8689: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8690: foreach my $key (keys(%packagetab)) {
1.483 albertel 8691: #no specific packages well let's get default then
8692: if ($key!~/^default&/) { next; }
1.488 albertel 8693: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8694: \%metathesekeys);
8695: }
8696: }
1.338 www 8697: # are there custom rights to evaluate
1.599 albertel 8698: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8699:
1.338 www 8700: #
8701: # Importing a rights file here
1.339 albertel 8702: #
8703: unless ($depthcount) {
1.599 albertel 8704: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8705: my $dir=$filename;
8706: $dir=~s|[^/]*$||;
8707: $location=&filelocation($dir,$location);
1.736 albertel 8708: my $rights_metadata =
8709: &metadata($uri,'keys',$location,'_rights',
8710: $depthcount+1);
8711: foreach my $rights (split(',',$rights_metadata)) {
8712: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8713: $metathesekeys{$rights}=1;
1.339 albertel 8714: }
8715: }
8716: }
1.737 albertel 8717: # uniqifiy package listing
8718: my %seen;
8719: my @uniq_packages =
8720: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8721: $metaentry{':packages'} = join(',',@uniq_packages);
8722:
8723: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8724: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8725: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8726: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8727: # this is the end of "was not already recently cached
1.71 www 8728: }
1.599 albertel 8729: return $metaentry{':'.$what};
1.261 albertel 8730: }
8731:
1.488 albertel 8732: sub metadata_create_package_def {
1.483 albertel 8733: my ($uri,$key,$package,$metathesekeys)=@_;
8734: my ($pack,$name,$subp)=split(/\&/,$key);
8735: if ($subp eq 'default') { next; }
8736:
1.599 albertel 8737: if (defined($metaentry{':packages'})) {
8738: $metaentry{':packages'}.=','.$package;
1.483 albertel 8739: } else {
1.599 albertel 8740: $metaentry{':packages'}=$package;
1.483 albertel 8741: }
8742: my $value=$packagetab{$key};
8743: my $unikey;
8744: $unikey='parameter_0_'.$name;
1.599 albertel 8745: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8746: $$metathesekeys{$unikey}=1;
1.599 albertel 8747: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8748: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8749: }
1.599 albertel 8750: if (defined($metaentry{':'.$unikey.'.default'})) {
8751: $metaentry{':'.$unikey}=
8752: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8753: }
8754: }
8755:
1.261 albertel 8756: sub metadata_generate_part0 {
8757: my ($metadata,$metacache,$uri) = @_;
8758: my %allnames;
1.737 albertel 8759: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8760: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8761: my $part=$$metacache{':'.$metakey.'.part'};
8762: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8763: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8764: $allnames{$name}=$part;
8765: }
8766: }
8767: }
8768: foreach my $name (keys(%allnames)) {
8769: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8770: my $key=":parameter_0_$name";
1.261 albertel 8771: $$metacache{"$key.part"}='0';
8772: $$metacache{"$key.name"}=$name;
1.428 albertel 8773: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8774: $allnames{$name}.'_'.$name.
8775: '.type'};
1.428 albertel 8776: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8777: '.display'};
1.644 www 8778: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8779: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8780: $$metacache{"$key.display"}=$olddis;
8781: }
1.71 www 8782: }
8783:
1.764 albertel 8784: # ------------------------------------------------------ Devalidate title cache
8785:
8786: sub devalidate_title_cache {
8787: my ($url)=@_;
8788: if (!$env{'request.course.id'}) { return; }
8789: my $symb=&symbread($url);
8790: if (!$symb) { return; }
8791: my $key=$env{'request.course.id'}."\0".$symb;
8792: &devalidate_cache_new('title',$key);
8793: }
8794:
1.1014 droeschl 8795: # ------------------------------------------------- Get the title of a course
8796:
8797: sub current_course_title {
8798: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8799: }
1.301 www 8800: # ------------------------------------------------- Get the title of a resource
8801:
8802: sub gettitle {
8803: my $urlsymb=shift;
8804: my $symb=&symbread($urlsymb);
1.534 albertel 8805: if ($symb) {
1.620 albertel 8806: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8807: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8808: if (defined($cached)) {
8809: return $result;
8810: }
1.534 albertel 8811: my ($map,$resid,$url)=&decode_symb($symb);
8812: my $title='';
1.907 albertel 8813: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8814: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8815: } else {
8816: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8817: &GDBM_READER(),0640)) {
8818: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8819: $title=$bighash{'title_'.$mapid.'.'.$resid};
8820: untie(%bighash);
8821: }
1.534 albertel 8822: }
8823: $title=~s/\&colon\;/\:/gs;
8824: if ($title) {
1.599 albertel 8825: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8826: }
8827: $urlsymb=$url;
8828: }
8829: my $title=&metadata($urlsymb,'title');
8830: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8831: return $title;
1.301 www 8832: }
1.613 albertel 8833:
1.614 albertel 8834: sub get_slot {
8835: my ($which,$cnum,$cdom)=@_;
8836: if (!$cnum || !$cdom) {
1.790 albertel 8837: (undef,my $courseid)=&whichuser();
1.620 albertel 8838: $cdom=$env{'course.'.$courseid.'.domain'};
8839: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8840: }
1.703 albertel 8841: my $key=join("\0",'slots',$cdom,$cnum,$which);
8842: my %slotinfo;
8843: if (exists($remembered{$key})) {
8844: $slotinfo{$which} = $remembered{$key};
8845: } else {
8846: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8847: &Apache::lonhomework::showhash(%slotinfo);
8848: my ($tmp)=keys(%slotinfo);
8849: if ($tmp=~/^error:/) { return (); }
8850: $remembered{$key} = $slotinfo{$which};
8851: }
1.616 albertel 8852: if (ref($slotinfo{$which}) eq 'HASH') {
8853: return %{$slotinfo{$which}};
8854: }
8855: return $slotinfo{$which};
1.614 albertel 8856: }
1.31 www 8857: # ------------------------------------------------- Update symbolic store links
8858:
8859: sub symblist {
8860: my ($mapname,%newhash)=@_;
1.438 www 8861: $mapname=&deversion(&declutter($mapname));
1.31 www 8862: my %hash;
1.620 albertel 8863: if (($env{'request.course.fn'}) && (%newhash)) {
8864: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8865: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8866: foreach my $url (keys(%newhash)) {
1.711 albertel 8867: next if ($url eq 'last_known'
8868: && $env{'form.no_update_last_known'});
8869: $hash{declutter($url)}=&encode_symb($mapname,
8870: $newhash{$url}->[1],
8871: $newhash{$url}->[0]);
1.191 harris41 8872: }
1.31 www 8873: if (untie(%hash)) {
8874: return 'ok';
8875: }
8876: }
8877: }
8878: return 'error';
1.212 www 8879: }
8880:
8881: # --------------------------------------------------------------- Verify a symb
8882:
8883: sub symbverify {
1.510 www 8884: my ($symb,$thisurl)=@_;
8885: my $thisfn=$thisurl;
1.439 www 8886: $thisfn=&declutter($thisfn);
1.215 www 8887: # direct jump to resource in page or to a sequence - will construct own symbs
8888: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8889: # check URL part
1.409 www 8890: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8891:
1.431 www 8892: unless ($url eq $thisfn) { return 0; }
1.213 www 8893:
1.216 www 8894: $symb=&symbclean($symb);
1.510 www 8895: $thisurl=&deversion($thisurl);
1.439 www 8896: $thisfn=&deversion($thisfn);
1.213 www 8897:
8898: my %bighash;
8899: my $okay=0;
1.431 www 8900:
1.620 albertel 8901: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8902: &GDBM_READER(),0640)) {
1.1032 raeburn 8903: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8904: $thisurl =~ s/\?.+$//;
8905: }
1.510 www 8906: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8907: unless ($ids) {
1.510 www 8908: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8909: }
8910: if ($ids) {
8911: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8912: foreach my $id (split(/\,/,$ids)) {
8913: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8914: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8915: $symb =~ s/\?.+$//;
8916: }
1.216 www 8917: if (
8918: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8919: eq $symb) {
1.620 albertel 8920: if (($env{'request.role.adv'}) ||
1.800 albertel 8921: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8922: $okay=1;
8923: }
8924: }
1.216 www 8925: }
8926: }
1.213 www 8927: untie(%bighash);
8928: }
8929: return $okay;
1.31 www 8930: }
8931:
1.210 www 8932: # --------------------------------------------------------------- Clean-up symb
8933:
8934: sub symbclean {
8935: my $symb=shift;
1.568 albertel 8936: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8937: # remove version from map
8938: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8939:
1.210 www 8940: # remove version from URL
8941: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8942:
1.507 www 8943: # remove wrapper
8944:
1.510 www 8945: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8946: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8947: return $symb;
1.409 www 8948: }
8949:
8950: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8951:
8952: sub encode_symb {
8953: my ($map,$resid,$url)=@_;
8954: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8955: }
1.409 www 8956:
8957: sub decode_symb {
1.568 albertel 8958: my $symb=shift;
8959: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8960: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8961: return (&fixversion($map),$resid,&fixversion($url));
8962: }
8963:
8964: sub fixversion {
8965: my $fn=shift;
1.609 banghart 8966: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8967: my %bighash;
8968: my $uri=&clutter($fn);
1.620 albertel 8969: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8970: # is this cached?
1.599 albertel 8971: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8972: if (defined($cached)) { return $result; }
8973: # unfortunately not cached, or expired
1.620 albertel 8974: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8975: &GDBM_READER(),0640)) {
8976: if ($bighash{'version_'.$uri}) {
8977: my $version=$bighash{'version_'.$uri};
1.444 www 8978: unless (($version eq 'mostrecent') ||
8979: ($version==&getversion($uri))) {
1.440 www 8980: $uri=~s/\.(\w+)$/\.$version\.$1/;
8981: }
8982: }
8983: untie %bighash;
1.413 www 8984: }
1.599 albertel 8985: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8986: }
8987:
8988: sub deversion {
8989: my $url=shift;
8990: $url=~s/\.\d+\.(\w+)$/\.$1/;
8991: return $url;
1.210 www 8992: }
8993:
1.31 www 8994: # ------------------------------------------------------ Return symb list entry
8995:
8996: sub symbread {
1.249 www 8997: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8998: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8999: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9000: # no filename provided? try from environment
1.44 www 9001: unless ($thisfn) {
1.620 albertel 9002: if ($env{'request.symb'}) {
9003: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9004: }
1.620 albertel 9005: $thisfn=$env{'request.filename'};
1.44 www 9006: }
1.569 albertel 9007: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9008: # is that filename actually a symb? Verify, clean, and return
9009: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9010: if (&symbverify($thisfn,$1)) {
1.620 albertel 9011: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9012: }
1.242 www 9013: }
1.44 www 9014: $thisfn=declutter($thisfn);
1.31 www 9015: my %hash;
1.37 www 9016: my %bighash;
9017: my $syval='';
1.620 albertel 9018: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9019: my $targetfn = $thisfn;
1.609 banghart 9020: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9021: $targetfn = 'adm/wrapper/'.$thisfn;
9022: }
1.687 albertel 9023: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9024: $targetfn=$1;
9025: }
1.620 albertel 9026: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9027: &GDBM_READER(),0640)) {
1.481 raeburn 9028: $syval=$hash{$targetfn};
1.37 www 9029: untie(%hash);
9030: }
9031: # ---------------------------------------------------------- There was an entry
9032: if ($syval) {
1.601 albertel 9033: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9034: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9035: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9036: #return $env{$cache_str}='';
1.601 albertel 9037: #}
9038: #$syval.=$1;
9039: #}
1.37 www 9040: } else {
9041: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9042: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9043: &GDBM_READER(),0640)) {
1.37 www 9044: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9045: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9046: unless ($ids) {
9047: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9048: }
9049: unless ($ids) {
9050: # alias?
9051: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9052: }
1.37 www 9053: if ($ids) {
9054: # ------------------------------------------------------------------- Has ID(s)
9055: my @possibilities=split(/\,/,$ids);
1.39 www 9056: if ($#possibilities==0) {
9057: # ----------------------------------------------- There is only one possibility
1.37 www 9058: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9059: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9060: $resid,$thisfn);
1.249 www 9061: } elsif (!$donotrecurse) {
1.39 www 9062: # ------------------------------------------ There is more than one possibility
9063: my $realpossible=0;
1.800 albertel 9064: foreach my $id (@possibilities) {
9065: my $file=$bighash{'src_'.$id};
1.39 www 9066: if (&allowed('bre',$file)) {
1.800 albertel 9067: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9068: if ($bighash{'map_type_'.$mapid} ne 'page') {
9069: $realpossible++;
1.626 albertel 9070: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9071: $resid,$thisfn);
1.39 www 9072: }
9073: }
1.191 harris41 9074: }
1.39 www 9075: if ($realpossible!=1) { $syval=''; }
1.249 www 9076: } else {
9077: $syval='';
1.37 www 9078: }
9079: }
9080: untie(%bighash)
1.481 raeburn 9081: }
1.31 www 9082: }
1.62 www 9083: if ($syval) {
1.620 albertel 9084: return $env{$cache_str}=$syval;
1.62 www 9085: }
1.31 www 9086: }
1.949 raeburn 9087: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9088: return $env{$cache_str}='';
1.31 www 9089: }
9090:
9091: # ---------------------------------------------------------- Return random seed
9092:
1.32 www 9093: sub numval {
9094: my $txt=shift;
9095: $txt=~tr/A-J/0-9/;
9096: $txt=~tr/a-j/0-9/;
9097: $txt=~tr/K-T/0-9/;
9098: $txt=~tr/k-t/0-9/;
9099: $txt=~tr/U-Z/0-5/;
9100: $txt=~tr/u-z/0-5/;
9101: $txt=~s/\D//g;
1.564 albertel 9102: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9103: return int($txt);
1.368 albertel 9104: }
9105:
1.484 albertel 9106: sub numval2 {
9107: my $txt=shift;
9108: $txt=~tr/A-J/0-9/;
9109: $txt=~tr/a-j/0-9/;
9110: $txt=~tr/K-T/0-9/;
9111: $txt=~tr/k-t/0-9/;
9112: $txt=~tr/U-Z/0-5/;
9113: $txt=~tr/u-z/0-5/;
9114: $txt=~s/\D//g;
9115: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9116: my $total;
9117: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9118: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9119: return int($total);
9120: }
9121:
1.575 albertel 9122: sub numval3 {
9123: use integer;
9124: my $txt=shift;
9125: $txt=~tr/A-J/0-9/;
9126: $txt=~tr/a-j/0-9/;
9127: $txt=~tr/K-T/0-9/;
9128: $txt=~tr/k-t/0-9/;
9129: $txt=~tr/U-Z/0-5/;
9130: $txt=~tr/u-z/0-5/;
9131: $txt=~s/\D//g;
9132: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9133: my $total;
9134: foreach my $val (@txts) { $total+=$val; }
9135: if ($_64bit) { $total=(($total<<32)>>32); }
9136: return $total;
9137: }
9138:
1.675 albertel 9139: sub digest {
9140: my ($data)=@_;
9141: my $digest=&Digest::MD5::md5($data);
9142: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9143: my ($e,$f);
9144: {
9145: use integer;
9146: $e=($a+$b);
9147: $f=($c+$d);
9148: if ($_64bit) {
9149: $e=(($e<<32)>>32);
9150: $f=(($f<<32)>>32);
9151: }
9152: }
9153: if (wantarray) {
9154: return ($e,$f);
9155: } else {
9156: my $g;
9157: {
9158: use integer;
9159: $g=($e+$f);
9160: if ($_64bit) {
9161: $g=(($g<<32)>>32);
9162: }
9163: }
9164: return $g;
9165: }
9166: }
9167:
1.368 albertel 9168: sub latest_rnd_algorithm_id {
1.675 albertel 9169: return '64bit5';
1.366 albertel 9170: }
1.32 www 9171:
1.503 albertel 9172: sub get_rand_alg {
9173: my ($courseid)=@_;
1.790 albertel 9174: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9175: if ($courseid) {
1.620 albertel 9176: return $env{"course.$courseid.rndseed"};
1.503 albertel 9177: }
9178: return &latest_rnd_algorithm_id();
9179: }
9180:
1.562 albertel 9181: sub validCODE {
9182: my ($CODE)=@_;
9183: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9184: return 0;
9185: }
9186:
1.491 albertel 9187: sub getCODE {
1.620 albertel 9188: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9189: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9190: defined($Apache::lonhomework::parsing_a_task) ) &&
9191: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9192: return $Apache::lonhomework::history{'resource.CODE'};
9193: }
9194: return undef;
9195: }
9196:
1.31 www 9197: sub rndseed {
1.155 albertel 9198: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9199: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9200: if (!defined($symb)) {
1.366 albertel 9201: unless ($symb=$wsymb) { return time; }
9202: }
9203: if (!$courseid) { $courseid=$wcourseid; }
9204: if (!$domain) { $domain=$wdomain; }
9205: if (!$username) { $username=$wusername }
1.503 albertel 9206: my $which=&get_rand_alg();
1.803 albertel 9207:
1.491 albertel 9208: if (defined(&getCODE())) {
1.675 albertel 9209: if ($which eq '64bit5') {
9210: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9211: } elsif ($which eq '64bit4') {
1.575 albertel 9212: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9213: } else {
9214: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9215: }
1.675 albertel 9216: } elsif ($which eq '64bit5') {
9217: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9218: } elsif ($which eq '64bit4') {
9219: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9220: } elsif ($which eq '64bit3') {
9221: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9222: } elsif ($which eq '64bit2') {
9223: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9224: } elsif ($which eq '64bit') {
9225: return &rndseed_64bit($symb,$courseid,$domain,$username);
9226: }
9227: return &rndseed_32bit($symb,$courseid,$domain,$username);
9228: }
9229:
9230: sub rndseed_32bit {
9231: my ($symb,$courseid,$domain,$username)=@_;
9232: {
9233: use integer;
9234: my $symbchck=unpack("%32C*",$symb) << 27;
9235: my $symbseed=numval($symb) << 22;
9236: my $namechck=unpack("%32C*",$username) << 17;
9237: my $nameseed=numval($username) << 12;
9238: my $domainseed=unpack("%32C*",$domain) << 7;
9239: my $courseseed=unpack("%32C*",$courseid);
9240: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9241: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9242: #&logthis("rndseed :$num:$symb");
1.564 albertel 9243: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9244: return $num;
9245: }
9246: }
9247:
9248: sub rndseed_64bit {
9249: my ($symb,$courseid,$domain,$username)=@_;
9250: {
9251: use integer;
9252: my $symbchck=unpack("%32S*",$symb) << 21;
9253: my $symbseed=numval($symb) << 10;
9254: my $namechck=unpack("%32S*",$username);
9255:
9256: my $nameseed=numval($username) << 21;
9257: my $domainseed=unpack("%32S*",$domain) << 10;
9258: my $courseseed=unpack("%32S*",$courseid);
9259:
9260: my $num1=$symbchck+$symbseed+$namechck;
9261: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9262: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9263: #&logthis("rndseed :$num:$symb");
1.564 albertel 9264: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9265: return "$num1,$num2";
1.155 albertel 9266: }
1.366 albertel 9267: }
9268:
1.443 albertel 9269: sub rndseed_64bit2 {
9270: my ($symb,$courseid,$domain,$username)=@_;
9271: {
9272: use integer;
9273: # strings need to be an even # of cahracters long, it it is odd the
9274: # last characters gets thrown away
9275: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9276: my $symbseed=numval($symb) << 10;
9277: my $namechck=unpack("%32S*",$username.' ');
9278:
9279: my $nameseed=numval($username) << 21;
1.501 albertel 9280: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9281: my $courseseed=unpack("%32S*",$courseid.' ');
9282:
9283: my $num1=$symbchck+$symbseed+$namechck;
9284: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9285: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9286: #&logthis("rndseed :$num:$symb");
1.803 albertel 9287: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9288: return "$num1,$num2";
9289: }
9290: }
9291:
9292: sub rndseed_64bit3 {
9293: my ($symb,$courseid,$domain,$username)=@_;
9294: {
9295: use integer;
9296: # strings need to be an even # of cahracters long, it it is odd the
9297: # last characters gets thrown away
9298: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9299: my $symbseed=numval2($symb) << 10;
9300: my $namechck=unpack("%32S*",$username.' ');
9301:
9302: my $nameseed=numval2($username) << 21;
1.443 albertel 9303: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9304: my $courseseed=unpack("%32S*",$courseid.' ');
9305:
9306: my $num1=$symbchck+$symbseed+$namechck;
9307: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9308: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9309: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9310: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9311:
1.503 albertel 9312: return "$num1:$num2";
1.443 albertel 9313: }
9314: }
9315:
1.575 albertel 9316: sub rndseed_64bit4 {
9317: my ($symb,$courseid,$domain,$username)=@_;
9318: {
9319: use integer;
9320: # strings need to be an even # of cahracters long, it it is odd the
9321: # last characters gets thrown away
9322: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9323: my $symbseed=numval3($symb) << 10;
9324: my $namechck=unpack("%32S*",$username.' ');
9325:
9326: my $nameseed=numval3($username) << 21;
9327: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9328: my $courseseed=unpack("%32S*",$courseid.' ');
9329:
9330: my $num1=$symbchck+$symbseed+$namechck;
9331: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9332: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9333: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9334: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9335:
9336: return "$num1:$num2";
9337: }
9338: }
9339:
1.675 albertel 9340: sub rndseed_64bit5 {
9341: my ($symb,$courseid,$domain,$username)=@_;
9342: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9343: return "$num1:$num2";
9344: }
9345:
1.366 albertel 9346: sub rndseed_CODE_64bit {
9347: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9348: {
1.366 albertel 9349: use integer;
1.443 albertel 9350: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9351: my $symbseed=numval2($symb);
1.491 albertel 9352: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9353: my $CODEseed=numval(&getCODE());
1.443 albertel 9354: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9355: my $num1=$symbseed+$CODEchck;
9356: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9357: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9358: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9359: if ($_64bit) { $num1=(($num1<<32)>>32); }
9360: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9361: return "$num1:$num2";
1.366 albertel 9362: }
9363: }
9364:
1.575 albertel 9365: sub rndseed_CODE_64bit4 {
9366: my ($symb,$courseid,$domain,$username)=@_;
9367: {
9368: use integer;
9369: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9370: my $symbseed=numval3($symb);
9371: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9372: my $CODEseed=numval3(&getCODE());
9373: my $courseseed=unpack("%32S*",$courseid.' ');
9374: my $num1=$symbseed+$CODEchck;
9375: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9376: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9377: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9378: if ($_64bit) { $num1=(($num1<<32)>>32); }
9379: if ($_64bit) { $num2=(($num2<<32)>>32); }
9380: return "$num1:$num2";
9381: }
9382: }
9383:
1.675 albertel 9384: sub rndseed_CODE_64bit5 {
9385: my ($symb,$courseid,$domain,$username)=@_;
9386: my $code = &getCODE();
9387: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9388: return "$num1:$num2";
9389: }
9390:
1.366 albertel 9391: sub setup_random_from_rndseed {
9392: my ($rndseed)=@_;
1.503 albertel 9393: if ($rndseed =~/([,:])/) {
9394: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9395: &Math::Random::random_set_seed(abs($num1),abs($num2));
9396: } else {
9397: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9398: }
1.36 albertel 9399: }
9400:
1.474 albertel 9401: sub latest_receipt_algorithm_id {
1.835 albertel 9402: return 'receipt3';
1.474 albertel 9403: }
9404:
1.480 www 9405: sub recunique {
9406: my $fucourseid=shift;
9407: my $unique;
1.835 albertel 9408: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9409: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9410: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9411: } else {
9412: $unique=$perlvar{'lonReceipt'};
9413: }
9414: return unpack("%32C*",$unique);
9415: }
9416:
9417: sub recprefix {
9418: my $fucourseid=shift;
9419: my $prefix;
1.835 albertel 9420: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9421: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9422: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9423: } else {
9424: $prefix=$perlvar{'lonHostID'};
9425: }
9426: return unpack("%32C*",$prefix);
9427: }
9428:
1.76 www 9429: sub ireceipt {
1.474 albertel 9430: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9431:
9432: my $return =&recprefix($fucourseid).'-';
9433:
9434: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9435: $env{'request.state'} eq 'construct') {
9436: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9437: return $return;
9438: }
9439:
1.76 www 9440: my $cuname=unpack("%32C*",$funame);
9441: my $cudom=unpack("%32C*",$fudom);
9442: my $cucourseid=unpack("%32C*",$fucourseid);
9443: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9444: my $cunique=&recunique($fucourseid);
1.474 albertel 9445: my $cpart=unpack("%32S*",$part);
1.835 albertel 9446: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9447:
1.790 albertel 9448: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9449:
9450: $return.= ($cunique%$cuname+
9451: $cunique%$cudom+
9452: $cusymb%$cuname+
9453: $cusymb%$cudom+
9454: $cucourseid%$cuname+
9455: $cucourseid%$cudom+
9456: $cpart%$cuname+
9457: $cpart%$cudom);
9458: } else {
9459: $return.= ($cunique%$cuname+
9460: $cunique%$cudom+
9461: $cusymb%$cuname+
9462: $cusymb%$cudom+
9463: $cucourseid%$cuname+
9464: $cucourseid%$cudom);
9465: }
9466: return $return;
1.76 www 9467: }
9468:
9469: sub receipt {
1.474 albertel 9470: my ($part)=@_;
1.790 albertel 9471: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9472: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9473: }
1.260 ng 9474:
1.790 albertel 9475: sub whichuser {
9476: my ($passedsymb)=@_;
9477: my ($symb,$courseid,$domain,$name,$publicuser);
9478: if (defined($env{'form.grade_symb'})) {
9479: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9480: my $allowed=&allowed('vgr',$tmp_courseid);
9481: if (!$allowed &&
9482: exists($env{'request.course.sec'}) &&
9483: $env{'request.course.sec'} !~ /^\s*$/) {
9484: $allowed=&allowed('vgr',$tmp_courseid.
9485: '/'.$env{'request.course.sec'});
9486: }
9487: if ($allowed) {
9488: ($symb)=&get_env_multiple('form.grade_symb');
9489: $courseid=$tmp_courseid;
9490: ($domain)=&get_env_multiple('form.grade_domain');
9491: ($name)=&get_env_multiple('form.grade_username');
9492: return ($symb,$courseid,$domain,$name,$publicuser);
9493: }
9494: }
9495: if (!$passedsymb) {
9496: $symb=&symbread();
9497: } else {
9498: $symb=$passedsymb;
9499: }
9500: $courseid=$env{'request.course.id'};
9501: $domain=$env{'user.domain'};
9502: $name=$env{'user.name'};
9503: if ($name eq 'public' && $domain eq 'public') {
9504: if (!defined($env{'form.username'})) {
9505: $env{'form.username'}.=time.rand(10000000);
9506: }
9507: $name.=$env{'form.username'};
9508: }
9509: return ($symb,$courseid,$domain,$name,$publicuser);
9510:
9511: }
9512:
1.36 albertel 9513: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9514: # returns either the contents of the file or
9515: # -1 if the file doesn't exist
1.481 raeburn 9516: #
9517: # if the target is a file that was uploaded via DOCS,
9518: # a check will be made to see if a current copy exists on the local server,
9519: # if it does this will be served, otherwise a copy will be retrieved from
9520: # the home server for the course and stored in /home/httpd/html/userfiles on
9521: # the local server.
1.472 albertel 9522:
1.36 albertel 9523: sub getfile {
1.538 albertel 9524: my ($file) = @_;
1.609 banghart 9525: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9526: &repcopy($file);
9527: return &readfile($file);
9528: }
9529:
9530: sub repcopy_userfile {
9531: my ($file)=@_;
1.609 banghart 9532: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9533: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9534: my ($cdom,$cnum,$filename) =
1.811 albertel 9535: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9536: my $uri="/uploaded/$cdom/$cnum/$filename";
9537: if (-e "$file") {
1.828 www 9538: # we already have a local copy, check it out
1.538 albertel 9539: my @fileinfo = stat($file);
1.828 www 9540: my $rtncode;
9541: my $info;
1.538 albertel 9542: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9543: if ($lwpresp ne 'ok') {
1.828 www 9544: # there is no such file anymore, even though we had a local copy
1.482 albertel 9545: if ($rtncode eq '404') {
1.538 albertel 9546: unlink($file);
1.482 albertel 9547: }
9548: return -1;
9549: }
9550: if ($info < $fileinfo[9]) {
1.828 www 9551: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9552: return 'ok';
1.828 www 9553: } else {
9554: # the file is outdated, get rid of it
9555: unlink($file);
1.482 albertel 9556: }
1.828 www 9557: }
9558: # one way or the other, at this point, we don't have the file
9559: # construct the correct path for the file
9560: my @parts = ($cdom,$cnum);
9561: if ($filename =~ m|^(.+)/[^/]+$|) {
9562: push @parts, split(/\//,$1);
9563: }
9564: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9565: foreach my $part (@parts) {
9566: $path .= '/'.$part;
9567: if (!-e $path) {
9568: mkdir($path,0770);
1.482 albertel 9569: }
9570: }
1.828 www 9571: # now the path exists for sure
9572: # get a user agent
9573: my $ua=new LWP::UserAgent;
9574: my $transferfile=$file.'.in.transfer';
9575: # FIXME: this should flock
9576: if (-e $transferfile) { return 'ok'; }
9577: my $request;
9578: $uri=~s/^\///;
1.980 raeburn 9579: my $homeserver = &homeserver($cnum,$cdom);
9580: my $protocol = $protocol{$homeserver};
9581: $protocol = 'http' if ($protocol ne 'https');
9582: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9583: my $response=$ua->request($request,$transferfile);
9584: # did it work?
9585: if ($response->is_error()) {
9586: unlink($transferfile);
9587: &logthis("Userfile repcopy failed for $uri");
9588: return -1;
9589: }
9590: # worked, rename the transfer file
9591: rename($transferfile,$file);
1.607 raeburn 9592: return 'ok';
1.481 raeburn 9593: }
9594:
1.517 albertel 9595: sub tokenwrapper {
9596: my $uri=shift;
1.980 raeburn 9597: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9598: $uri=~s|^/||;
1.620 albertel 9599: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9600: my $token=$1;
1.552 albertel 9601: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9602: if ($udom && $uname && $file) {
9603: $file=~s|(\?\.*)*$||;
1.949 raeburn 9604: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9605: my $homeserver = &homeserver($uname,$udom);
9606: my $protocol = $protocol{$homeserver};
9607: $protocol = 'http' if ($protocol ne 'https');
9608: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9609: (($uri=~/\?/)?'&':'?').'token='.$token.
9610: '&tokenissued='.$perlvar{'lonHostID'};
9611: } else {
9612: return '/adm/notfound.html';
9613: }
9614: }
9615:
1.828 www 9616: # call with reqtype HEAD: get last modification time
9617: # call with reqtype GET: get the file contents
9618: # Do not call this with reqtype GET for large files! It loads everything into memory
9619: #
1.481 raeburn 9620: sub getuploaded {
9621: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9622: $uri=~s/^\///;
1.980 raeburn 9623: my $homeserver = &homeserver($cnum,$cdom);
9624: my $protocol = $protocol{$homeserver};
9625: $protocol = 'http' if ($protocol ne 'https');
9626: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9627: my $ua=new LWP::UserAgent;
9628: my $request=new HTTP::Request($reqtype,$uri);
9629: my $response=$ua->request($request);
9630: $$rtncode = $response->code;
1.482 albertel 9631: if (! $response->is_success()) {
9632: return 'failed';
9633: }
9634: if ($reqtype eq 'HEAD') {
1.486 www 9635: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9636: } elsif ($reqtype eq 'GET') {
9637: $$info = $response->content;
1.472 albertel 9638: }
1.482 albertel 9639: return 'ok';
1.36 albertel 9640: }
9641:
1.481 raeburn 9642: sub readfile {
9643: my $file = shift;
9644: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9645: my $fh;
9646: open($fh,"<$file");
9647: my $a='';
1.800 albertel 9648: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9649: return $a;
9650: }
9651:
1.36 albertel 9652: sub filelocation {
1.590 banghart 9653: my ($dir,$file) = @_;
9654: my $location;
9655: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9656:
9657: if ($file =~ m-^/adm/-) {
9658: $file=~s-^/adm/wrapper/-/-;
9659: $file=~s-^/adm/coursedocs/showdoc/-/-;
9660: }
1.882 albertel 9661:
1.590 banghart 9662: if ($file=~m:^/~:) { # is a contruction space reference
9663: $location = $file;
9664: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9665: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9666: # is a correct contruction space reference
9667: $location = $file;
1.956 raeburn 9668: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9669: $location = $file;
1.609 banghart 9670: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9671: my ($udom,$uname,$filename)=
1.811 albertel 9672: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9673: my $home=&homeserver($uname,$udom);
9674: my $is_me=0;
9675: my @ids=¤t_machine_ids();
9676: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9677: if ($is_me) {
1.955 raeburn 9678: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9679: } else {
9680: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9681: $udom.'/'.$uname.'/'.$filename;
9682: }
1.882 albertel 9683: } elsif ($file =~ m-^/adm/-) {
9684: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9685: } else {
9686: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9687: $file=~s:^/res/:/:;
9688: if ( !( $file =~ m:^/:) ) {
9689: $location = $dir. '/'.$file;
9690: } else {
9691: $location = '/home/httpd/html/res'.$file;
9692: }
1.59 albertel 9693: }
1.590 banghart 9694: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9695: while ($location=~m{/\.\./}) {
9696: if ($location =~ m{/[^/]+/\.\./}) {
9697: $location=~ s{/[^/]+/\.\./}{/}g;
9698: } else {
9699: $location=~ s{/\.\./}{/}g;
9700: }
9701: } #remove dir/..
1.590 banghart 9702: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9703: return $location;
1.46 www 9704: }
1.36 albertel 9705:
1.46 www 9706: sub hreflocation {
9707: my ($dir,$file)=@_;
1.980 raeburn 9708: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9709: $file=filelocation($dir,$file);
1.700 albertel 9710: } elsif ($file=~m-^/adm/-) {
9711: $file=~s-^/adm/wrapper/-/-;
9712: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9713: }
9714: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9715: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9716: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9717: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9718: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9719: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9720: -/uploaded/$1/$2/-x;
1.46 www 9721: }
1.913 albertel 9722: if ($file=~ m{^/userfiles/}) {
9723: $file =~ s{^/userfiles/}{/uploaded/};
9724: }
1.462 albertel 9725: return $file;
1.465 albertel 9726: }
9727:
9728: sub current_machine_domains {
1.853 albertel 9729: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9730: }
9731:
9732: sub machine_domains {
9733: my ($hostname) = @_;
1.465 albertel 9734: my @domains;
1.838 albertel 9735: my %hostname = &all_hostnames();
1.465 albertel 9736: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9737: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9738: if ($hostname eq $name) {
1.844 albertel 9739: push(@domains,&host_domain($id));
1.465 albertel 9740: }
9741: }
9742: return @domains;
9743: }
9744:
9745: sub current_machine_ids {
1.853 albertel 9746: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9747: }
9748:
9749: sub machine_ids {
9750: my ($hostname) = @_;
9751: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9752: my @ids;
1.888 albertel 9753: my %name_to_host = &all_names();
1.889 albertel 9754: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9755: return @{ $name_to_host{$hostname} };
9756: }
9757: return;
1.31 www 9758: }
9759:
1.824 raeburn 9760: sub additional_machine_domains {
9761: my @domains;
9762: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9763: while( my $line = <$fh>) {
9764: $line =~ s/\s//g;
9765: push(@domains,$line);
9766: }
9767: return @domains;
9768: }
9769:
9770: sub default_login_domain {
9771: my $domain = $perlvar{'lonDefDomain'};
9772: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9773: foreach my $posdom (¤t_machine_domains(),
9774: &additional_machine_domains()) {
9775: if (lc($posdom) eq lc($testdomain)) {
9776: $domain=$posdom;
9777: last;
9778: }
9779: }
9780: return $domain;
9781: }
9782:
1.31 www 9783: # ------------------------------------------------------------- Declutters URLs
9784:
9785: sub declutter {
9786: my $thisfn=shift;
1.569 albertel 9787: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9788: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9789: $thisfn=~s/^\///;
1.697 albertel 9790: $thisfn=~s|^adm/wrapper/||;
9791: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9792: $thisfn=~s/^res\///;
1.1032 raeburn 9793: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9794: $thisfn=~s/\?.+$//;
9795: }
1.268 www 9796: return $thisfn;
9797: }
9798:
9799: # ------------------------------------------------------------- Clutter up URLs
9800:
9801: sub clutter {
9802: my $thisfn='/'.&declutter(shift);
1.887 albertel 9803: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9804: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9805: $thisfn='/res'.$thisfn;
9806: }
1.1031 raeburn 9807: if ($thisfn !~m|^/adm|) {
9808: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9809: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9810: } else {
9811: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9812: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9813: if ($embstyle eq 'ssi'
9814: || ($embstyle eq 'hdn')
9815: || ($embstyle eq 'rat')
9816: || ($embstyle eq 'prv')
9817: || ($embstyle eq 'ign')) {
9818: #do nothing with these
9819: } elsif (($embstyle eq 'img')
1.695 albertel 9820: || ($embstyle eq 'emb')
9821: || ($embstyle eq 'wrp')) {
9822: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9823: } elsif ($embstyle eq 'unk'
9824: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9825: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9826: } else {
1.718 www 9827: # &logthis("Got a blank emb style");
1.695 albertel 9828: }
1.694 albertel 9829: }
9830: }
1.31 www 9831: return $thisfn;
1.12 www 9832: }
9833:
1.787 albertel 9834: sub clutter_with_no_wrapper {
9835: my $uri = &clutter(shift);
9836: if ($uri =~ m-^/adm/-) {
9837: $uri =~ s-^/adm/wrapper/-/-;
9838: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9839: }
9840: return $uri;
9841: }
9842:
1.557 albertel 9843: sub freeze_escape {
9844: my ($value)=@_;
9845: if (ref($value)) {
9846: $value=&nfreeze($value);
9847: return '__FROZEN__'.&escape($value);
9848: }
9849: return &escape($value);
9850: }
9851:
1.11 www 9852:
1.557 albertel 9853: sub thaw_unescape {
9854: my ($value)=@_;
9855: if ($value =~ /^__FROZEN__/) {
9856: substr($value,0,10,undef);
9857: $value=&unescape($value);
9858: return &thaw($value);
9859: }
9860: return &unescape($value);
9861: }
9862:
1.436 albertel 9863: sub correct_line_ends {
9864: my ($result)=@_;
9865: $$result =~s/\r\n/\n/mg;
9866: $$result =~s/\r/\n/mg;
1.415 albertel 9867: }
1.1 albertel 9868: # ================================================================ Main Program
9869:
1.184 www 9870: sub goodbye {
1.204 albertel 9871: &logthis("Starting Shut down");
1.443 albertel 9872: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9873: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9874: #converted
1.599 albertel 9875: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9876: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9877: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9878: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9879: #1.1 only
1.870 albertel 9880: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9881: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9882: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9883: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9884: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9885: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9886: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9887: &flushcourselogs();
9888: &logthis("Shutting down");
9889: }
9890:
1.852 albertel 9891: sub get_dns {
1.869 albertel 9892: my ($url,$func,$ignore_cache) = @_;
9893: if (!$ignore_cache) {
9894: my ($content,$cached)=
9895: &Apache::lonnet::is_cached_new('dns',$url);
9896: if ($cached) {
9897: &$func($content);
9898: return;
9899: }
9900: }
9901:
9902: my %alldns;
1.852 albertel 9903: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9904: foreach my $dns (<$config>) {
9905: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9906: my $line = $1;
9907: my ($host,$protocol) = split(/:/,$line);
9908: if ($protocol ne 'https') {
9909: $protocol = 'http';
9910: }
9911: $alldns{$host} = $protocol;
1.869 albertel 9912: }
9913: while (%alldns) {
9914: my ($dns) = keys(%alldns);
1.852 albertel 9915: my $ua=new LWP::UserAgent;
1.979 raeburn 9916: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9917: my $response=$ua->request($request);
1.979 raeburn 9918: delete($alldns{$dns});
1.852 albertel 9919: next if ($response->is_error());
9920: my @content = split("\n",$response->content);
1.869 albertel 9921: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9922: &$func(\@content);
1.869 albertel 9923: return;
1.852 albertel 9924: }
9925: close($config);
1.871 albertel 9926: my $which = (split('/',$url))[3];
9927: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9928: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9929: my @content = <$config>;
9930: &$func(\@content);
9931: return;
1.852 albertel 9932: }
1.327 albertel 9933: # ------------------------------------------------------------ Read domain file
9934: {
1.852 albertel 9935: my $loaded;
1.846 albertel 9936: my %domain;
9937:
1.852 albertel 9938: sub parse_domain_tab {
9939: my ($lines) = @_;
9940: foreach my $line (@$lines) {
9941: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9942:
1.846 albertel 9943: chomp($line);
1.852 albertel 9944: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9945: my %this_domain;
9946: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9947: 'lang_def', 'city', 'longi', 'lati',
9948: 'primary') {
9949: $this_domain{$field} = shift(@elements);
9950: }
9951: $domain{$name} = \%this_domain;
1.852 albertel 9952: }
9953: }
1.864 albertel 9954:
9955: sub reset_domain_info {
9956: undef($loaded);
9957: undef(%domain);
9958: }
9959:
1.852 albertel 9960: sub load_domain_tab {
1.869 albertel 9961: my ($ignore_cache) = @_;
9962: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9963: my $fh;
9964: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9965: my @lines = <$fh>;
9966: &parse_domain_tab(\@lines);
1.448 albertel 9967: }
1.852 albertel 9968: close($fh);
9969: $loaded = 1;
1.327 albertel 9970: }
1.846 albertel 9971:
9972: sub domain {
1.852 albertel 9973: &load_domain_tab() if (!$loaded);
9974:
1.846 albertel 9975: my ($name,$what) = @_;
9976: return if ( !exists($domain{$name}) );
9977:
9978: if (!$what) {
9979: return $domain{$name}{'description'};
9980: }
9981: return $domain{$name}{$what};
9982: }
1.974 raeburn 9983:
9984: sub domain_info {
9985: &load_domain_tab() if (!$loaded);
9986: return %domain;
9987: }
9988:
1.327 albertel 9989: }
9990:
9991:
1.1 albertel 9992: # ------------------------------------------------------------- Read hosts file
9993: {
1.838 albertel 9994: my %hostname;
1.844 albertel 9995: my %hostdom;
1.845 albertel 9996: my %libserv;
1.852 albertel 9997: my $loaded;
1.888 albertel 9998: my %name_to_host;
1.1056.4.6 raeburn 9999: my %internetdom;
1.852 albertel 10000:
10001: sub parse_hosts_tab {
10002: my ($file) = @_;
10003: foreach my $configline (@$file) {
10004: next if ($configline =~ /^(\#|\s*$ )/x);
10005: next if ($configline =~ /^\^/);
10006: chomp($configline);
1.1056.4.6 raeburn 10007: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10008: $name=~s/\s//g;
10009: if ($id && $domain && $role && $name) {
10010: $hostname{$id}=$name;
1.888 albertel 10011: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10012: $hostdom{$id}=$domain;
10013: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10014: if (defined($protocol)) {
10015: if ($protocol eq 'https') {
10016: $protocol{$id} = $protocol;
10017: } else {
10018: $protocol{$id} = 'http';
10019: }
1.968 raeburn 10020: } else {
1.969 raeburn 10021: $protocol{$id} = 'http';
1.968 raeburn 10022: }
1.1056.4.6 raeburn 10023: if (defined($intdom)) {
10024: $internetdom{$id} = $intdom;
10025: }
1.852 albertel 10026: }
10027: }
10028: }
1.864 albertel 10029:
10030: sub reset_hosts_info {
1.897 albertel 10031: &purge_remembered();
1.864 albertel 10032: &reset_domain_info();
10033: &reset_hosts_ip_info();
1.892 albertel 10034: undef(%name_to_host);
1.864 albertel 10035: undef(%hostname);
10036: undef(%hostdom);
10037: undef(%libserv);
10038: undef($loaded);
10039: }
1.1 albertel 10040:
1.852 albertel 10041: sub load_hosts_tab {
1.869 albertel 10042: my ($ignore_cache) = @_;
10043: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10044: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10045: my @config = <$config>;
10046: &parse_hosts_tab(\@config);
10047: close($config);
10048: $loaded=1;
1.1 albertel 10049: }
1.852 albertel 10050:
1.838 albertel 10051: sub hostname {
1.852 albertel 10052: &load_hosts_tab() if (!$loaded);
10053:
1.838 albertel 10054: my ($lonid) = @_;
10055: return $hostname{$lonid};
10056: }
1.845 albertel 10057:
1.838 albertel 10058: sub all_hostnames {
1.852 albertel 10059: &load_hosts_tab() if (!$loaded);
10060:
1.838 albertel 10061: return %hostname;
10062: }
1.845 albertel 10063:
1.888 albertel 10064: sub all_names {
10065: &load_hosts_tab() if (!$loaded);
10066:
10067: return %name_to_host;
10068: }
10069:
1.974 raeburn 10070: sub all_host_domain {
10071: &load_hosts_tab() if (!$loaded);
10072: return %hostdom;
10073: }
10074:
1.845 albertel 10075: sub is_library {
1.852 albertel 10076: &load_hosts_tab() if (!$loaded);
10077:
1.845 albertel 10078: return exists($libserv{$_[0]});
10079: }
10080:
10081: sub all_library {
1.852 albertel 10082: &load_hosts_tab() if (!$loaded);
10083:
1.845 albertel 10084: return %libserv;
10085: }
10086:
1.1056.4.2 raeburn 10087: sub unique_library {
10088: #2x reverse removes all hostnames that appear more than once
10089: my %unique = reverse &all_library();
10090: return reverse %unique;
10091: }
10092:
1.841 albertel 10093: sub get_servers {
1.852 albertel 10094: &load_hosts_tab() if (!$loaded);
10095:
1.841 albertel 10096: my ($domain,$type) = @_;
10097: my %possible_hosts = ($type eq 'library') ? %libserv
10098: : %hostname;
10099: my %result;
1.842 albertel 10100: if (ref($domain) eq 'ARRAY') {
10101: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10102: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10103: $result{$host} = $hostname;
10104: }
10105: }
10106: } else {
10107: while ( my ($host,$hostname) = each(%possible_hosts)) {
10108: if ($hostdom{$host} eq $domain) {
10109: $result{$host} = $hostname;
10110: }
1.841 albertel 10111: }
10112: }
10113: return %result;
10114: }
1.845 albertel 10115:
1.1056.4.2 raeburn 10116: sub get_unique_servers {
10117: my %unique = reverse &get_servers(@_);
10118: return reverse %unique;
10119: }
10120:
1.844 albertel 10121: sub host_domain {
1.852 albertel 10122: &load_hosts_tab() if (!$loaded);
10123:
1.844 albertel 10124: my ($lonid) = @_;
10125: return $hostdom{$lonid};
10126: }
10127:
1.841 albertel 10128: sub all_domains {
1.852 albertel 10129: &load_hosts_tab() if (!$loaded);
10130:
1.841 albertel 10131: my %seen;
10132: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10133: return @uniq;
10134: }
1.1056.4.3 raeburn 10135:
10136: sub internet_dom {
10137: &load_hosts_tab() if (!$loaded);
10138:
10139: my ($lonid) = @_;
10140: return $internetdom{$lonid};
10141: }
1.1 albertel 10142: }
10143:
1.847 albertel 10144: {
10145: my %iphost;
1.856 albertel 10146: my %name_to_ip;
10147: my %lonid_to_ip;
1.869 albertel 10148:
1.847 albertel 10149: sub get_hosts_from_ip {
10150: my ($ip) = @_;
10151: my %iphosts = &get_iphost();
10152: if (ref($iphosts{$ip})) {
10153: return @{$iphosts{$ip}};
10154: }
10155: return;
1.839 albertel 10156: }
1.864 albertel 10157:
10158: sub reset_hosts_ip_info {
10159: undef(%iphost);
10160: undef(%name_to_ip);
10161: undef(%lonid_to_ip);
10162: }
1.856 albertel 10163:
10164: sub get_host_ip {
10165: my ($lonid) = @_;
10166: if (exists($lonid_to_ip{$lonid})) {
10167: return $lonid_to_ip{$lonid};
10168: }
10169: my $name=&hostname($lonid);
10170: my $ip = gethostbyname($name);
10171: return if (!$ip || length($ip) ne 4);
10172: $ip=inet_ntoa($ip);
10173: $name_to_ip{$name} = $ip;
10174: $lonid_to_ip{$lonid} = $ip;
10175: return $ip;
10176: }
1.847 albertel 10177:
10178: sub get_iphost {
1.869 albertel 10179: my ($ignore_cache) = @_;
1.894 albertel 10180:
1.869 albertel 10181: if (!$ignore_cache) {
10182: if (%iphost) {
10183: return %iphost;
10184: }
10185: my ($ip_info,$cached)=
10186: &Apache::lonnet::is_cached_new('iphost','iphost');
10187: if ($cached) {
10188: %iphost = %{$ip_info->[0]};
10189: %name_to_ip = %{$ip_info->[1]};
10190: %lonid_to_ip = %{$ip_info->[2]};
10191: return %iphost;
10192: }
10193: }
1.894 albertel 10194:
10195: # get yesterday's info for fallback
10196: my %old_name_to_ip;
10197: my ($ip_info,$cached)=
10198: &Apache::lonnet::is_cached_new('iphost','iphost');
10199: if ($cached) {
10200: %old_name_to_ip = %{$ip_info->[1]};
10201: }
10202:
1.888 albertel 10203: my %name_to_host = &all_names();
10204: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10205: my $ip;
10206: if (!exists($name_to_ip{$name})) {
10207: $ip = gethostbyname($name);
10208: if (!$ip || length($ip) ne 4) {
1.894 albertel 10209: if (defined($old_name_to_ip{$name})) {
10210: $ip = $old_name_to_ip{$name};
10211: &logthis("Can't find $name defaulting to old $ip");
10212: } else {
10213: &logthis("Name $name no IP found");
10214: next;
10215: }
10216: } else {
10217: $ip=inet_ntoa($ip);
1.847 albertel 10218: }
10219: $name_to_ip{$name} = $ip;
10220: } else {
10221: $ip = $name_to_ip{$name};
1.653 albertel 10222: }
1.888 albertel 10223: foreach my $id (@{ $name_to_host{$name} }) {
10224: $lonid_to_ip{$id} = $ip;
10225: }
10226: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10227: }
1.869 albertel 10228: &Apache::lonnet::do_cache_new('iphost','iphost',
10229: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10230: 48*60*60);
1.869 albertel 10231:
1.847 albertel 10232: return %iphost;
1.598 albertel 10233: }
10234:
1.992 raeburn 10235: #
10236: # Given a DNS returns the loncapa host name for that DNS
10237: #
10238: sub host_from_dns {
10239: my ($dns) = @_;
10240: my @hosts;
10241: my $ip;
10242:
1.993 raeburn 10243: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10244: $ip = $name_to_ip{$dns};
10245: }
10246: if (!$ip) {
10247: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10248: if (length($ip) == 4) {
10249: $ip = &IO::Socket::inet_ntoa($ip);
10250: }
10251: }
10252: if ($ip) {
10253: @hosts = get_hosts_from_ip($ip);
10254: return $hosts[0];
10255: }
10256: return undef;
1.986 foxr 10257: }
1.992 raeburn 10258:
1.1056.4.3 raeburn 10259: sub get_internet_names {
10260: my ($lonid) = @_;
10261: return if ($lonid eq '');
10262: my ($idnref,$cached)=
10263: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10264: if ($cached) {
10265: return $idnref;
10266: }
10267: my $ip = &get_host_ip($lonid);
10268: my @hosts = &get_hosts_from_ip($ip);
10269: my %iphost = &get_iphost();
10270: my (@idns,%seen);
10271: foreach my $id (@hosts) {
10272: my $dom = &host_domain($id);
10273: my $prim_id = &domain($dom,'primary');
10274: my $prim_ip = &get_host_ip($prim_id);
10275: next if ($seen{$prim_ip});
10276: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10277: foreach my $id (@{$iphost{$prim_ip}}) {
10278: my $intdom = &internet_dom($id);
10279: unless (grep(/^\Q$intdom\E$/,@idns)) {
10280: push(@idns,$intdom);
10281: }
10282: }
10283: }
10284: $seen{$prim_ip} = 1;
10285: }
10286: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10287: }
10288:
10289: }
10290:
10291: sub all_loncaparevs {
10292: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986 foxr 10293: }
10294:
1.862 albertel 10295: BEGIN {
10296:
10297: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10298: unless ($readit) {
10299: {
10300: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10301: %perlvar = (%perlvar,%{$configvars});
10302: }
10303:
10304:
1.1 albertel 10305: # ------------------------------------------------------ Read spare server file
10306: {
1.448 albertel 10307: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10308:
10309: while (my $configline=<$config>) {
10310: chomp($configline);
1.284 matthew 10311: if ($configline) {
1.784 albertel 10312: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10313: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10314: push(@{ $spareid{$type} }, $host);
1.1 albertel 10315: }
10316: }
1.448 albertel 10317: close($config);
1.1 albertel 10318: }
1.11 www 10319: # ------------------------------------------------------------ Read permissions
10320: {
1.448 albertel 10321: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10322:
10323: while (my $configline=<$config>) {
1.448 albertel 10324: chomp($configline);
10325: if ($configline) {
10326: my ($role,$perm)=split(/ /,$configline);
10327: if ($perm ne '') { $pr{$role}=$perm; }
10328: }
1.11 www 10329: }
1.448 albertel 10330: close($config);
1.11 www 10331: }
10332:
10333: # -------------------------------------------- Read plain texts for permissions
10334: {
1.448 albertel 10335: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10336:
10337: while (my $configline=<$config>) {
1.448 albertel 10338: chomp($configline);
10339: if ($configline) {
1.742 raeburn 10340: my ($short,@plain)=split(/:/,$configline);
10341: %{$prp{$short}} = ();
10342: if (@plain > 0) {
10343: $prp{$short}{'std'} = $plain[0];
10344: for (my $i=1; $i<@plain; $i++) {
10345: $prp{$short}{'alt'.$i} = $plain[$i];
10346: }
10347: }
1.448 albertel 10348: }
1.135 www 10349: }
1.448 albertel 10350: close($config);
1.135 www 10351: }
10352:
10353: # ---------------------------------------------------------- Read package table
10354: {
1.448 albertel 10355: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10356:
10357: while (my $configline=<$config>) {
1.483 albertel 10358: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10359: chomp($configline);
10360: my ($short,$plain)=split(/:/,$configline);
10361: my ($pack,$name)=split(/\&/,$short);
10362: if ($plain ne '') {
10363: $packagetab{$pack.'&'.$name.'&name'}=$name;
10364: $packagetab{$short}=$plain;
10365: }
1.11 www 10366: }
1.448 albertel 10367: close($config);
1.329 matthew 10368: }
10369:
1.1056.4.3 raeburn 10370: # ---------------------------------------------------------- Read loncaparev table
10371: {
10372: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10373: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10374: while (my $configline=<$config>) {
10375: chomp($configline);
10376: my ($hostid,$loncaparev)=split(/:/,$configline);
10377: $loncaparevs{$hostid}=$loncaparev;
10378: }
10379: close($config);
10380: }
10381: }
10382: }
10383:
10384: # ---------------------------------------------------------- Read serverhostID table
10385: {
10386: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10387: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10388: while (my $configline=<$config>) {
10389: chomp($configline);
10390: my ($name,$id)=split(/:/,$configline);
10391: $serverhomeIDs{$name}=$id;
10392: }
10393: close($config);
10394: }
10395: }
10396: }
10397:
1.1056.4.5 raeburn 10398: {
10399: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10400: if (-e $file) {
10401: my $parser = HTML::LCParser->new($file);
10402: while (my $token = $parser->get_token()) {
10403: if ($token->[0] eq 'S') {
10404: my $item = $token->[1];
10405: my $name = $token->[2]{'name'};
10406: my $value = $token->[2]{'value'};
10407: if ($item ne '' && $name ne '' && $value ne '') {
10408: my $release = $parser->get_text();
10409: $release =~ s/(^\s*|\s*$ )//gx;
10410: $needsrelease{$item.':'.$name.':'.$value} = $release;
10411: }
10412: }
10413: }
10414: }
10415: }
10416:
1.329 matthew 10417: # ------------- set up temporary directory
10418: {
10419: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10420:
1.11 www 10421: }
10422:
1.794 albertel 10423: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10424: 'compress_threshold'=> 20_000,
10425: });
1.185 www 10426:
1.281 www 10427: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10428: $dumpcount=0;
1.958 www 10429: $locknum=0;
1.22 www 10430:
1.163 harris41 10431: &logtouch();
1.672 albertel 10432: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10433: $readit=1;
1.564 albertel 10434: {
10435: use integer;
10436: my $test=(2**32)+1;
1.568 albertel 10437: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10438: &logthis(" Detected 64bit platform ($_64bit)");
10439: }
1.195 www 10440: }
1.1 albertel 10441: }
1.179 www 10442:
1.1 albertel 10443: 1;
1.191 harris41 10444: __END__
10445:
1.243 albertel 10446: =pod
10447:
1.191 harris41 10448: =head1 NAME
10449:
1.243 albertel 10450: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10451:
10452: =head1 SYNOPSIS
10453:
1.243 albertel 10454: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10455:
10456: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10457:
1.243 albertel 10458: Common parameters:
10459:
10460: =over 4
10461:
10462: =item *
10463:
10464: $uname : an internal username (if $cname expecting a course Id specifically)
10465:
10466: =item *
10467:
10468: $udom : a domain (if $cdom expecting a course's domain specifically)
10469:
10470: =item *
10471:
10472: $symb : a resource instance identifier
10473:
10474: =item *
10475:
10476: $namespace : the name of a .db file that contains the data needed or
10477: being set.
10478:
10479: =back
10480:
1.394 bowersj2 10481: =head1 OVERVIEW
1.191 harris41 10482:
1.394 bowersj2 10483: lonnet provides subroutines which interact with the
10484: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10485: about classes, users, and resources.
1.243 albertel 10486:
10487: For many of these objects you can also use this to store data about
10488: them or modify them in various ways.
1.191 harris41 10489:
1.394 bowersj2 10490: =head2 Symbs
1.191 harris41 10491:
1.394 bowersj2 10492: To identify a specific instance of a resource, LON-CAPA uses symbols
10493: or "symbs"X<symb>. These identifiers are built from the URL of the
10494: map, the resource number of the resource in the map, and the URL of
10495: the resource itself. The latter is somewhat redundant, but might help
10496: if maps change.
10497:
10498: An example is
10499:
10500: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10501:
10502: The respective map entry is
10503:
10504: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10505: title="Problem 2">
10506: </resource>
10507:
10508: Symbs are used by the random number generator, as well as to store and
10509: restore data specific to a certain instance of for example a problem.
10510:
10511: =head2 Storing And Retrieving Data
10512:
10513: X<store()>X<cstore()>X<restore()>Three of the most important functions
10514: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10515: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10516: is is the non-critical message twin of cstore. These functions are for
10517: handlers to store a perl hash to a user's permanent data space in an
10518: easy manner, and to retrieve it again on another call. It is expected
10519: that a handler would use this once at the beginning to retrieve data,
10520: and then again once at the end to send only the new data back.
10521:
10522: The data is stored in the user's data directory on the user's
10523: homeserver under the ID of the course.
10524:
10525: The hash that is returned by restore will have all of the previous
10526: value for all of the elements of the hash.
10527:
10528: Example:
10529:
10530: #creating a hash
10531: my %hash;
10532: $hash{'foo'}='bar';
10533:
10534: #storing it
10535: &Apache::lonnet::cstore(\%hash);
10536:
10537: #changing a value
10538: $hash{'foo'}='notbar';
10539:
10540: #adding a new value
10541: $hash{'bar'}='foo';
10542: &Apache::lonnet::cstore(\%hash);
10543:
10544: #retrieving the hash
10545: my %history=&Apache::lonnet::restore();
10546:
10547: #print the hash
10548: foreach my $key (sort(keys(%history))) {
10549: print("\%history{$key} = $history{$key}");
10550: }
10551:
10552: Will print out:
1.191 harris41 10553:
1.394 bowersj2 10554: %history{1:foo} = bar
10555: %history{1:keys} = foo:timestamp
10556: %history{1:timestamp} = 990455579
10557: %history{2:bar} = foo
10558: %history{2:foo} = notbar
10559: %history{2:keys} = foo:bar:timestamp
10560: %history{2:timestamp} = 990455580
10561: %history{bar} = foo
10562: %history{foo} = notbar
10563: %history{timestamp} = 990455580
10564: %history{version} = 2
10565:
10566: Note that the special hash entries C<keys>, C<version> and
10567: C<timestamp> were added to the hash. C<version> will be equal to the
10568: total number of versions of the data that have been stored. The
10569: C<timestamp> attribute will be the UNIX time the hash was
10570: stored. C<keys> is available in every historical section to list which
10571: keys were added or changed at a specific historical revision of a
10572: hash.
10573:
10574: B<Warning>: do not store the hash that restore returns directly. This
10575: will cause a mess since it will restore the historical keys as if the
10576: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10577:
1.394 bowersj2 10578: Calling convention:
1.191 harris41 10579:
1.394 bowersj2 10580: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10581: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10582:
1.394 bowersj2 10583: For more detailed information, see lonnet specific documentation.
1.191 harris41 10584:
1.394 bowersj2 10585: =head1 RETURN MESSAGES
1.191 harris41 10586:
1.394 bowersj2 10587: =over 4
1.191 harris41 10588:
1.394 bowersj2 10589: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10590:
1.394 bowersj2 10591: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10592: when the connection is brought back up
1.191 harris41 10593:
1.394 bowersj2 10594: =item * B<con_failed>: unable to contact remote host and unable to save message
10595: for later delivery
1.191 harris41 10596:
1.967 bisitz 10597: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10598:
1.394 bowersj2 10599: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10600: that was requested
1.191 harris41 10601:
1.243 albertel 10602: =back
1.191 harris41 10603:
1.243 albertel 10604: =head1 PUBLIC SUBROUTINES
1.191 harris41 10605:
1.243 albertel 10606: =head2 Session Environment Functions
1.191 harris41 10607:
1.243 albertel 10608: =over 4
1.191 harris41 10609:
1.394 bowersj2 10610: =item *
10611: X<appenv()>
1.949 raeburn 10612: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10613: the user envirnoment file, and will be restored for each access this
1.620 albertel 10614: user makes during this session, also modifies the %env for the current
1.949 raeburn 10615: process. Optional rolesarrayref - if defined contains a reference to an array
10616: of roles which are exempt from the restriction on modifying user.role entries
10617: in the user's environment.db and in %env.
1.191 harris41 10618:
10619: =item *
1.394 bowersj2 10620: X<delenv()>
1.987 raeburn 10621: B<delenv($delthis,$regexp)>: removes all items from the session
10622: environment file that begin with $delthis. If the
10623: optional second arg - $regexp - is true, $delthis is treated as a
10624: regular expression, otherwise \Q$delthis\E is used.
10625: The values are also deleted from the current processes %env.
1.191 harris41 10626:
1.795 albertel 10627: =item * get_env_multiple($name)
10628:
10629: gets $name from the %env hash, it seemlessly handles the cases where multiple
10630: values may be defined and end up as an array ref.
10631:
10632: returns an array of values
10633:
1.243 albertel 10634: =back
10635:
10636: =head2 User Information
1.191 harris41 10637:
1.243 albertel 10638: =over 4
1.191 harris41 10639:
10640: =item *
1.394 bowersj2 10641: X<queryauthenticate()>
10642: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10643: authentication scheme
10644:
10645: =item *
1.394 bowersj2 10646: X<authenticate()>
1.1056.4.3 raeburn 10647: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10648: authenticate user from domain's lib servers (first use the current
10649: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10650: $checkdefauth is optional (value is 1 if a check should be made to
10651: authenticate user using default authentication method, and allow
10652: account creation if username does not have account in the domain).
10653: $clientcancheckhost is optional (value is 1 if checking whether the
10654: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10655:
10656: =item *
1.394 bowersj2 10657: X<homeserver()>
10658: B<homeserver($uname,$udom)>: find the server which has
10659: the user's directory and files (there must be only one), this caches
10660: the answer, and also caches if there is a borken connection.
1.191 harris41 10661:
10662: =item *
1.394 bowersj2 10663: X<idget()>
10664: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10665: (IDs are a unique resource in a domain, there must be only 1 ID per
10666: username, and only 1 username per ID in a specific domain) (returns
10667: hash: id=>name,id=>name)
1.191 harris41 10668:
10669: =item *
1.394 bowersj2 10670: X<idrget()>
10671: B<idrget($udom,@unames)>: find the IDs behind a list of
10672: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10673:
10674: =item *
1.394 bowersj2 10675: X<idput()>
10676: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10677:
10678: =item *
1.394 bowersj2 10679: X<rolesinit()>
10680: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10681:
10682: =item *
1.551 albertel 10683: X<getsection()>
10684: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10685: course $cname, return section name/number or '' for "not in course"
10686: and '-1' for "no section"
10687:
10688: =item *
1.394 bowersj2 10689: X<userenvironment()>
10690: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10691: passed in @what from the requested user's environment, returns a hash
10692:
1.858 raeburn 10693: =item *
10694: X<userlog_query()>
1.859 albertel 10695: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10696: activity.log file. %filters defines filters applied when parsing the
10697: log file. These can be start or end timestamps, or the type of action
10698: - log to look for Login or Logout events, check for Checkin or
10699: Checkout, role for role selection. The response is in the form
10700: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10701: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10702:
1.243 albertel 10703: =back
10704:
10705: =head2 User Roles
10706:
10707: =over 4
10708:
10709: =item *
10710:
1.810 raeburn 10711: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10712: F: full access
10713: U,I,K: authentication modes (cxx only)
10714: '': forbidden
10715: 1: user needs to choose course
10716: 2: browse allowed
1.766 albertel 10717: A: passphrase authentication needed
1.243 albertel 10718:
10719: =item *
10720:
10721: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10722: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10723: and course level
10724:
10725: =item *
10726:
1.988 raeburn 10727: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10728: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10729: $type is Course (default) or Community.
1.988 raeburn 10730: If $forcedefault evaluates to true, text returned will be default
10731: text for $type. Otherwise, if this is a course, the text returned
10732: will be a custom name for the role (if defined in the course's
10733: environment). If no custom name is defined the default is returned.
10734:
1.832 raeburn 10735: =item *
10736:
1.935 raeburn 10737: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10738: All arguments are optional. Returns a hash of a roles, either for
10739: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10740: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10741: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10742: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10743: For each key, value is set to colon-separated start and end times for
10744: the role. If no username and domain are specified, will default to
1.934 raeburn 10745: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10746: of role statuses (active, future or previous), roles
10747: (e.g., cc,in, st etc.) and domains of the roles which can be used
10748: to restrict the list of roles reported. If no array ref is
10749: provided for types, will default to return only active roles.
1.834 albertel 10750:
1.243 albertel 10751: =back
10752:
10753: =head2 User Modification
10754:
10755: =over 4
10756:
10757: =item *
10758:
1.957 raeburn 10759: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10760: user for the level given by URL. Optional start and end dates (leave empty
10761: string or zero for "no date")
1.191 harris41 10762:
10763: =item *
10764:
1.243 albertel 10765: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10766: change a users, password, possible return values are: ok,
10767: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10768: refused
1.191 harris41 10769:
10770: =item *
10771:
1.243 albertel 10772: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10773:
10774: =item *
10775:
1.1056.4.1 raeburn 10776: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10777: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10778:
10779: will update user information (firstname,middlename,lastname,generation,
10780: permanentemail), and if forceid is true, student/employee ID also.
10781: A user's institutional affiliation(s) can also be updated.
10782: User information fields will not be overwritten with empty entries
10783: unless the field is included in the $candelete array reference.
10784: This array is included when a single user is modified via "Manage Users",
10785: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10786:
10787: =item *
10788:
1.286 matthew 10789: modifystudent
10790:
1.957 raeburn 10791: modify a student's enrollment and identification information.
1.286 matthew 10792: The course id is resolved based on the current users environment.
10793: This means the envoking user must be a course coordinator or otherwise
10794: associated with a course.
10795:
1.297 matthew 10796: This call is essentially a wrapper for lonnet::modifyuser and
10797: lonnet::modify_student_enrollment
1.286 matthew 10798:
10799: Inputs:
10800:
10801: =over 4
10802:
1.957 raeburn 10803: =item B<$udom> Student's loncapa domain
1.286 matthew 10804:
1.957 raeburn 10805: =item B<$uname> Student's loncapa login name
1.286 matthew 10806:
1.964 bisitz 10807: =item B<$uid> Student/Employee ID
1.286 matthew 10808:
1.957 raeburn 10809: =item B<$umode> Student's authentication mode
1.286 matthew 10810:
1.957 raeburn 10811: =item B<$upass> Student's password
1.286 matthew 10812:
1.957 raeburn 10813: =item B<$first> Student's first name
1.286 matthew 10814:
1.957 raeburn 10815: =item B<$middle> Student's middle name
1.286 matthew 10816:
1.957 raeburn 10817: =item B<$last> Student's last name
1.286 matthew 10818:
1.957 raeburn 10819: =item B<$gene> Student's generation
1.286 matthew 10820:
1.957 raeburn 10821: =item B<$usec> Student's section in course
1.286 matthew 10822:
10823: =item B<$end> Unix time of the roles expiration
10824:
10825: =item B<$start> Unix time of the roles start date
10826:
10827: =item B<$forceid> If defined, allow $uid to be changed
10828:
10829: =item B<$desiredhome> server to use as home server for student
10830:
1.957 raeburn 10831: =item B<$email> Student's permanent e-mail address
10832:
10833: =item B<$type> Type of enrollment (auto or manual)
10834:
1.963 raeburn 10835: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10836:
10837: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10838:
1.963 raeburn 10839: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10840:
1.963 raeburn 10841: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10842:
1.963 raeburn 10843: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10844:
1.286 matthew 10845: =back
1.297 matthew 10846:
10847: =item *
10848:
10849: modify_student_enrollment
10850:
10851: Change a students enrollment status in a class. The environment variable
10852: 'role.request.course' must be defined for this function to proceed.
10853:
10854: Inputs:
10855:
10856: =over 4
10857:
10858: =item $udom, students domain
10859:
10860: =item $uname, students name
10861:
10862: =item $uid, students user id
10863:
10864: =item $first, students first name
10865:
10866: =item $middle
10867:
10868: =item $last
10869:
10870: =item $gene
10871:
10872: =item $usec
10873:
10874: =item $end
10875:
10876: =item $start
10877:
1.957 raeburn 10878: =item $type
10879:
10880: =item $locktype
10881:
10882: =item $cid
10883:
10884: =item $selfenroll
10885:
10886: =item $context
10887:
1.297 matthew 10888: =back
10889:
1.191 harris41 10890:
10891: =item *
10892:
1.243 albertel 10893: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10894: custom role; give a custom role to a user for the level given by URL. Specify
10895: name and domain of role author, and role name
1.191 harris41 10896:
10897: =item *
10898:
1.243 albertel 10899: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10900:
10901: =item *
10902:
1.243 albertel 10903: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10904:
10905: =back
10906:
10907: =head2 Course Infomation
10908:
10909: =over 4
1.191 harris41 10910:
10911: =item *
10912:
1.631 albertel 10913: coursedescription($courseid) : returns a hash of information about the
10914: specified course id, including all environment settings for the
10915: course, the description of the course will be in the hash under the
10916: key 'description'
1.191 harris41 10917:
10918: =item *
10919:
1.624 albertel 10920: resdata($name,$domain,$type,@which) : request for current parameter
10921: setting for a specific $type, where $type is either 'course' or 'user',
10922: @what should be a list of parameters to ask about. This routine caches
10923: answers for 5 minutes.
1.243 albertel 10924:
1.877 foxr 10925: =item *
10926:
10927: get_courseresdata($courseid, $domain) : dump the entire course resource
10928: data base, returning a hash that is keyed by the resource name and has
10929: values that are the resource value. I believe that the timestamps and
10930: versions are also returned.
10931:
10932:
1.243 albertel 10933: =back
10934:
10935: =head2 Course Modification
10936:
10937: =over 4
1.191 harris41 10938:
10939: =item *
10940:
1.243 albertel 10941: writecoursepref($courseid,%prefs) : write preferences (environment
10942: database) for a course
1.191 harris41 10943:
10944: =item *
10945:
1.1011 raeburn 10946: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10947:
10948: =item *
10949:
1.1038 raeburn 10950: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10951:
10952: =back
10953:
10954: =head2 Resource Subroutines
10955:
10956: =over 4
1.191 harris41 10957:
10958: =item *
10959:
1.243 albertel 10960: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10961:
10962: =item *
10963:
1.243 albertel 10964: repcopy($filename) : subscribes to the requested file, and attempts to
10965: replicate from the owning library server, Might return
1.607 raeburn 10966: 'unavailable', 'not_found', 'forbidden', 'ok', or
10967: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10968: resource. Expects the local filesystem pathname
10969: (/home/httpd/html/res/....)
10970:
10971: =back
10972:
10973: =head2 Resource Information
10974:
10975: =over 4
1.191 harris41 10976:
10977: =item *
10978:
1.243 albertel 10979: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10980: a vairety of different possible values, $varname should be a request
10981: string, and the other parameters can be used to specify who and what
10982: one is asking about.
10983:
10984: Possible values for $varname are environment.lastname (or other item
10985: from the envirnment hash), user.name (or someother aspect about the
10986: user), resource.0.maxtries (or some other part and parameter of a
10987: resource)
1.204 albertel 10988:
10989: =item *
10990:
1.243 albertel 10991: directcondval($number) : get current value of a condition; reads from a state
10992: string
1.204 albertel 10993:
10994: =item *
10995:
1.243 albertel 10996: condval($condidx) : value of condition index based on state
1.204 albertel 10997:
10998: =item *
10999:
1.243 albertel 11000: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11001: resource's metadata, $what should be either a specific key, or either
11002: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11003: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11004:
11005: this function automatically caches all requests
1.191 harris41 11006:
11007: =item *
11008:
1.243 albertel 11009: metadata_query($query,$custom,$customshow) : make a metadata query against the
11010: network of library servers; returns file handle of where SQL and regex results
11011: will be stored for query
1.191 harris41 11012:
11013: =item *
11014:
1.243 albertel 11015: symbread($filename) : return symbolic list entry (filename argument optional);
11016: returns the data handle
1.191 harris41 11017:
11018: =item *
11019:
1.243 albertel 11020: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11021: a possible symb for the URL in $thisfn, and if is an encryypted
11022: resource that the user accessed using /enc/ returns a 1 on success, 0
11023: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11024: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11025:
1.191 harris41 11026:
11027: =item *
11028:
1.243 albertel 11029: symbclean($symb) : removes versions numbers from a symb, returns the
11030: cleaned symb
1.191 harris41 11031:
11032: =item *
11033:
1.243 albertel 11034: is_on_map($uri) : checks if the $uri is somewhere on the current
11035: course map, user must be in a course for it to work.
1.191 harris41 11036:
11037: =item *
11038:
1.243 albertel 11039: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11040:
11041: =item *
11042:
1.243 albertel 11043: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11044: a random seed, all arguments are optional, if they aren't sent it uses the
11045: environment to derive them. Note: if symb isn't sent and it can't get one
11046: from &symbread it will use the current time as its return value
1.191 harris41 11047:
11048: =item *
11049:
1.243 albertel 11050: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11051: unfakeable, receipt
1.191 harris41 11052:
11053: =item *
11054:
1.620 albertel 11055: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11056:
11057: =item *
11058:
1.243 albertel 11059: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11060:
11061: =item *
11062:
1.243 albertel 11063: 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 11064:
11065: =item *
11066:
1.243 albertel 11067: 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 11068:
11069: =item *
11070:
1.243 albertel 11071: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11072:
11073: =item *
11074:
1.243 albertel 11075: devalidate($symb) : devalidate temporary spreadsheet calculations,
11076: forcing spreadsheet to reevaluate the resource scores next time.
11077:
11078: =back
11079:
11080: =head2 Storing/Retreiving Data
11081:
11082: =over 4
1.191 harris41 11083:
11084: =item *
11085:
1.243 albertel 11086: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11087: for this url; hashref needs to be given and should be a \%hashname; the
11088: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11089: be derived from the env
1.191 harris41 11090:
11091: =item *
11092:
1.243 albertel 11093: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11094: uses critical subroutine
1.191 harris41 11095:
11096: =item *
11097:
1.243 albertel 11098: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11099: all args are optional
1.191 harris41 11100:
11101: =item *
11102:
1.717 albertel 11103: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11104: dumps the complete (or key matching regexp) namespace into a hash
11105: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11106: normally &store()ed into
11107:
11108: $range should be either an integer '100' (give me the first 100
11109: matching records)
11110: or be two integers sperated by a - with no spaces
11111: '30-50' (give me the 30th through the 50th matching
11112: records)
11113:
11114:
11115: =item *
11116:
11117: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11118: replaces a &store() version of data with a replacement set of data
11119: for a particular resource in a namespace passed in the $storehash hash
11120: reference
11121:
11122: =item *
11123:
1.243 albertel 11124: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11125: works very similar to store/cstore, but all data is stored in a
11126: temporary location and can be reset using tmpreset, $storehash should
11127: be a hash reference, returns nothing on success
1.191 harris41 11128:
11129: =item *
11130:
1.243 albertel 11131: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11132: similar to restore, but all data is stored in a temporary location and
11133: can be reset using tmpreset. Returns a hash of values on success,
11134: error string otherwise.
1.191 harris41 11135:
11136: =item *
11137:
1.243 albertel 11138: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11139: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11140:
11141: =item *
11142:
1.243 albertel 11143: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11144: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11145:
11146: =item *
11147:
1.243 albertel 11148: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11149: namesp ($udom and $uname are optional)
1.191 harris41 11150:
11151: =item *
11152:
1.702 albertel 11153: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11154: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11155: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11156:
1.702 albertel 11157: $range should be either an integer '100' (give me the first 100
11158: matching records)
11159: or be two integers sperated by a - with no spaces
11160: '30-50' (give me the 30th through the 50th matching
11161: records)
1.449 matthew 11162: =item *
11163:
11164: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11165: $store can be a scalar, an array reference, or if the amount to be
11166: incremented is > 1, a hash reference.
11167:
11168: ($udom and $uname are optional)
1.191 harris41 11169:
11170: =item *
11171:
1.243 albertel 11172: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11173: ($udom and $uname are optional)
1.191 harris41 11174:
11175: =item *
11176:
1.243 albertel 11177: cput($namespace,$storehash,$udom,$uname) : critical put
11178: ($udom and $uname are optional)
1.191 harris41 11179:
11180: =item *
11181:
1.748 albertel 11182: newput($namespace,$storehash,$udom,$uname) :
11183:
11184: Attempts to store the items in the $storehash, but only if they don't
11185: currently exist, if this succeeds you can be certain that you have
11186: successfully created a new key value pair in the $namespace db.
11187:
11188:
11189: Args:
11190: $namespace: name of database to store values to
11191: $storehash: hashref to store to the db
11192: $udom: (optional) domain of user containing the db
11193: $uname: (optional) name of user caontaining the db
11194:
11195: Returns:
11196: 'ok' -> succeeded in storing all keys of $storehash
11197: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11198: least <key> already existed in the db (other
11199: requested keys may also already exist)
1.967 bisitz 11200: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11201: 'con_lost' -> unable to contact request server
11202: 'refused' -> action was not allowed by remote machine
11203:
11204:
11205: =item *
11206:
1.243 albertel 11207: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11208: reference filled in from namesp (encrypts the return communication)
11209: ($udom and $uname are optional)
1.191 harris41 11210:
11211: =item *
11212:
1.243 albertel 11213: log($udom,$name,$home,$message) : write to permanent log for user; use
11214: critical subroutine
11215:
1.806 raeburn 11216: =item *
11217:
1.860 raeburn 11218: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11219: array reference filled in from namespace found in domain level on either
11220: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11221:
11222: =item *
11223:
1.860 raeburn 11224: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11225: domain level either on specified domain server ($uhome) or primary domain
11226: server ($udom and $uhome are optional)
1.806 raeburn 11227:
1.943 raeburn 11228: =item *
11229:
11230: get_domain_defaults($target_domain) : returns hash with defaults for
11231: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11232: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11233: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11234: Values are retrieved from cache (if current), or from domain's configuration.db
11235: (if available), or lastly from values in lonTabs/dns_domain,tab,
11236: or lonTabs/domain.tab.
11237:
11238: %domdefaults = &get_auth_defaults($target_domain);
11239:
1.243 albertel 11240: =back
11241:
11242: =head2 Network Status Functions
11243:
11244: =over 4
1.191 harris41 11245:
11246: =item *
11247:
11248: dirlist($uri) : return directory list based on URI
11249:
11250: =item *
11251:
1.243 albertel 11252: spareserver() : find server with least workload from spare.tab
11253:
1.986 foxr 11254:
11255: =item *
11256:
11257: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11258: if there is no corresponding loncapa host.
11259:
1.243 albertel 11260: =back
11261:
1.986 foxr 11262:
1.243 albertel 11263: =head2 Apache Request
11264:
11265: =over 4
1.191 harris41 11266:
11267: =item *
11268:
1.243 albertel 11269: ssi($url,%hash) : server side include, does a complete request cycle on url to
11270: localhost, posts hash
11271:
11272: =back
11273:
11274: =head2 Data to String to Data
11275:
11276: =over 4
1.191 harris41 11277:
11278: =item *
11279:
1.243 albertel 11280: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11281: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11282:
11283: =item *
11284:
1.243 albertel 11285: hashref2str($hashref) : convert a hashref into a string complete with
11286: escaping and '=' and '&' separators, supports elements that are
11287: arrayrefs and hashrefs
1.191 harris41 11288:
11289: =item *
11290:
1.243 albertel 11291: arrayref2str($arrayref) : convert an arrayref into a string complete
11292: with escaping and '&' separators, supports elements that are arrayrefs
11293: and hashrefs
1.191 harris41 11294:
11295: =item *
11296:
1.243 albertel 11297: str2hash($string) : convert string to hash using unescaping and
11298: splitting on '=' and '&', supports elements that are arrayrefs and
11299: hashrefs
1.191 harris41 11300:
11301: =item *
11302:
1.243 albertel 11303: str2array($string) : convert string to hash using unescaping and
11304: splitting on '&', supports elements that are arrayrefs and hashrefs
11305:
11306: =back
11307:
11308: =head2 Logging Routines
11309:
11310: =over 4
11311:
11312: These routines allow one to make log messages in the lonnet.log and
11313: lonnet.perm logfiles.
1.191 harris41 11314:
11315: =item *
11316:
1.243 albertel 11317: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11318:
11319: =item *
11320:
1.243 albertel 11321: logthis() : append message to the normal lonnet.log file, it gets
11322: preiodically rolled over and deleted.
1.191 harris41 11323:
11324: =item *
11325:
1.243 albertel 11326: logperm() : append a permanent message to lonnet.perm.log, this log
11327: file never gets deleted by any automated portion of the system, only
11328: messages of critical importance should go in here.
11329:
11330: =back
11331:
11332: =head2 General File Helper Routines
11333:
11334: =over 4
1.191 harris41 11335:
11336: =item *
11337:
1.481 raeburn 11338: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11339: (a) files in /uploaded
11340: (i) If a local copy of the file exists -
11341: compares modification date of local copy with last-modified date for
11342: definitive version stored on home server for course. If local copy is
11343: stale, requests a new version from the home server and stores it.
11344: If the original has been removed from the home server, then local copy
11345: is unlinked.
11346: (ii) If local copy does not exist -
11347: requests the file from the home server and stores it.
11348:
11349: If $caller is 'uploadrep':
11350: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11351: for request for files originally uploaded via DOCS.
11352: - returns 'ok' if fresh local copy now available, -1 otherwise.
11353:
11354: Otherwise:
11355: This indicates a call from the content generation phase of the request.
11356: - returns the entire contents of the file or -1.
11357:
11358: (b) files in /res
11359: - returns the entire contents of a file or -1;
11360: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11361:
1.712 albertel 11362:
11363: =item *
11364:
11365: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11366: reference
11367:
11368: returns either a stat() list of data about the file or an empty list
11369: if the file doesn't exist or couldn't find out about it (connection
11370: problems or user unknown)
11371:
1.191 harris41 11372: =item *
11373:
1.243 albertel 11374: filelocation($dir,$file) : returns file system location of a file
11375: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11376: directory that relative $file lookups are to looked in ($dir of /a/dir
11377: and a file of ../bob will become /a/bob)
1.191 harris41 11378:
11379: =item *
11380:
11381: hreflocation($dir,$file) : returns file system location or a URL; same as
11382: filelocation except for hrefs
11383:
11384: =item *
11385:
11386: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11387:
1.243 albertel 11388: =back
11389:
1.608 albertel 11390: =head2 Usererfile file routines (/uploaded*)
11391:
11392: =over 4
11393:
11394: =item *
11395:
11396: userfileupload(): main rotine for putting a file in a user or course's
11397: filespace, arguments are,
11398:
1.620 albertel 11399: formname - required - this is the name of the element in $env where the
1.608 albertel 11400: filename, and the contents of the file to create/modifed exist
1.620 albertel 11401: the filename is in $env{'form.'.$formname.'.filename'} and the
11402: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11403: coursedoc - if true, store the file in the course of the active role
11404: of the current user
11405: subdir - required - subdirectory to put the file in under ../userfiles/
11406: if undefined, it will be placed in "unknown"
11407:
11408: (This routine calls clean_filename() to remove any dangerous
11409: characters from the filename, and then calls finuserfileupload() to
11410: complete the transaction)
11411:
11412: returns either the url of the uploaded file (/uploaded/....) if successful
11413: and /adm/notfound.html if unsuccessful
11414:
11415: =item *
11416:
11417: clean_filename(): routine for cleaing a filename up for storage in
11418: userfile space, argument is:
11419:
11420: filename - proposed filename
11421:
11422: returns: the new clean filename
11423:
11424: =item *
11425:
11426: finishuserfileupload(): routine that creaes and sends the file to
11427: userspace, probably shouldn't be called directly
11428:
11429: docuname: username or courseid of destination for the file
11430: docudom: domain of user/course of destination for the file
11431: formname: same as for userfileupload()
11432: fname: filename (inculding subdirectories) for the file
11433:
11434: returns either the url of the uploaded file (/uploaded/....) if successful
11435: and /adm/notfound.html if unsuccessful
11436:
11437: =item *
11438:
11439: renameuserfile(): renames an existing userfile to a new name
11440:
11441: Args:
11442: docuname: username or courseid of destination for the file
11443: docudom: domain of user/course of destination for the file
11444: old: current file name (including any subdirs under userfiles)
11445: new: desired file name (including any subdirs under userfiles)
11446:
11447: =item *
11448:
11449: mkdiruserfile(): creates a directory is a userfiles dir
11450:
11451: Args:
11452: docuname: username or courseid of destination for the file
11453: docudom: domain of user/course of destination for the file
11454: dir: dir to create (including any subdirs under userfiles)
11455:
11456: =item *
11457:
11458: removeuserfile(): removes a file that exists in userfiles
11459:
11460: Args:
11461: docuname: username or courseid of destination for the file
11462: docudom: domain of user/course of destination for the file
11463: fname: filname to delete (including any subdirs under userfiles)
11464:
11465: =item *
11466:
11467: removeuploadedurl(): convience function for removeuserfile()
11468:
11469: Args:
11470: url: a full /uploaded/... url to delete
11471:
1.747 albertel 11472: =item *
11473:
11474: get_portfile_permissions():
11475: Args:
11476: domain: domain of user or course contain the portfolio files
11477: user: name of user or num of course contain the portfolio files
11478: Returns:
11479: hashref of a dump of the proper file_permissions.db
11480:
11481:
11482: =item *
11483:
11484: get_access_controls():
11485:
11486: Args:
11487: current_permissions: the hash ref returned from get_portfile_permissions()
11488: group: (optional) the group you want the files associated with
11489: file: (optional) the file you want access info on
11490:
11491: Returns:
1.749 raeburn 11492: a hash (keys are file names) of hashes containing
11493: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11494: values are XML containing access control settings (see below)
1.747 albertel 11495:
11496: Internal notes:
11497:
1.749 raeburn 11498: access controls are stored in file_permissions.db as key=value pairs.
11499: key -> path to file/file_name\0uniqueID:scope_end_start
11500: where scope -> public,guest,course,group,domains or users.
11501: end -> UNIX time for end of access (0 -> no end date)
11502: start -> UNIX time for start of access
11503:
11504: value -> XML description of access control
11505: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11506: <start></start>
11507: <end></end>
11508:
11509: <password></password> for scope type = guest
11510:
11511: <domain></domain> for scope type = course or group
11512: <number></number>
11513: <roles id="">
11514: <role></role>
11515: <access></access>
11516: <section></section>
11517: <group></group>
11518: </roles>
11519:
11520: <dom></dom> for scope type = domains
11521:
11522: <users> for scope type = users
11523: <user>
11524: <uname></uname>
11525: <udom></udom>
11526: </user>
11527: </users>
11528: </scope>
11529:
11530: Access data is also aggregated for each file in an additional key=value pair:
11531: key -> path to file/file_name\0accesscontrol
11532: value -> reference to hash
11533: hash contains key = value pairs
11534: where key = uniqueID:scope_end_start
11535: value = UNIX time record was last updated
11536:
11537: Used to improve speed of look-ups of access controls for each file.
11538:
11539: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11540:
11541: modify_access_controls():
11542:
11543: Modifies access controls for a portfolio file
11544: Args
11545: 1. file name
11546: 2. reference to hash of required changes,
11547: 3. domain
11548: 4. username
11549: where domain,username are the domain of the portfolio owner
11550: (either a user or a course)
11551:
11552: Returns:
11553: 1. result of additions or updates ('ok' or 'error', with error message).
11554: 2. result of deletions ('ok' or 'error', with error message).
11555: 3. reference to hash of any new or updated access controls.
11556: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11557: key = integer (inbound ID)
11558: value = uniqueID
1.747 albertel 11559:
1.608 albertel 11560: =back
11561:
1.243 albertel 11562: =head2 HTTP Helper Routines
11563:
11564: =over 4
11565:
1.191 harris41 11566: =item *
11567:
11568: escape() : unpack non-word characters into CGI-compatible hex codes
11569:
11570: =item *
11571:
11572: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11573:
1.243 albertel 11574: =back
11575:
11576: =head1 PRIVATE SUBROUTINES
11577:
11578: =head2 Underlying communication routines (Shouldn't call)
11579:
11580: =over 4
11581:
11582: =item *
11583:
11584: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11585:
11586: =item *
11587:
11588: reply() : uses subreply to send a message to remote machine, logs all failures
11589:
11590: =item *
11591:
11592: critical() : passes a critical message to another server; if cannot
11593: get through then place message in connection buffer directory and
11594: returns con_delayed, if incapable of saving message, returns
11595: con_failed
11596:
11597: =item *
11598:
11599: reconlonc() : tries to reconnect lonc client processes.
11600:
11601: =back
11602:
11603: =head2 Resource Access Logging
11604:
11605: =over 4
11606:
11607: =item *
11608:
11609: flushcourselogs() : flush (save) buffer logs and access logs
11610:
11611: =item *
11612:
11613: courselog($what) : save message for course in hash
11614:
11615: =item *
11616:
11617: courseacclog($what) : save message for course using &courselog(). Perform
11618: special processing for specific resource types (problems, exams, quizzes, etc).
11619:
1.191 harris41 11620: =item *
11621:
11622: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11623: as a PerlChildExitHandler
1.243 albertel 11624:
11625: =back
11626:
11627: =head2 Other
11628:
11629: =over 4
11630:
11631: =item *
11632:
11633: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11634:
11635: =back
11636:
11637: =cut
1.877 foxr 11638:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>