Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.93.4.11
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.93.4 11(raebu 4:18): # $Id: lonnet.pm,v 1.1172.2.93.4.10 2018/04/29 00:56:53 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.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.1172.2.79 raeburn 105: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.93.4 7(raebur 145:7): open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.1172.2.93.4 7(raebur 157:7): if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.1172.2.93.4 7(raebur 170:7): if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 373: sleep(0.1);
1.549 foxr 374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.1172.2.79 raeburn 391: sleep(0.1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.93.4 7(raebur 439:7): if (open(my $fh,"<",$loncfile)) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
1.1172.2.93.4 7(raebur 479:7): if (open($dfh,">",$dfilename)) {
1.448 albertel 480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
1.1172.2.79 raeburn 484: sleep 1;
1.1 albertel 485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
1.1172.2.93.4 7(raebur 488:7): if (open($dfh,"<",$dfilename)) {
1.448 albertel 489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.93.4 3(raebur 604:7): my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.1172.2.93.4 3(raebur 619:7): if (!-e "$lonidsdir/$handle.id") {
620:7): if ((ref($domref)) && ($name eq 'lonID') &&
621:7): ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
622:7): my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
623:7): if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
624:7): $$domref = $possudom;
625:7): }
626:7): }
627:7): return undef;
628:7): }
1.916 albertel 629:
1.917 albertel 630: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
631: return undef if (!$opened);
1.916 albertel 632:
633: flock($idf,LOCK_SH);
634: my %disk_env;
635: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
636: &GDBM_READER(),0640)) {
637: return undef;
638: }
639:
640: if (!defined($disk_env{'user.name'})
641: || !defined($disk_env{'user.domain'})) {
642: return undef;
643: }
1.1172.2.18 raeburn 644:
1.1172.2.36 raeburn 645: if (ref($userhashref) eq 'HASH') {
646: $userhashref->{'name'} = $disk_env{'user.name'};
647: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 648: }
649:
1.916 albertel 650: return $handle;
651: }
652:
1.830 albertel 653: sub timed_flock {
654: my ($file,$lock_type) = @_;
655: my $failed=0;
656: eval {
657: local $SIG{__DIE__}='DEFAULT';
658: local $SIG{ALRM}=sub {
659: $failed=1;
660: die("failed lock");
661: };
662: alarm(13);
663: flock($file,$lock_type);
664: alarm(0);
665: };
666: if ($failed) {
667: return undef;
668: } else {
669: return 1;
670: }
671: }
672:
1.5 www 673: # ---------------------------------------------------------- Append Environment
674:
675: sub appenv {
1.949 raeburn 676: my ($newenv,$roles) = @_;
677: if (ref($newenv) eq 'HASH') {
678: foreach my $key (keys(%{$newenv})) {
679: my $refused = 0;
680: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
681: $refused = 1;
682: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 683: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 684: if (grep(/^\Q$role\E$/,@{$roles})) {
685: $refused = 0;
686: }
687: }
688: }
689: if ($refused) {
690: &logthis("<font color=\"blue\">WARNING: ".
691: "Attempt to modify environment ".$key." to ".$newenv->{$key}
692: .'</font>');
693: delete($newenv->{$key});
694: } else {
695: $env{$key}=$newenv->{$key};
696: }
697: }
1.1172.2.93.4 11(raebu 698:18): my $lonids = $perlvar{'lonIDsDir'};
699:18): if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
700:18): my $opened = open(my $env_file,'+<',$env{'user.environment'});
701:18): if ($opened
702:18): && &timed_flock($env_file,LOCK_EX)
703:18): &&
704:18): tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705:18): (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
706:18): while (my ($key,$value) = each(%{$newenv})) {
707:18): $disk_env{$key} = $value;
708:18): }
709:18): untie(%disk_env);
710:18): }
1.35 www 711: }
1.191 harris41 712: }
1.56 www 713: return 'ok';
714: }
715: # ----------------------------------------------------- Delete from Environment
716:
717: sub delenv {
1.1104 raeburn 718: my ($delthis,$regexp,$roles) = @_;
719: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
720: my $refused = 1;
721: if (ref($roles) eq 'ARRAY') {
722: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
723: if (grep(/^\Q$role\E$/,@{$roles})) {
724: $refused = 0;
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to delete from environment ".$delthis);
730: return 'error';
731: }
1.56 www 732: }
1.917 albertel 733: my $opened = open(my $env_file,'+<',$env{'user.environment'});
734: if ($opened
1.915 albertel 735: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 736: &&
737: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
738: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 739: foreach my $key (keys(%disk_env)) {
1.987 raeburn 740: if ($regexp) {
741: if ($key=~/^$delthis/) {
742: delete($env{$key});
743: delete($disk_env{$key});
744: }
745: } else {
746: if ($key=~/^\Q$delthis\E/) {
747: delete($env{$key});
748: delete($disk_env{$key});
749: }
750: }
1.448 albertel 751: }
1.783 albertel 752: untie(%disk_env);
1.5 www 753: }
754: return 'ok';
1.369 albertel 755: }
756:
1.790 albertel 757: sub get_env_multiple {
758: my ($name) = @_;
759: my @values;
760: if (defined($env{$name})) {
761: # exists is it an array
762: if (ref($env{$name})) {
763: @values=@{ $env{$name} };
764: } else {
765: $values[0]=$env{$name};
766: }
767: }
768: return(@values);
769: }
770:
1.958 www 771: # ------------------------------------------------------------------- Locking
772:
773: sub set_lock {
774: my ($text)=@_;
775: $locknum++;
776: my $id=$$.'-'.$locknum;
777: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
778: 'session.lock.'.$id => $text});
779: return $id;
780: }
781:
782: sub get_locks {
783: my $num=0;
784: my %texts=();
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: $num++;
788: $texts{$lock}=$env{'session.lock.'.$lock};
789: }
790: }
791: return ($num,%texts);
792: }
793:
794: sub remove_lock {
795: my ($id)=@_;
796: my $newlocks='';
797: foreach my $lock (split(/\,/,$env{'session.locks'})) {
798: if (($lock=~/\w/) && ($lock ne $id)) {
799: $newlocks.=','.$lock;
800: }
801: }
802: &appenv({'session.locks' => $newlocks});
803: &delenv('session.lock.'.$id);
804: }
805:
806: sub remove_all_locks {
807: my $activelocks=$env{'session.locks'};
808: foreach my $lock (split(/\,/,$env{'session.locks'})) {
809: if ($lock=~/\w/) {
810: &remove_lock($lock);
811: }
812: }
813: }
814:
815:
1.369 albertel 816: # ------------------------------------------ Find out current server userload
817: sub userload {
818: my $numusers=0;
819: {
820: opendir(LONIDS,$perlvar{'lonIDsDir'});
821: my $filename;
822: my $curtime=time;
823: while ($filename=readdir(LONIDS)) {
1.925 albertel 824: next if ($filename eq '.' || $filename eq '..');
825: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 826: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 827: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 828: }
829: closedir(LONIDS);
830: }
831: my $userloadpercent=0;
832: my $maxuserload=$perlvar{'lonUserLoadLim'};
833: if ($maxuserload) {
1.371 albertel 834: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 835: }
1.372 albertel 836: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 837: return $userloadpercent;
1.283 www 838: }
839:
1.1 albertel 840: # ------------------------------ Find server with least workload from spare.tab
1.11 www 841:
1.1 albertel 842: sub spareserver {
1.1083 raeburn 843: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 844: my $spare_server;
1.370 albertel 845: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 846: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
847: : $userloadpercent;
1.1083 raeburn 848: my ($uint_dom,$remotesessions);
849: if (($udom ne '') && (&domain($udom) ne '')) {
850: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
851: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
852: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
853: $remotesessions = $udomdefaults{'remotesessions'};
854: }
1.1123 raeburn 855: my $spareshash = &this_host_spares($udom);
856: if (ref($spareshash) eq 'HASH') {
857: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
860: $try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
1.1083 raeburn 864: }
1.784 albertel 865:
1.1123 raeburn 866: my $found_server = ($spare_server ne '' && $lowest_load < 100);
867:
868: if (!$found_server) {
869: if (ref($spareshash->{'default'}) eq 'ARRAY') {
870: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 871: next unless (&spare_can_host($udom,$uint_dom,
872: $remotesessions,$try_server));
1.1123 raeburn 873: ($spare_server, $lowest_load) =
874: &compare_server_load($try_server, $spare_server, $lowest_load);
875: }
876: }
877: }
1.784 albertel 878: }
879:
880: if (!$want_server_name) {
1.968 raeburn 881: my $protocol = 'http';
882: if ($protocol{$spare_server} eq 'https') {
883: $protocol = $protocol{$spare_server};
884: }
1.1001 raeburn 885: if (defined($spare_server)) {
886: my $hostname = &hostname($spare_server);
1.1083 raeburn 887: if (defined($hostname)) {
1.1001 raeburn 888: $spare_server = $protocol.'://'.$hostname;
889: }
890: }
1.784 albertel 891: }
892: return $spare_server;
893: }
894:
895: sub compare_server_load {
1.1172.2.41 raeburn 896: my ($try_server, $spare_server, $lowest_load, $required) = @_;
897:
898: if ($required) {
899: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
900: my $remoterev = &get_server_loncaparev(undef,$try_server);
901: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
902: if (($major eq '' && $minor eq '') ||
903: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
904: return ($spare_server,$lowest_load);
905: }
906: }
1.784 albertel 907:
908: my $loadans = &reply('load', $try_server);
909: my $userloadans = &reply('userload',$try_server);
910:
911: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 912: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 913: }
914:
915: my $load;
916: if ($loadans =~ /\d/) {
917: if ($userloadans =~ /\d/) {
918: #both are numbers, pick the bigger one
919: $load = ($loadans > $userloadans) ? $loadans
920: : $userloadans;
1.411 albertel 921: } else {
1.784 albertel 922: $load = $loadans;
1.411 albertel 923: }
1.784 albertel 924: } else {
925: $load = $userloadans;
926: }
927:
928: if (($load =~ /\d/) && ($load < $lowest_load)) {
929: $spare_server = $try_server;
930: $lowest_load = $load;
1.370 albertel 931: }
1.784 albertel 932: return ($spare_server,$lowest_load);
1.202 matthew 933: }
1.914 albertel 934:
935: # --------------------------- ask offload servers if user already has a session
936: sub find_existing_session {
937: my ($udom,$uname) = @_;
1.1123 raeburn 938: my $spareshash = &this_host_spares($udom);
939: if (ref($spareshash) eq 'HASH') {
940: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
941: foreach my $try_server (@{ $spareshash->{'primary'} }) {
942: return $try_server if (&has_user_session($try_server, $udom, $uname));
943: }
944: }
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
947: return $try_server if (&has_user_session($try_server, $udom, $uname));
948: }
949: }
1.914 albertel 950: }
951: return;
952: }
953:
954: # -------------------------------- ask if server already has a session for user
955: sub has_user_session {
956: my ($lonid,$udom,$uname) = @_;
957: my $result = &reply(join(':','userhassession',
958: map {&escape($_)} ($udom,$uname)),$lonid);
959: return 1 if ($result eq 'ok');
960:
961: return 0;
962: }
963:
1.1076 raeburn 964: # --------- determine least loaded server in a user's domain which allows login
965:
966: sub choose_server {
1.1172.2.47 raeburn 967: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 968: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 969: my %servers = &get_servers($udom);
1.1076 raeburn 970: my $lowest_load = 30000;
1.1172.2.47 raeburn 971: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
972: if ($skiploadbal) {
973: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
974: unless (defined($cached)) {
975: my $cachetime = 60*60*24;
976: my %domconfig =
977: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
978: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
979: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
980: $cachetime);
981: }
982: }
983: }
1.1076 raeburn 984: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 985: my $loginvia;
1.1172.2.47 raeburn 986: if ($skiploadbal) {
987: if (ref($balancers) eq 'HASH') {
988: next if (exists($balancers->{$lonhost}));
989: }
990: }
1.1115 raeburn 991: if ($checkloginvia) {
992: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 993: if ($loginvia) {
994: my ($server,$path) = split(/:/,$loginvia);
995: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 996: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $server) {
998: $portal_path = $path;
1.1151 raeburn 999: $isredirect = 1;
1.1116 raeburn 1000: }
1001: } else {
1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1004: if ($login_host eq $lonhost) {
1005: $portal_path = '';
1.1151 raeburn 1006: $isredirect = '';
1.1116 raeburn 1007: }
1008: }
1009: } else {
1.1076 raeburn 1010: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1011: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1012: }
1013: }
1014: if ($login_host ne '') {
1.1116 raeburn 1015: $hostname = &hostname($login_host);
1.1076 raeburn 1016: }
1.1172.2.88 raeburn 1017: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1018: }
1019:
1.202 matthew 1020: # --------------------------------------------- Try to change a user's password
1021:
1022: sub changepass {
1.799 raeburn 1023: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1024: $currentpass = &escape($currentpass);
1025: $newpass = &escape($newpass);
1.1030 raeburn 1026: my $lonhost = $perlvar{'lonHostID'};
1027: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1028: $server);
1029: if (! $answer) {
1030: &logthis("No reply on password change request to $server ".
1031: "by $uname in domain $udom.");
1032: } elsif ($answer =~ "^ok") {
1033: &logthis("$uname in $udom successfully changed their password ".
1034: "on $server.");
1035: } elsif ($answer =~ "^pwchange_failure") {
1036: &logthis("$uname in $udom was unable to change their password ".
1037: "on $server. The action was blocked by either lcpasswd ".
1038: "or pwchange");
1039: } elsif ($answer =~ "^non_authorized") {
1040: &logthis("$uname in $udom did not get their password correct when ".
1041: "attempting to change it on $server.");
1042: } elsif ($answer =~ "^auth_mode_error") {
1043: &logthis("$uname in $udom attempted to change their password despite ".
1044: "not being locally or internally authenticated on $server.");
1045: } elsif ($answer =~ "^unknown_user") {
1046: &logthis("$uname in $udom attempted to change their password ".
1047: "on $server but were unable to because $server is not ".
1048: "their home server.");
1049: } elsif ($answer =~ "^refused") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1052: } elsif ($answer =~ "invalid_client") {
1053: &logthis("$server refused to change $uname in $udom password because ".
1054: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1055: }
1056: return $answer;
1.1 albertel 1057: }
1058:
1.169 harris41 1059: # ----------------------- Try to determine user's current authentication scheme
1060:
1061: sub queryauthenticate {
1062: my ($uname,$udom)=@_;
1.456 albertel 1063: my $uhome=&homeserver($uname,$udom);
1064: if (!$uhome) {
1065: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1066: return 'no_host';
1067: }
1068: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1069: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1070: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1071: }
1.456 albertel 1072: return $answer;
1.169 harris41 1073: }
1074:
1.1 albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1076:
1.1 albertel 1077: sub authenticate {
1.1073 raeburn 1078: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1079: $upass=&escape($upass);
1080: $uname= &LONCAPA::clean_username($uname);
1.836 www 1081: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1082: my $newhome;
1.836 www 1083: if ((!$uhome) || ($uhome eq 'no_host')) {
1084: # Maybe the machine was offline and only re-appeared again recently?
1085: &reconlonc();
1086: # One more
1.952 raeburn 1087: $uhome=&homeserver($uname,$udom,1);
1088: if (($uhome eq 'no_host') && $checkdefauth) {
1089: if (defined(&domain($udom,'primary'))) {
1090: $newhome=&domain($udom,'primary');
1091: }
1092: if ($newhome ne '') {
1093: $uhome = $newhome;
1094: }
1095: }
1.836 www 1096: if ((!$uhome) || ($uhome eq 'no_host')) {
1097: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1098: return 'no_host';
1099: }
1.1 albertel 1100: }
1.1073 raeburn 1101: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1102: if ($answer eq 'authorized') {
1.952 raeburn 1103: if ($newhome) {
1104: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1105: return 'no_account_on_host';
1106: } else {
1107: &logthis("User $uname at $udom authorized by $uhome");
1108: return $uhome;
1109: }
1.471 albertel 1110: }
1111: if ($answer eq 'non_authorized') {
1112: &logthis("User $uname at $udom rejected by $uhome");
1113: return 'no_host';
1.9 www 1114: }
1.471 albertel 1115: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1116: return 'no_host';
1117: }
1118:
1.1073 raeburn 1119: sub can_host_session {
1.1074 raeburn 1120: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1121: my $canhost = 1;
1.1074 raeburn 1122: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1123: if (ref($remotesessions) eq 'HASH') {
1124: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1126: $canhost = 0;
1127: } else {
1128: $canhost = 1;
1129: }
1130: }
1131: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1132: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1133: $canhost = 1;
1134: } else {
1135: $canhost = 0;
1136: }
1137: }
1138: if ($canhost) {
1139: if ($remotesessions->{'version'} ne '') {
1140: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1141: if ($reqmajor ne '' && $reqminor ne '') {
1142: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1143: my $major = $1;
1144: my $minor = $2;
1145: if (($major < $reqmajor ) ||
1146: (($major == $reqmajor) && ($minor < $reqminor))) {
1147: $canhost = 0;
1148: }
1149: } else {
1150: $canhost = 0;
1151: }
1152: }
1153: }
1154: }
1155: }
1156: if ($canhost) {
1157: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1158: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1159: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1160: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1163: $canhost = 0;
1164: } else {
1165: $canhost = 1;
1166: }
1167: }
1168: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1169: if (($uint_dom ne '') &&
1170: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1171: $canhost = 1;
1172: } else {
1173: $canhost = 0;
1174: }
1175: }
1176: }
1177: }
1178: return $canhost;
1179: }
1180:
1.1083 raeburn 1181: sub spare_can_host {
1182: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1183: my $canhost=1;
1.1172.2.62 raeburn 1184: my $try_server_hostname = &hostname($try_server);
1185: my $serverhomeID = &get_server_homeID($try_server_hostname);
1186: my $serverhomedom = &host_domain($serverhomeID);
1187: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1188: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1189: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1190: $canhost = 0;
1191: }
1192: }
1193: if (($canhost) && ($uint_dom)) {
1194: my @intdoms;
1195: my $internet_names = &get_internet_names($try_server);
1196: if (ref($internet_names) eq 'ARRAY') {
1197: @intdoms = @{$internet_names};
1198: }
1199: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1200: my $remoterev = &get_server_loncaparev(undef,$try_server);
1201: $canhost = &can_host_session($udom,$try_server,$remoterev,
1202: $remotesessions,
1203: $defdomdefaults{'hostedsessions'});
1204: }
1.1083 raeburn 1205: }
1206: return $canhost;
1207: }
1208:
1.1123 raeburn 1209: sub this_host_spares {
1210: my ($dom) = @_;
1.1126 raeburn 1211: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1212: my @hosts = ¤t_machine_ids();
1213: foreach my $lonhost (@hosts) {
1214: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1215: $dom_in_use = $dom;
1216: $lonhost_in_use = $lonhost;
1.1123 raeburn 1217: last;
1218: }
1219: }
1.1126 raeburn 1220: if ($dom_in_use ne '') {
1221: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1222: }
1223: if (ref($result) ne 'HASH') {
1224: $lonhost_in_use = $perlvar{'lonHostID'};
1225: $dom_in_use = &host_domain($lonhost_in_use);
1226: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1227: if (ref($result) ne 'HASH') {
1228: $result = \%spareid;
1229: }
1230: }
1231: return $result;
1232: }
1233:
1234: sub spares_for_offload {
1235: my ($dom_in_use,$lonhost_in_use) = @_;
1236: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1237: if (defined($cached)) {
1238: return $result;
1239: } else {
1.1126 raeburn 1240: my $cachetime = 60*60*24;
1241: my %domconfig =
1242: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1243: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1244: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1245: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1246: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1247: }
1248: }
1249: }
1250: }
1.1126 raeburn 1251: return;
1.1123 raeburn 1252: }
1253:
1.1129 raeburn 1254: sub get_lonbalancer_config {
1255: my ($servers) = @_;
1256: my ($currbalancer,$currtargets);
1257: if (ref($servers) eq 'HASH') {
1258: foreach my $server (keys(%{$servers})) {
1259: my %what = (
1260: spareid => 1,
1261: perlvar => 1,
1262: );
1263: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1264: if ($result eq 'ok') {
1265: if (ref($returnhash) eq 'HASH') {
1266: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1267: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1268: $currbalancer = $server;
1269: $currtargets = {};
1270: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1271: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1272: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1273: }
1274: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1275: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1276: }
1277: }
1278: last;
1279: }
1280: }
1281: }
1282: }
1283: }
1284: }
1285: return ($currbalancer,$currtargets);
1286: }
1287:
1288: sub check_loadbalancing {
1.1172.2.88 raeburn 1289: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1290: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1291: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1292: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1293: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1294: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1295: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1296: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1297: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1298: my $domneedscache;
1.1129 raeburn 1299: my $cachetime = 60*60*24;
1300:
1301: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1302: $dom_in_use = $udom;
1303: $homeintdom = 1;
1304: } else {
1305: $dom_in_use = $serverhomedom;
1306: }
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1313: } else {
1314: $domneedscache = $dom_in_use;
1.1129 raeburn 1315: }
1316: }
1317: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1318: ($is_balancer,$currtargets,$currrules) =
1319: &check_balancer_result($result,@hosts);
1.1129 raeburn 1320: if ($is_balancer) {
1321: if (ref($currrules) eq 'HASH') {
1322: if ($homeintdom) {
1323: if ($uname ne '') {
1324: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1325: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1326: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1327: $rule_in_effect = $currrules->{'_LC_author'};
1328: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1329: $rule_in_effect = $currrules->{'_LC_adv'}
1330: }
1331: }
1332: if ($rule_in_effect eq '') {
1333: my %userenv = &userenvironment($udom,$uname,'inststatus');
1334: if ($userenv{'inststatus'} ne '') {
1335: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1336: my ($othertitle,$usertypes,$types) =
1337: &Apache::loncommon::sorted_inst_types($udom);
1338: if (ref($types) eq 'ARRAY') {
1339: foreach my $type (@{$types}) {
1340: if (grep(/^\Q$type\E$/,@statuses)) {
1341: if (exists($currrules->{$type})) {
1342: $rule_in_effect = $currrules->{$type};
1343: }
1344: }
1345: }
1346: }
1347: } else {
1348: if (exists($currrules->{'default'})) {
1349: $rule_in_effect = $currrules->{'default'};
1350: }
1351: }
1352: }
1353: } else {
1354: if (exists($currrules->{'default'})) {
1355: $rule_in_effect = $currrules->{'default'};
1356: }
1357: }
1358: } else {
1359: if ($currrules->{'_LC_external'} ne '') {
1360: $rule_in_effect = $currrules->{'_LC_external'};
1361: }
1362: }
1363: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1364: $uname,$udom);
1365: }
1366: }
1367: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1368: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1369: unless (defined($cached)) {
1370: my %domconfig =
1371: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1372: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1373: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1374: } else {
1375: $domneedscache = $serverhomedom;
1.1129 raeburn 1376: }
1377: }
1378: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1379: ($is_balancer,$currtargets,$currrules) =
1380: &check_balancer_result($result,@hosts);
1381: if ($is_balancer) {
1.1129 raeburn 1382: if (ref($currrules) eq 'HASH') {
1383: if ($currrules->{'_LC_internetdom'} ne '') {
1384: $rule_in_effect = $currrules->{'_LC_internetdom'};
1385: }
1386: }
1387: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1388: $uname,$udom);
1389: }
1390: } else {
1391: if ($perlvar{'lonBalancer'} eq 'yes') {
1392: $is_balancer = 1;
1393: $offloadto = &this_host_spares($dom_in_use);
1394: }
1.1172.2.75 raeburn 1395: unless (defined($cached)) {
1396: $domneedscache = $serverhomedom;
1397: }
1.1129 raeburn 1398: }
1399: } else {
1400: if ($perlvar{'lonBalancer'} eq 'yes') {
1401: $is_balancer = 1;
1402: $offloadto = &this_host_spares($dom_in_use);
1403: }
1.1172.2.75 raeburn 1404: unless (defined($cached)) {
1405: $domneedscache = $serverhomedom;
1406: }
1407: }
1408: if ($domneedscache) {
1409: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1410: }
1.1172.2.5 raeburn 1411: if ($is_balancer) {
1412: my $lowest_load = 30000;
1413: if (ref($offloadto) eq 'HASH') {
1414: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1415: foreach my $try_server (@{$offloadto->{'primary'}}) {
1416: ($otherserver,$lowest_load) =
1417: &compare_server_load($try_server,$otherserver,$lowest_load);
1418: }
1.1129 raeburn 1419: }
1.1172.2.5 raeburn 1420: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1421:
1.1172.2.5 raeburn 1422: if (!$found_server) {
1423: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1424: foreach my $try_server (@{$offloadto->{'default'}}) {
1425: ($otherserver,$lowest_load) =
1426: &compare_server_load($try_server,$otherserver,$lowest_load);
1427: }
1428: }
1429: }
1430: } elsif (ref($offloadto) eq 'ARRAY') {
1431: if (@{$offloadto} == 1) {
1432: $otherserver = $offloadto->[0];
1433: } elsif (@{$offloadto} > 1) {
1434: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1435: ($otherserver,$lowest_load) =
1436: &compare_server_load($try_server,$otherserver,$lowest_load);
1437: }
1438: }
1439: }
1.1172.2.88 raeburn 1440: unless ($caller eq 'login') {
1441: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1442: $is_balancer = 0;
1443: if ($uname ne '' && $udom ne '') {
1444: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5 raeburn 1445:
1.1172.2.88 raeburn 1446: &appenv({'user.loadbalexempt' => $lonhost,
1447: 'user.loadbalcheck.time' => time});
1448: }
1.1172.2.5 raeburn 1449: }
1.1129 raeburn 1450: }
1451: }
1452: }
1453: return ($is_balancer,$otherserver);
1454: }
1455:
1.1172.2.12 raeburn 1456: sub check_balancer_result {
1457: my ($result,@hosts) = @_;
1458: my ($is_balancer,$currtargets,$currrules);
1459: if (ref($result) eq 'HASH') {
1460: if ($result->{'lonhost'} ne '') {
1461: my $currbalancer = $result->{'lonhost'};
1462: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1463: $is_balancer = 1;
1464: $currtargets = $result->{'targets'};
1465: $currrules = $result->{'rules'};
1466: }
1467: } else {
1468: foreach my $key (keys(%{$result})) {
1469: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1470: (ref($result->{$key}) eq 'HASH')) {
1471: $is_balancer = 1;
1472: $currrules = $result->{$key}{'rules'};
1473: $currtargets = $result->{$key}{'targets'};
1474: last;
1475: }
1476: }
1477: }
1478: }
1479: return ($is_balancer,$currtargets,$currrules);
1480: }
1481:
1.1129 raeburn 1482: sub get_loadbalancer_targets {
1483: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1484: my $offloadto;
1.1172.2.4 raeburn 1485: if ($rule_in_effect eq 'none') {
1486: return [$perlvar{'lonHostID'}];
1487: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1488: $offloadto = $currtargets;
1489: } else {
1490: if ($rule_in_effect eq 'homeserver') {
1491: my $homeserver = &homeserver($uname,$udom);
1492: if ($homeserver ne 'no_host') {
1493: $offloadto = [$homeserver];
1494: }
1495: } elsif ($rule_in_effect eq 'externalbalancer') {
1496: my %domconfig =
1497: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1498: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1499: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1500: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1501: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1502: }
1503: }
1504: } else {
1.1172.2.7 raeburn 1505: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1506: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1507: if (&hostname($remotebalancer) ne '') {
1508: $offloadto = [$remotebalancer];
1509: }
1510: }
1511: } elsif (&hostname($rule_in_effect) ne '') {
1512: $offloadto = [$rule_in_effect];
1513: }
1514: }
1515: return $offloadto;
1516: }
1517:
1.1127 raeburn 1518: sub internet_dom_servers {
1519: my ($dom) = @_;
1520: my (%uniqservers,%servers);
1521: my $primaryserver = &hostname(&domain($dom,'primary'));
1522: my @machinedoms = &machine_domains($primaryserver);
1523: foreach my $mdom (@machinedoms) {
1524: my %currservers = %servers;
1525: my %server = &get_servers($mdom);
1526: %servers = (%currservers,%server);
1527: }
1528: my %by_hostname;
1529: foreach my $id (keys(%servers)) {
1530: push(@{$by_hostname{$servers{$id}}},$id);
1531: }
1532: foreach my $hostname (sort(keys(%by_hostname))) {
1533: if (@{$by_hostname{$hostname}} > 1) {
1534: my $match = 0;
1535: foreach my $id (@{$by_hostname{$hostname}}) {
1536: if (&host_domain($id) eq $dom) {
1537: $uniqservers{$id} = $hostname;
1538: $match = 1;
1539: }
1540: }
1541: unless ($match) {
1542: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1543: }
1544: } else {
1545: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1546: }
1547: }
1548: return %uniqservers;
1549: }
1550:
1.1 albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1552:
1.599 albertel 1553: my %homecache;
1.1 albertel 1554: sub homeserver {
1.230 stredwic 1555: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1556: my $index="$uname:$udom";
1.426 albertel 1557:
1.599 albertel 1558: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1559:
1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1562: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1563: exists($badServerCache{$tryserver}));
1.841 albertel 1564:
1565: my $answer=reply("home:$udom:$uname",$tryserver);
1566: if ($answer eq 'found') {
1567: delete($badServerCache{$tryserver});
1568: return $homecache{$index}=$tryserver;
1569: } elsif ($answer eq 'no_host') {
1570: $badServerCache{$tryserver}=1;
1571: }
1.1 albertel 1572: }
1573: return 'no_host';
1.70 www 1574: }
1575:
1576: # ------------------------------------- Find the usernames behind a list of IDs
1577:
1578: sub idget {
1579: my ($udom,@ids)=@_;
1580: my %returnhash=();
1581:
1.841 albertel 1582: my %servers = &get_servers($udom,'library');
1583: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1584: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1585: $idlist=~tr/A-Z/a-z/;
1586: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1587: my @answer=();
1588: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1589: @answer=split(/\&/,$reply);
1590: } ;
1591: my $i;
1592: for ($i=0;$i<=$#ids;$i++) {
1593: if ($answer[$i]) {
1.1172.2.73 raeburn 1594: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1595: }
1596: }
1597: }
1.70 www 1598: return %returnhash;
1599: }
1600:
1601: # ------------------------------------- Find the IDs behind a list of usernames
1602:
1603: sub idrget {
1604: my ($udom,@unames)=@_;
1605: my %returnhash=();
1.800 albertel 1606: foreach my $uname (@unames) {
1607: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1608: }
1.70 www 1609: return %returnhash;
1610: }
1611:
1612: # ------------------------------- Store away a list of names and associated IDs
1613:
1614: sub idput {
1615: my ($udom,%ids)=@_;
1616: my %servers=();
1.800 albertel 1617: foreach my $uname (keys(%ids)) {
1618: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1619: my $uhom=&homeserver($uname,$udom);
1.70 www 1620: if ($uhom ne 'no_host') {
1.800 albertel 1621: my $id=&escape($ids{$uname});
1.70 www 1622: $id=~tr/A-Z/a-z/;
1.800 albertel 1623: my $esc_unam=&escape($uname);
1.70 www 1624: if ($servers{$uhom}) {
1.800 albertel 1625: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1626: } else {
1.800 albertel 1627: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1628: }
1629: }
1.191 harris41 1630: }
1.800 albertel 1631: foreach my $server (keys(%servers)) {
1632: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1633: }
1.344 www 1634: }
1635:
1.1172.2.30 raeburn 1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
1637:
1638: sub iddel {
1639: my ($udom,$idshashref,$uhome)=@_;
1640: my %result=();
1641: unless (ref($idshashref) eq 'HASH') {
1642: return %result;
1643: }
1644: my %servers=();
1645: while (my ($id,$uname) = each(%{$idshashref})) {
1646: my $uhom;
1647: if ($uhome) {
1648: $uhom = $uhome;
1649: } else {
1650: $uhom=&homeserver($uname,$udom);
1651: }
1652: if ($uhom ne 'no_host') {
1653: if ($servers{$uhom}) {
1654: $servers{$uhom}.='&'.&escape($id);
1655: } else {
1656: $servers{$uhom}=&escape($id);
1657: }
1658: }
1659: }
1660: foreach my $server (keys(%servers)) {
1661: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1662: }
1663: return %result;
1664: }
1665:
1.1023 raeburn 1666: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1667: sub dump_dom {
1.1165 droeschl 1668: my ($namespace, $udom, $regexp) = @_;
1669:
1670: $udom ||= $env{'user.domain'};
1671:
1672: return () unless $udom;
1673:
1674: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1675: }
1676:
1.1023 raeburn 1677: # ------------------------------------------ get items from domain db files
1.806 raeburn 1678:
1679: sub get_dom {
1.860 raeburn 1680: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1681: return if ($udom eq 'public');
1.806 raeburn 1682: my $items='';
1683: foreach my $item (@$storearr) {
1684: $items.=&escape($item).'&';
1685: }
1686: $items=~s/\&$//;
1.860 raeburn 1687: if (!$udom) {
1688: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1689: return if ($udom eq 'public');
1.860 raeburn 1690: if (defined(&domain($udom,'primary'))) {
1691: $uhome=&domain($udom,'primary');
1692: } else {
1.874 albertel 1693: undef($uhome);
1.860 raeburn 1694: }
1695: } else {
1696: if (!$uhome) {
1697: if (defined(&domain($udom,'primary'))) {
1698: $uhome=&domain($udom,'primary');
1699: }
1700: }
1701: }
1702: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.93.4 2(raebur 1703:7): my $rep;
1704:7): if ($namespace =~ /^enc/) {
1705:7): $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1706:7): } else {
1707:7): $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1708:7): }
1.866 raeburn 1709: my %returnhash;
1.875 albertel 1710: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1711: return %returnhash;
1712: }
1.806 raeburn 1713: my @pairs=split(/\&/,$rep);
1714: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1715: return @pairs;
1716: }
1717: my $i=0;
1718: foreach my $item (@$storearr) {
1719: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1720: $i++;
1721: }
1722: return %returnhash;
1723: } else {
1.880 banghart 1724: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1725: }
1726: }
1727:
1728: # -------------------------------------------- put items in domain db files
1729:
1730: sub put_dom {
1.860 raeburn 1731: my ($namespace,$storehash,$udom,$uhome)=@_;
1732: if (!$udom) {
1733: $udom=$env{'user.domain'};
1734: if (defined(&domain($udom,'primary'))) {
1735: $uhome=&domain($udom,'primary');
1736: } else {
1.874 albertel 1737: undef($uhome);
1.860 raeburn 1738: }
1739: } else {
1740: if (!$uhome) {
1741: if (defined(&domain($udom,'primary'))) {
1742: $uhome=&domain($udom,'primary');
1743: }
1744: }
1745: }
1746: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1747: my $items='';
1748: foreach my $item (keys(%$storehash)) {
1749: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1750: }
1751: $items=~s/\&$//;
1.1172.2.93.4 2(raebur 1752:7): if ($namespace =~ /^enc/) {
1753:7): return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
1754:7): } else {
1755:7): return &reply("putdom:$udom:$namespace:$items",$uhome);
1756:7): }
1.806 raeburn 1757: } else {
1.860 raeburn 1758: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1759: }
1760: }
1761:
1.1023 raeburn 1762: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1763: sub newput_dom {
1.1023 raeburn 1764: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1765: my $result;
1766: if (!$udom) {
1767: $udom=$env{'user.domain'};
1768: }
1.1023 raeburn 1769: if ($udom) {
1770: my $uname = &get_domainconfiguser($udom);
1771: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1772: }
1773: return $result;
1774: }
1775:
1.1023 raeburn 1776: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1777: sub del_dom {
1.1023 raeburn 1778: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1779: if (ref($storearr) eq 'ARRAY') {
1780: if (!$udom) {
1781: $udom=$env{'user.domain'};
1782: }
1.1023 raeburn 1783: if ($udom) {
1784: my $uname = &get_domainconfiguser($udom);
1785: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1786: }
1787: }
1788: }
1789:
1.1023 raeburn 1790: # ----------------------------------construct domainconfig user for a domain
1791: sub get_domainconfiguser {
1792: my ($udom) = @_;
1793: return $udom.'-domainconfig';
1794: }
1795:
1.837 raeburn 1796: sub retrieve_inst_usertypes {
1797: my ($udom) = @_;
1798: my (%returnhash,@order);
1.989 raeburn 1799: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1800: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1801: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1802: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1803: } else {
1804: if (defined(&domain($udom,'primary'))) {
1805: my $uhome=&domain($udom,'primary');
1806: my $rep=&reply("inst_usertypes:$udom",$uhome);
1807: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1808: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1809: return (\%returnhash,\@order);
1810: }
1811: my ($hashitems,$orderitems) = split(/:/,$rep);
1812: my @pairs=split(/\&/,$hashitems);
1813: foreach my $item (@pairs) {
1814: my ($key,$value)=split(/=/,$item,2);
1815: $key = &unescape($key);
1816: next if ($key =~ /^error: 2 /);
1817: $returnhash{$key}=&thaw_unescape($value);
1818: }
1819: my @esc_order = split(/\&/,$orderitems);
1820: foreach my $item (@esc_order) {
1821: push(@order,&unescape($item));
1822: }
1823: } else {
1.1172.2.44 raeburn 1824: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1825: }
1.1172.2.44 raeburn 1826: return (\%returnhash,\@order);
1.837 raeburn 1827: }
1828: }
1829:
1.868 raeburn 1830: sub is_domainimage {
1831: my ($url) = @_;
1.1172.2.74 raeburn 1832: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1833: if (&domain($1) ne '') {
1834: return '1';
1835: }
1836: }
1837: return;
1838: }
1839:
1.899 raeburn 1840: sub inst_directory_query {
1841: my ($srch) = @_;
1842: my $udom = $srch->{'srchdomain'};
1843: my %results;
1844: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1845: my $outcome;
1.899 raeburn 1846: if ($homeserver ne '') {
1.1172.2.93.4 4(raebur 1847:7): unless ($homeserver eq $perlvar{'lonHostID'}) {
1848:7): if ($srch->{'srchby'} eq 'email') {
1849:7): my $lcrev = &get_server_loncaparev(undef,$homeserver);
1850:7): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
1851:7): if (($major eq '' && $minor eq '') || ($major < 2) ||
1852:7): (($major == 2) && ($minor < 11)) ||
1853:7): (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
1854:7): return;
1855:7): }
1856:7): }
1857:7): }
1.904 albertel 1858: my $queryid=&reply("querysend:instdirsearch:".
1859: &escape($srch->{'srchby'}).':'.
1860: &escape($srch->{'srchterm'}).':'.
1861: &escape($srch->{'srchtype'}),$homeserver);
1862: my $host=&hostname($homeserver);
1863: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4 1(raebur 1864:7): &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1865: return;
1866: }
1867: my $response = &get_query_reply($queryid);
1868: my $maxtries = 5;
1869: my $tries = 1;
1870: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1871: $response = &get_query_reply($queryid);
1872: $tries ++;
1873: }
1874:
1875: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1876: if ($response eq 'unavailable') {
1877: $outcome = $response;
1878: } else {
1879: $outcome = 'ok';
1880: my @matches = split(/\n/,$response);
1881: foreach my $match (@matches) {
1882: my ($key,$value) = split(/=/,$match);
1883: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1884: }
1.899 raeburn 1885: }
1886: }
1887: }
1.909 raeburn 1888: return ($outcome,%results);
1.899 raeburn 1889: }
1890:
1891: sub usersearch {
1892: my ($srch) = @_;
1893: my $dom = $srch->{'srchdomain'};
1894: my %results;
1895: my %libserv = &all_library();
1896: my $query = 'usersearch';
1897: foreach my $tryserver (keys(%libserv)) {
1898: if (&host_domain($tryserver) eq $dom) {
1.1172.2.93.4 4(raebur 1899:7): unless ($tryserver eq $perlvar{'lonHostID'}) {
1900:7): if ($srch->{'srchby'} eq 'email') {
1901:7): my $lcrev = &get_server_loncaparev(undef,$tryserver);
1902:7): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
1903:7): next if (($major eq '' && $minor eq '') || ($major < 2) ||
1904:7): (($major == 2) && ($minor < 11)) ||
6(raebur 1905:7): (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/)));
4(raebur 1906:7): }
1907:7): }
1.899 raeburn 1908: my $host=&hostname($tryserver);
1909: my $queryid=
1.911 raeburn 1910: &reply("querysend:".&escape($query).':'.
1911: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1912: &escape($srch->{'srchtype'}).':'.
1913: &escape($srch->{'srchterm'}),$tryserver);
1914: if ($queryid !~/^\Q$host\E\_/) {
1915: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1916: next;
1.899 raeburn 1917: }
1918: my $reply = &get_query_reply($queryid);
1919: my $maxtries = 1;
1920: my $tries = 1;
1921: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1922: $reply = &get_query_reply($queryid);
1923: $tries ++;
1924: }
1925: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1926: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1927: } else {
1.911 raeburn 1928: my @matches;
1929: if ($reply =~ /\n/) {
1930: @matches = split(/\n/,$reply);
1931: } else {
1932: @matches = split(/\&/,$reply);
1933: }
1.899 raeburn 1934: foreach my $match (@matches) {
1935: my ($uname,$udom,%userhash);
1.911 raeburn 1936: foreach my $entry (split(/:/,$match)) {
1937: my ($key,$value) =
1938: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1939: $userhash{$key} = $value;
1940: if ($key eq 'username') {
1941: $uname = $value;
1942: } elsif ($key eq 'domain') {
1943: $udom = $value;
1.911 raeburn 1944: }
1.899 raeburn 1945: }
1946: $results{$uname.':'.$udom} = \%userhash;
1947: }
1948: }
1949: }
1950: }
1951: return %results;
1952: }
1953:
1.912 raeburn 1954: sub get_instuser {
1955: my ($udom,$uname,$id) = @_;
1956: my $homeserver = &domain($udom,'primary');
1957: my ($outcome,%results);
1958: if ($homeserver ne '') {
1959: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1960: &escape($id).':'.&escape($udom),$homeserver);
1961: my $host=&hostname($homeserver);
1962: if ($queryid !~/^\Q$host\E\_/) {
1963: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1964: return;
1965: }
1966: my $response = &get_query_reply($queryid);
1967: my $maxtries = 5;
1968: my $tries = 1;
1969: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1970: $response = &get_query_reply($queryid);
1971: $tries ++;
1972: }
1973: if (!&error($response) && $response ne 'refused') {
1974: if ($response eq 'unavailable') {
1975: $outcome = $response;
1976: } else {
1977: $outcome = 'ok';
1978: my @matches = split(/\n/,$response);
1979: foreach my $match (@matches) {
1980: my ($key,$value) = split(/=/,$match);
1981: $results{&unescape($key)} = &thaw_unescape($value);
1982: }
1983: }
1984: }
1985: }
1986: my %userinfo;
1987: if (ref($results{$uname}) eq 'HASH') {
1988: %userinfo = %{$results{$uname}};
1989: }
1990: return ($outcome,%userinfo);
1991: }
1992:
1.1172.2.69 raeburn 1993: sub get_multiple_instusers {
1994: my ($udom,$users,$caller) = @_;
1995: my ($outcome,$results);
1996: if (ref($users) eq 'HASH') {
1997: my $count = keys(%{$users});
1998: my $requested = &freeze_escape($users);
1999: my $homeserver = &domain($udom,'primary');
2000: if ($homeserver ne '') {
2001: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2002: my $host=&hostname($homeserver);
2003: if ($queryid !~/^\Q$host\E\_/) {
2004: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2005: ' for host: '.$homeserver.'in domain '.$udom);
2006: return ($outcome,$results);
2007: }
2008: my $response = &get_query_reply($queryid);
2009: my $maxtries = 5;
2010: if ($count > 100) {
2011: $maxtries = 1+int($count/20);
2012: }
2013: my $tries = 1;
2014: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2015: $response = &get_query_reply($queryid);
2016: $tries ++;
2017: }
2018: if ($response eq '') {
2019: $results = {};
2020: foreach my $key (keys(%{$users})) {
2021: my ($uname,$id);
2022: if ($caller eq 'id') {
2023: $id = $key;
2024: } else {
2025: $uname = $key;
2026: }
2027: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2028: $outcome = $resp;
2029: if ($resp eq 'ok') {
2030: %{$results} = (%{$results}, %info);
2031: } else {
2032: last;
2033: }
2034: }
2035: } elsif(!&error($response) && ($response ne 'refused')) {
2036: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2037: $outcome = $response;
2038: } else {
2039: ($outcome,my $userdata) = split(/=/,$response,2);
2040: if ($outcome eq 'ok') {
2041: $results = &thaw_unescape($userdata);
2042: }
2043: }
2044: }
2045: }
2046: }
2047: return ($outcome,$results);
2048: }
2049:
1.912 raeburn 2050: sub inst_rulecheck {
1.923 raeburn 2051: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2052: my %returnhash;
2053: if ($udom ne '') {
2054: if (ref($rules) eq 'ARRAY') {
2055: @{$rules} = map {&escape($_);} (@{$rules});
2056: my $rulestr = join(':',@{$rules});
2057: my $homeserver=&domain($udom,'primary');
2058: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2059: my $response;
2060: if ($item eq 'username') {
2061: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2062: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2063: $homeserver));
1.923 raeburn 2064: } elsif ($item eq 'id') {
2065: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2066: ':'.&escape($id).':'.$rulestr,
2067: $homeserver));
1.945 raeburn 2068: } elsif ($item eq 'selfcreate') {
2069: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2070: &escape($udom).':'.&escape($uname).
2071: ':'.$rulestr,$homeserver));
1.923 raeburn 2072: }
1.912 raeburn 2073: if ($response ne 'refused') {
2074: my @pairs=split(/\&/,$response);
2075: foreach my $item (@pairs) {
2076: my ($key,$value)=split(/=/,$item,2);
2077: $key = &unescape($key);
2078: next if ($key =~ /^error: 2 /);
2079: $returnhash{$key}=&thaw_unescape($value);
2080: }
2081: }
2082: }
2083: }
2084: }
2085: return %returnhash;
2086: }
2087:
2088: sub inst_userrules {
1.923 raeburn 2089: my ($udom,$check) = @_;
1.912 raeburn 2090: my (%ruleshash,@ruleorder);
2091: if ($udom ne '') {
2092: my $homeserver=&domain($udom,'primary');
2093: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2094: my $response;
2095: if ($check eq 'id') {
2096: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2097: $homeserver);
1.943 raeburn 2098: } elsif ($check eq 'email') {
2099: $response=&reply('instemailrules:'.&escape($udom),
2100: $homeserver);
1.923 raeburn 2101: } else {
2102: $response=&reply('instuserrules:'.&escape($udom),
2103: $homeserver);
2104: }
1.912 raeburn 2105: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2106: ($response ne 'unknown_cmd') &&
1.912 raeburn 2107: ($response ne 'no_such_host')) {
2108: my ($hashitems,$orderitems) = split(/:/,$response);
2109: my @pairs=split(/\&/,$hashitems);
2110: foreach my $item (@pairs) {
2111: my ($key,$value)=split(/=/,$item,2);
2112: $key = &unescape($key);
2113: next if ($key =~ /^error: 2 /);
2114: $ruleshash{$key}=&thaw_unescape($value);
2115: }
2116: my @esc_order = split(/\&/,$orderitems);
2117: foreach my $item (@esc_order) {
2118: push(@ruleorder,&unescape($item));
2119: }
2120: }
2121: }
2122: }
2123: return (\%ruleshash,\@ruleorder);
2124: }
2125:
1.976 raeburn 2126: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2127:
2128: sub get_domain_defaults {
1.1172.2.35 raeburn 2129: my ($domain,$ignore_cache) = @_;
2130: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2131: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2132: unless ($ignore_cache) {
2133: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2134: if (defined($cached)) {
2135: if (ref($result) eq 'HASH') {
2136: return %{$result};
2137: }
1.943 raeburn 2138: }
2139: }
2140: my %domdefaults;
2141: my %domconfig =
1.989 raeburn 2142: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2143: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2144: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2145: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2146: 'coursecategories','autoenroll',
2147: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2148: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2149: if (ref($domconfig{'defaults'}) eq 'HASH') {
2150: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2151: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2152: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2153: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2154: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2155: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2156: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2157: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2158: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2159: } else {
2160: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2161: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2162: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2163: }
1.976 raeburn 2164: if (ref($domconfig{'quotas'}) eq 'HASH') {
2165: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2166: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2167: } else {
2168: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2169: }
1.1172.2.6 raeburn 2170: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2171: foreach my $item (@usertools) {
2172: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2173: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2174: }
2175: }
1.1172.2.29 raeburn 2176: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2177: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2178: }
1.976 raeburn 2179: }
1.985 raeburn 2180: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2181: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2182: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2183: }
2184: }
1.1172.2.9 raeburn 2185: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2186: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2187: }
1.989 raeburn 2188: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2189: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2190: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2191: }
2192: }
1.1047 raeburn 2193: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2194: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2195: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2196: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2197: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2198: }
1.1172.2.41 raeburn 2199: foreach my $type (@coursetypes) {
2200: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2201: unless ($type eq 'community') {
2202: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2203: }
2204: }
2205: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2206: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2207: }
1.1172.2.60 raeburn 2208: if ($domdefaults{'postsubmit'} eq 'on') {
2209: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2210: $domdefaults{$type.'postsubtimeout'} =
2211: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2212: }
2213: }
1.1172.2.30 raeburn 2214: }
1.1172.2.67 raeburn 2215: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2216: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2217: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2218: if (@clonecodes) {
2219: $domdefaults{'canclone'} = join('+',@clonecodes);
2220: }
2221: }
2222: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2223: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2224: }
1.1047 raeburn 2225: }
1.1073 raeburn 2226: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2227: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2228: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2229: }
2230: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2231: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2232: }
1.1172.2.62 raeburn 2233: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2234: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2235: }
1.1073 raeburn 2236: }
1.1172.2.41 raeburn 2237: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2238: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2239: my @settings = ('types','registered','enroll_dates','access_dates','section',
2240: 'approval','limit');
2241: foreach my $type (@coursetypes) {
2242: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2243: my @mgrdc = ();
2244: foreach my $item (@settings) {
2245: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2246: push(@mgrdc,$item);
2247: }
2248: }
2249: if (@mgrdc) {
2250: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2251: }
2252: }
2253: }
2254: }
2255: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2256: foreach my $type (@coursetypes) {
2257: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2258: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2259: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2260: }
2261: }
2262: }
2263: }
2264: }
1.1172.2.46 raeburn 2265: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2266: $domdefaults{'catauth'} = 'std';
2267: $domdefaults{'catunauth'} = 'std';
2268: if ($domconfig{'coursecategories'}{'auth'}) {
2269: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2270: }
2271: if ($domconfig{'coursecategories'}{'unauth'}) {
2272: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2273: }
2274: }
1.1172.2.76 raeburn 2275: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2276: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2277: }
1.1172.2.89 raeburn 2278: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2279: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2280: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2281: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2282: }
2283: }
1.1172.2.23 raeburn 2284: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2285: return %domdefaults;
2286: }
2287:
1.1172.2.93.4 2(raebur 2288:7): sub course_portal_url {
2289:7): my ($cnum,$cdom) = @_;
2290:7): my $chome = &homeserver($cnum,$cdom);
2291:7): my $hostname = &hostname($chome);
2292:7): my $protocol = $protocol{$chome};
2293:7): $protocol = 'http' if ($protocol ne 'https');
2294:7): my %domdefaults = &get_domain_defaults($cdom);
2295:7): my $firsturl;
2296:7): if ($domdefaults{'portal_def'}) {
2297:7): $firsturl = $domdefaults{'portal_def'};
2298:7): } else {
2299:7): $firsturl = $protocol.'://'.$hostname;
2300:7): }
2301:7): return $firsturl;
2302:7): }
2303:7):
1.344 www 2304: # --------------------------------------------------- Assign a key to a student
2305:
2306: sub assign_access_key {
1.364 www 2307: #
2308: # a valid key looks like uname:udom#comments
2309: # comments are being appended
2310: #
1.498 www 2311: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2312: $kdom=
1.620 albertel 2313: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2314: $knum=
1.620 albertel 2315: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2316: $cdom=
1.620 albertel 2317: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2318: $cnum=
1.620 albertel 2319: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2320: $udom=$env{'user.name'} unless (defined($udom));
2321: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2322: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2323: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2324: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2325: # assigned to this person
2326: # - this should not happen,
1.345 www 2327: # unless something went wrong
2328: # the first time around
2329: # ready to assign
1.364 www 2330: $logentry=$1.'; '.$logentry;
1.496 www 2331: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2332: $kdom,$knum) eq 'ok') {
1.345 www 2333: # key now belongs to user
1.346 www 2334: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2335: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2336: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2337: return 'ok';
2338: } else {
2339: return
2340: 'error: Count not permanently assign key, will need to be re-entered later.';
2341: }
2342: } else {
2343: return 'error: Could not assign key, try again later.';
2344: }
1.364 www 2345: } elsif (!$existing{$ckey}) {
1.345 www 2346: # the key does not exist
2347: return 'error: The key does not exist';
2348: } else {
2349: # the key is somebody else's
2350: return 'error: The key is already in use';
2351: }
1.344 www 2352: }
2353:
1.364 www 2354: # ------------------------------------------ put an additional comment on a key
2355:
2356: sub comment_access_key {
2357: #
2358: # a valid key looks like uname:udom#comments
2359: # comments are being appended
2360: #
2361: my ($ckey,$cdom,$cnum,$logentry)=@_;
2362: $cdom=
1.620 albertel 2363: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2364: $cnum=
1.620 albertel 2365: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2366: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2367: if ($existing{$ckey}) {
2368: $existing{$ckey}.='; '.$logentry;
2369: # ready to assign
1.367 www 2370: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2371: $cdom,$cnum) eq 'ok') {
2372: return 'ok';
2373: } else {
2374: return 'error: Count not store comment.';
2375: }
2376: } else {
2377: # the key does not exist
2378: return 'error: The key does not exist';
2379: }
2380: }
2381:
1.344 www 2382: # ------------------------------------------------------ Generate a set of keys
2383:
2384: sub generate_access_keys {
1.364 www 2385: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2386: $cdom=
1.620 albertel 2387: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2388: $cnum=
1.620 albertel 2389: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2390: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2391: unless (($cdom) && ($cnum)) { return 0; }
2392: if ($number>10000) { return 0; }
2393: sleep(2); # make sure don't get same seed twice
2394: srand(time()^($$+($$<<15))); # from "Programming Perl"
2395: my $total=0;
2396: for (my $i=1;$i<=$number;$i++) {
2397: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2398: sprintf("%lx",int(100000*rand)).'-'.
2399: sprintf("%lx",int(100000*rand));
2400: $newkey=~s/1/g/g; # folks mix up 1 and l
2401: $newkey=~s/0/h/g; # and also 0 and O
2402: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2403: if ($existing{$newkey}) {
2404: $i--;
2405: } else {
1.364 www 2406: if (&put('accesskeys',
2407: { $newkey => '# generated '.localtime().
1.620 albertel 2408: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2409: '; '.$logentry },
2410: $cdom,$cnum) eq 'ok') {
1.344 www 2411: $total++;
2412: }
2413: }
2414: }
1.620 albertel 2415: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2416: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2417: return $total;
2418: }
2419:
2420: # ------------------------------------------------------- Validate an accesskey
2421:
2422: sub validate_access_key {
2423: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2424: $cdom=
1.620 albertel 2425: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2426: $cnum=
1.620 albertel 2427: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2428: $udom=$env{'user.domain'} unless (defined($udom));
2429: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2430: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2431: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2432: }
2433:
2434: # ------------------------------------- Find the section of student in a course
1.652 albertel 2435: sub devalidate_getsection_cache {
2436: my ($udom,$unam,$courseid)=@_;
2437: my $hashid="$udom:$unam:$courseid";
2438: &devalidate_cache_new('getsection',$hashid);
2439: }
1.298 matthew 2440:
1.815 albertel 2441: sub courseid_to_courseurl {
2442: my ($courseid) = @_;
2443: #already url style courseid
2444: return $courseid if ($courseid =~ m{^/});
2445:
2446: if (exists($env{'course.'.$courseid.'.num'})) {
2447: my $cnum = $env{'course.'.$courseid.'.num'};
2448: my $cdom = $env{'course.'.$courseid.'.domain'};
2449: return "/$cdom/$cnum";
2450: }
2451:
2452: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2453: if (exists($courseinfo{'num'})) {
2454: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2455: }
2456:
2457: return undef;
2458: }
2459:
1.298 matthew 2460: sub getsection {
2461: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2462: my $cachetime=1800;
1.551 albertel 2463:
2464: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2465: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2466: if (defined($cached)) { return $result; }
2467:
1.298 matthew 2468: my %Pending;
2469: my %Expired;
2470: #
2471: # Each role can either have not started yet (pending), be active,
2472: # or have expired.
2473: #
2474: # If there is an active role, we are done.
2475: #
2476: # If there is more than one role which has not started yet,
2477: # choose the one which will start sooner
2478: # If there is one role which has not started yet, return it.
2479: #
2480: # If there is more than one expired role, choose the one which ended last.
2481: # If there is a role which has expired, return it.
2482: #
1.815 albertel 2483: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2484: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2485: foreach my $key (keys(%roleshash)) {
1.479 albertel 2486: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2487: my $section=$1;
2488: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2489: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2490: my $now=time;
1.548 albertel 2491: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2492: $Expired{$end}=$section;
2493: next;
2494: }
1.548 albertel 2495: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2496: $Pending{$start}=$section;
2497: next;
2498: }
1.599 albertel 2499: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2500: }
2501: #
2502: # Presumedly there will be few matching roles from the above
2503: # loop and the sorting time will be negligible.
2504: if (scalar(keys(%Pending))) {
2505: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2506: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2507: }
2508: if (scalar(keys(%Expired))) {
2509: my @sorted = sort {$a <=> $b} keys(%Expired);
2510: my $time = pop(@sorted);
1.599 albertel 2511: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2512: }
1.599 albertel 2513: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2514: }
1.70 www 2515:
1.599 albertel 2516: sub save_cache {
2517: &purge_remembered();
1.722 albertel 2518: #&Apache::loncommon::validate_page();
1.620 albertel 2519: undef(%env);
1.780 albertel 2520: undef($env_loaded);
1.599 albertel 2521: }
1.452 albertel 2522:
1.599 albertel 2523: my $to_remember=-1;
2524: my %remembered;
2525: my %accessed;
2526: my $kicks=0;
2527: my $hits=0;
1.849 albertel 2528: sub make_key {
2529: my ($name,$id) = @_;
1.872 albertel 2530: if (length($id) > 65
2531: && length(&escape($id)) > 200) {
2532: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2533: }
1.849 albertel 2534: return &escape($name.':'.$id);
2535: }
2536:
1.599 albertel 2537: sub devalidate_cache_new {
2538: my ($name,$id,$debug) = @_;
2539: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2540: my $remembered_id=$name.':'.$id;
1.849 albertel 2541: $id=&make_key($name,$id);
1.599 albertel 2542: $memcache->delete($id);
1.1172.2.81 raeburn 2543: delete($remembered{$remembered_id});
2544: delete($accessed{$remembered_id});
1.599 albertel 2545: }
2546:
2547: sub is_cached_new {
2548: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2549: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2550: # keys in %remembered hash, which persists for
2551: # duration of request (no restriction on key length).
2552: if (exists($remembered{$remembered_id})) {
2553: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2554: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2555: $hits++;
1.1172.2.81 raeburn 2556: return ($remembered{$remembered_id},1);
1.599 albertel 2557: }
1.1172.2.81 raeburn 2558: $id=&make_key($name,$id);
1.599 albertel 2559: my $value = $memcache->get($id);
2560: if (!(defined($value))) {
2561: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2562: return (undef,undef);
1.416 albertel 2563: }
1.599 albertel 2564: if ($value eq '__undef__') {
2565: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2566: $value=undef;
2567: }
1.1172.2.81 raeburn 2568: &make_room($remembered_id,$value,$debug);
1.599 albertel 2569: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2570: return ($value,1);
2571: }
2572:
2573: sub do_cache_new {
2574: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2575: my $remembered_id=$name.':'.$id;
1.849 albertel 2576: $id=&make_key($name,$id);
1.599 albertel 2577: my $setvalue=$value;
2578: if (!defined($setvalue)) {
2579: $setvalue='__undef__';
2580: }
1.623 albertel 2581: if (!defined($time) ) {
2582: $time=600;
2583: }
1.599 albertel 2584: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2585: my $result = $memcache->set($id,$setvalue,$time);
2586: if (! $result) {
1.872 albertel 2587: &logthis("caching of id -> $id failed");
1.910 albertel 2588: $memcache->disconnect_all();
1.872 albertel 2589: }
1.600 albertel 2590: # need to make a copy of $value
1.1172.2.81 raeburn 2591: &make_room($remembered_id,$value,$debug);
1.599 albertel 2592: return $value;
2593: }
2594:
2595: sub make_room {
1.1172.2.81 raeburn 2596: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2597:
1.1172.2.81 raeburn 2598: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2599: : $value;
1.599 albertel 2600: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2601: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2602: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2603: my $to_kick;
2604: my $max_time=0;
2605: foreach my $other (keys(%accessed)) {
2606: if (&tv_interval($accessed{$other}) > $max_time) {
2607: $to_kick=$other;
2608: $max_time=&tv_interval($accessed{$other});
2609: }
2610: }
2611: delete($remembered{$to_kick});
2612: delete($accessed{$to_kick});
2613: $kicks++;
2614: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2615: return;
2616: }
2617:
1.599 albertel 2618: sub purge_remembered {
1.604 albertel 2619: #&logthis("Tossing ".scalar(keys(%remembered)));
2620: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2621: undef(%remembered);
2622: undef(%accessed);
1.428 albertel 2623: }
1.70 www 2624: # ------------------------------------- Read an entry from a user's environment
2625:
2626: sub userenvironment {
2627: my ($udom,$unam,@what)=@_;
1.976 raeburn 2628: my $items;
2629: foreach my $item (@what) {
2630: $items.=&escape($item).'&';
2631: }
2632: $items=~s/\&$//;
1.70 www 2633: my %returnhash=();
1.1009 raeburn 2634: my $uhome = &homeserver($unam,$udom);
2635: unless ($uhome eq 'no_host') {
2636: my @answer=split(/\&/,
2637: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2638: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2639: return %returnhash;
2640: }
1.1009 raeburn 2641: my $i;
2642: for ($i=0;$i<=$#what;$i++) {
2643: $returnhash{$what[$i]}=&unescape($answer[$i]);
2644: }
1.70 www 2645: }
2646: return %returnhash;
1.1 albertel 2647: }
2648:
1.617 albertel 2649: # ---------------------------------------------------------- Get a studentphoto
2650: sub studentphoto {
2651: my ($udom,$unam,$ext) = @_;
2652: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2653: if (defined($env{'request.course.id'})) {
1.708 raeburn 2654: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2655: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2656: return(&retrievestudentphoto($udom,$unam,$ext));
2657: } else {
2658: my ($result,$perm_reqd)=
1.707 albertel 2659: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2660: if ($result eq 'ok') {
2661: if (!($perm_reqd eq 'yes')) {
2662: return(&retrievestudentphoto($udom,$unam,$ext));
2663: }
2664: }
2665: }
2666: }
2667: } else {
2668: my ($result,$perm_reqd) =
1.707 albertel 2669: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2670: if ($result eq 'ok') {
2671: if (!($perm_reqd eq 'yes')) {
2672: return(&retrievestudentphoto($udom,$unam,$ext));
2673: }
2674: }
2675: }
2676: return '/adm/lonKaputt/lonlogo_broken.gif';
2677: }
2678:
2679: sub retrievestudentphoto {
2680: my ($udom,$unam,$ext,$type) = @_;
2681: my $home=&Apache::lonnet::homeserver($unam,$udom);
2682: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2683: if ($ret eq 'ok') {
2684: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2685: if ($type eq 'thumbnail') {
2686: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2687: }
2688: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2689: return $tokenurl;
2690: } else {
2691: if ($type eq 'thumbnail') {
2692: return '/adm/lonKaputt/genericstudent_tn.gif';
2693: } else {
2694: return '/adm/lonKaputt/lonlogo_broken.gif';
2695: }
1.617 albertel 2696: }
2697: }
2698:
1.263 www 2699: # -------------------------------------------------------------------- New chat
2700:
2701: sub chatsend {
1.724 raeburn 2702: my ($newentry,$anon,$group)=@_;
1.620 albertel 2703: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2704: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2705: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2706: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2707: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2708: &escape($newentry)).':'.$group,$chome);
1.292 www 2709: }
2710:
2711: # ------------------------------------------ Find current version of a resource
2712:
2713: sub getversion {
2714: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2715: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2716: return ¤tversion(&filelocation('',$fname));
2717: }
2718:
2719: sub currentversion {
2720: my $fname=shift;
2721: my $author=$fname;
2722: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2723: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2724: my $home=&homeserver($uname,$udom);
1.292 www 2725: if ($home eq 'no_host') {
2726: return -1;
2727: }
1.1112 www 2728: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2729: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2730: return -1;
2731: }
1.1112 www 2732: return $answer;
1.263 www 2733: }
2734:
1.1111 www 2735: #
2736: # Return special version number of resource if set by override, empty otherwise
2737: #
2738: sub usedversion {
2739: my $fname=shift;
2740: unless ($fname) { $fname=$env{'request.uri'}; }
2741: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2742: if ($urlversion) { return $urlversion; }
2743: return '';
2744: }
2745:
1.1 albertel 2746: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2747:
1.1 albertel 2748: sub subscribe {
2749: my $fname=shift;
1.761 raeburn 2750: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2751: $fname=~s/[\n\r]//g;
1.1 albertel 2752: my $author=$fname;
2753: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2754: my ($udom,$uname)=split(/\//,$author);
2755: my $home=homeserver($uname,$udom);
1.335 albertel 2756: if ($home eq 'no_host') {
2757: return 'not_found';
1.1 albertel 2758: }
2759: my $answer=reply("sub:$fname",$home);
1.64 www 2760: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2761: $answer.=' by '.$home;
2762: }
1.1 albertel 2763: return $answer;
2764: }
2765:
1.8 www 2766: # -------------------------------------------------------------- Replicate file
2767:
2768: sub repcopy {
2769: my $filename=shift;
1.23 www 2770: $filename=~s/\/+/\//g;
1.1142 raeburn 2771: my $londocroot = $perlvar{'lonDocRoot'};
2772: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2773: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2774: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2775: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2776: return &repcopy_userfile($filename);
2777: }
1.532 albertel 2778: $filename=~s/[\n\r]//g;
1.8 www 2779: my $transname="$filename.in.transfer";
1.828 www 2780: # FIXME: this should flock
1.607 raeburn 2781: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2782: my $remoteurl=subscribe($filename);
1.64 www 2783: if ($remoteurl =~ /^con_lost by/) {
2784: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2785: return 'unavailable';
1.8 www 2786: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2787: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2788: return 'not_found';
1.64 www 2789: } elsif ($remoteurl =~ /^rejected by/) {
2790: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2791: return 'forbidden';
1.20 www 2792: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2793: return 'ok';
1.8 www 2794: } else {
1.290 www 2795: my $author=$filename;
2796: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2797: my ($udom,$uname)=split(/\//,$author);
2798: my $home=homeserver($uname,$udom);
2799: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2800: my @parts=split(/\//,$filename);
2801: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2802: if ($path ne "$londocroot/res") {
1.8 www 2803: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2804: return 'bad_request';
1.8 www 2805: }
2806: my $count;
2807: for ($count=5;$count<$#parts;$count++) {
2808: $path.="/$parts[$count]";
2809: if ((-e $path)!=1) {
2810: mkdir($path,0777);
2811: }
2812: }
2813: my $ua=new LWP::UserAgent;
2814: my $request=new HTTP::Request('GET',"$remoteurl");
2815: my $response=$ua->request($request,$transname);
2816: if ($response->is_error()) {
2817: unlink($transname);
2818: my $message=$response->status_line;
1.672 albertel 2819: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2820: ." LWP get: $message: $filename</font>");
1.607 raeburn 2821: return 'unavailable';
1.8 www 2822: } else {
1.16 www 2823: if ($remoteurl!~/\.meta$/) {
2824: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2825: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2826: if ($mresponse->is_error()) {
2827: unlink($filename.'.meta');
2828: &logthis(
1.672 albertel 2829: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2830: }
2831: }
1.8 www 2832: rename($transname,$filename);
1.607 raeburn 2833: return 'ok';
1.8 www 2834: }
1.290 www 2835: }
1.8 www 2836: }
1.330 www 2837: }
2838:
2839: # ------------------------------------------------ Get server side include body
2840: sub ssi_body {
1.381 albertel 2841: my ($filelink,%form)=@_;
1.606 matthew 2842: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2843: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2844: }
1.953 www 2845: my $output='';
2846: my $response;
1.980 raeburn 2847: if ($filelink=~/^https?\:/) {
1.954 raeburn 2848: ($output,$response)=&externalssi($filelink);
1.953 www 2849: } else {
1.1004 droeschl 2850: $filelink .= $filelink=~/\?/ ? '&' : '?';
2851: $filelink .= 'inhibitmenu=yes';
1.953 www 2852: ($output,$response)=&ssi($filelink,%form);
2853: }
1.778 albertel 2854: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2855: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2856: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2857: if (wantarray) {
2858: return ($output, $response);
2859: } else {
2860: return $output;
2861: }
1.8 www 2862: }
2863:
1.15 www 2864: # --------------------------------------------------------- Server Side Include
2865:
1.782 albertel 2866: sub absolute_url {
2867: my ($host_name) = @_;
2868: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2869: if ($host_name eq '') {
2870: $host_name = $ENV{'SERVER_NAME'};
2871: }
2872: return $protocol.$host_name;
2873: }
2874:
1.942 foxr 2875: #
2876: # Server side include.
2877: # Parameters:
2878: # fn Possibly encrypted resource name/id.
2879: # form Hash that describes how the rendering should be done
2880: # and other things.
1.944 foxr 2881: # Returns:
1.950 raeburn 2882: # Scalar context: The content of the response.
2883: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2884: #
1.15 www 2885: sub ssi {
2886:
1.944 foxr 2887: my ($fn,%form)=@_;
1.15 www 2888: my $ua=new LWP::UserAgent;
1.23 www 2889: my $request;
1.711 albertel 2890:
2891: $form{'no_update_last_known'}=1;
1.895 albertel 2892: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2893: if (%form) {
1.782 albertel 2894: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2895: $request->content(join('&',map {
2896: my $name = escape($_);
2897: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2898: ? join("&$name=", map {escape($_) } @{$form{$_}})
2899: : &escape($form{$_}) );
2900: } keys(%form)));
1.23 www 2901: } else {
1.782 albertel 2902: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2903: }
2904:
1.15 www 2905: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2906: my $response= $ua->request($request);
1.944 foxr 2907: if (wantarray) {
1.1172.2.3 raeburn 2908: return ($response->content, $response);
1.944 foxr 2909: } else {
1.1172.2.3 raeburn 2910: return $response->content;
1.942 foxr 2911: }
1.324 www 2912: }
2913:
2914: sub externalssi {
2915: my ($url)=@_;
2916: my $ua=new LWP::UserAgent;
2917: my $request=new HTTP::Request('GET',$url);
2918: my $response=$ua->request($request);
1.954 raeburn 2919: if (wantarray) {
2920: return ($response->content, $response);
2921: } else {
2922: return $response->content;
2923: }
1.15 www 2924: }
1.254 www 2925:
1.492 albertel 2926: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2927:
2928: sub allowuploaded {
2929: my ($srcurl,$url)=@_;
2930: $url=&clutter(&declutter($url));
2931: my $dir=$url;
2932: $dir=~s/\/[^\/]+$//;
2933: my %httpref=();
2934: my $httpurl=&hreflocation('',$url);
2935: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2936: &Apache::lonnet::appenv(\%httpref);
1.254 www 2937: }
1.477 raeburn 2938:
1.1172.2.13 raeburn 2939: #
2940: # Determine if the current user should be able to edit a particular resource,
2941: # when viewing in course context.
2942: # (a) When viewing resource used to determine if "Edit" item is included in
2943: # Functions.
2944: # (b) When displaying folder contents in course editor, used to determine if
2945: # "Edit" link will be displayed alongside resource.
2946: #
2947: # input: six args -- filename (decluttered), course number, course domain,
2948: # url, symb (if registered) and group (if this is a group
2949: # item -- e.g., bulletin board, group page etc.).
2950: # output: array of five scalars --
2951: # $cfile -- url for file editing if editable on current server
2952: # $home -- homeserver of resource (i.e., for author if published,
2953: # or course if uploaded.).
2954: # $switchserver -- 1 if server switch will be needed.
2955: # $forceedit -- 1 if icon/link should be to go to edit mode
2956: # $forceview -- 1 if icon/link should be to go to view mode
2957: #
2958:
2959: sub can_edit_resource {
2960: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2961: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2962: #
2963: # For aboutme pages user can only edit his/her own.
2964: #
2965: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2966: my ($sdom,$sname) = ($1,$2);
2967: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2968: $home = $env{'user.home'};
2969: $cfile = $resurl;
2970: if ($env{'form.forceedit'}) {
2971: $forceview = 1;
2972: } else {
2973: $forceedit = 1;
2974: }
2975: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2976: } else {
2977: return;
2978: }
2979: }
2980:
2981: if ($env{'request.course.id'}) {
2982: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2983: if ($group ne '') {
2984: # if this is a group homepage or group bulletin board, check group privs
2985: my $allowed = 0;
2986: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2987: if ((&allowed('mdg',$env{'request.course.id'}.
2988: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2989: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2990: $allowed = 1;
2991: }
2992: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2993: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2994: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2995: $allowed = 1;
2996: }
2997: }
2998: if ($allowed) {
2999: $home=&homeserver($cnum,$cdom);
3000: if ($env{'form.forceedit'}) {
3001: $forceview = 1;
3002: } else {
3003: $forceedit = 1;
3004: }
3005: $cfile = $resurl;
3006: } else {
3007: return;
3008: }
3009: } else {
1.1172.2.15 raeburn 3010: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3011: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3012: return;
3013: }
3014: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3015: #
3016: # No edit allowed where CC has switched to student role.
3017: #
3018: return;
3019: }
3020: }
3021: }
3022:
3023: if ($file ne '') {
3024: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3025: if (&is_course_upload($file,$cnum,$cdom)) {
3026: $uploaded = 1;
3027: $incourse = 1;
3028: if ($file =~/\.(htm|html|css|js|txt)$/) {
3029: $cfile = &hreflocation('',$file);
3030: if ($env{'form.forceedit'}) {
3031: $forceview = 1;
3032: } else {
3033: $forceedit = 1;
3034: }
3035: }
3036: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3037: $incourse = 1;
3038: if ($env{'form.forceedit'}) {
3039: $forceview = 1;
3040: } else {
3041: $forceedit = 1;
3042: }
3043: $cfile = $resurl;
3044: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3045: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3046: $incourse = 1;
3047: if ($env{'form.forceedit'}) {
3048: $forceview = 1;
3049: } else {
3050: $forceedit = 1;
3051: }
3052: $cfile = $resurl;
3053: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3054: $incourse = 1;
3055: $cfile = $resurl.'/smpedit';
3056: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3057: $incourse = 1;
3058: if ($env{'form.forceedit'}) {
3059: $forceview = 1;
3060: } else {
3061: $forceedit = 1;
3062: }
3063: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3064:7): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3065:7): $incourse = 1;
3066:7): if ($env{'form.forceedit'}) {
3067:7): $forceview = 1;
3068:7): } else {
3069:7): $forceedit = 1;
3070:7): }
3071:7): $cfile = $resurl;
1.1172.2.15 raeburn 3072: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3073: $incourse = 1;
3074: if ($env{'form.forceedit'}) {
3075: $forceview = 1;
3076: } else {
3077: $forceedit = 1;
3078: }
3079: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3080: }
3081: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3082: my $template = '/res/lib/templates/simpleproblem.problem';
3083: if (&is_on_map($template)) {
3084: $incourse = 1;
3085: $forceview = 1;
3086: $cfile = $template;
3087: }
3088: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3089: $incourse = 1;
3090: if ($env{'form.forceedit'}) {
3091: $forceview = 1;
3092: } else {
3093: $forceedit = 1;
3094: }
3095: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3096:7): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3097:7): $incourse = 1;
3098:7): if ($env{'form.forceedit'}) {
3099:7): $forceview = 1;
3100:7): } else {
3101:7): $forceedit = 1;
3102:7): }
3103:7): $cfile = $resurl;
1.1172.2.13 raeburn 3104: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3105: $incourse = 1;
3106: $forceview = 1;
3107: if ($symb) {
3108: my ($map,$id,$res)=&decode_symb($symb);
3109: $env{'request.symb'} = $symb;
3110: $cfile = &clutter($res);
3111: } else {
3112: $cfile = $env{'form.suppurl'};
1.1172.2.93.4 1(raebur 3113:7): my $escfile = &unescape($cfile);
2(raebur 3114:7): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3115:7): $cfile = '/adm/wrapper'.$escfile;
3116:7): } else {
3117:7): $escfile =~ s{^http://}{};
3118:7): $cfile = &escape("/adm/wrapper/ext/$escfile");
3119:7): }
1.1172.2.13 raeburn 3120: }
1.1172.2.31 raeburn 3121: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3122: if ($env{'form.forceedit'}) {
3123: $forceview = 1;
3124: } else {
3125: $forceedit = 1;
3126: }
3127: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3128: }
3129: }
3130: if ($uploaded || $incourse) {
3131: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3132: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3133: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3134: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3135: # Check that the user has permission to edit this resource
3136: my $setpriv = 1;
3137: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3138: if (defined($cfudom)) {
3139: $home=&homeserver($cfuname,$cfudom);
3140: $cfile=$file;
3141: }
3142: }
3143: if (($cfile ne '') && (!$incourse || $uploaded) &&
3144: (($home ne '') && ($home ne 'no_host'))) {
3145: my @ids=¤t_machine_ids();
3146: unless (grep(/^\Q$home\E$/,@ids)) {
3147: $switchserver=1;
3148: }
3149: }
3150: }
3151: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3152: }
3153:
3154: sub is_course_upload {
3155: my ($file,$cnum,$cdom) = @_;
3156: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3157: $uploadpath =~ s{^\/}{};
3158: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3159: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3160: return 1;
3161: }
3162: return;
3163: }
3164:
3165: sub in_course {
3166: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3167: if ($hideprivileged) {
3168: my $skipuser;
1.1172.2.23 raeburn 3169: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3170: my @possdoms = ($cdom);
3171: if ($coursehash{'checkforpriv'}) {
3172: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3173: }
3174: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3175: $skipuser = 1;
3176: if ($coursehash{'nothideprivileged'}) {
3177: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3178: my $user;
3179: if ($item =~ /:/) {
3180: $user = $item;
3181: } else {
3182: $user = join(':',split(/[\@]/,$item));
3183: }
3184: if ($user eq $uname.':'.$udom) {
3185: undef($skipuser);
3186: last;
3187: }
3188: }
3189: }
3190: if ($skipuser) {
3191: return 0;
3192: }
3193: }
3194: }
3195: $type ||= 'any';
3196: if (!defined($cdom) || !defined($cnum)) {
3197: my $cid = $env{'request.course.id'};
3198: $cdom = $env{'course.'.$cid.'.domain'};
3199: $cnum = $env{'course.'.$cid.'.num'};
3200: }
3201: my $typesref;
3202: if (($type eq 'any') || ($type eq 'all')) {
3203: $typesref = ['active','previous','future'];
3204: } elsif ($type eq 'previous' || $type eq 'future') {
3205: $typesref = [$type];
3206: }
3207: my %roles = &get_my_roles($uname,$udom,'userroles',
3208: $typesref,undef,[$cdom]);
3209: my ($tmp) = keys(%roles);
3210: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3211: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3212: if (@course_roles > 0) {
3213: return 1;
3214: }
3215: return 0;
3216: }
3217:
1.478 albertel 3218: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3219: # input: action, courseID, current domain, intended
1.637 raeburn 3220: # path to file, source of file, instruction to parse file for objects,
3221: # ref to hash for embedded objects,
3222: # ref to hash for codebase of java objects.
1.1095 raeburn 3223: # reference to scalar to accommodate mime type determined
3224: # from File::MMagic if $parser = parse.
1.637 raeburn 3225: #
1.485 raeburn 3226: # output: url to file (if action was uploaddoc),
3227: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3228: #
1.478 albertel 3229: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3230: # course.
1.477 raeburn 3231: #
1.478 albertel 3232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3233: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3234: # course's home server.
1.477 raeburn 3235: #
1.478 albertel 3236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3237: # be copied from $source (current location) to
3238: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3239: # and will then be copied to
3240: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3241: # course's home server.
1.485 raeburn 3242: #
1.481 raeburn 3243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3244: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3245: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3246: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3247: # in course's home server.
1.637 raeburn 3248: #
1.477 raeburn 3249:
3250: sub process_coursefile {
1.1095 raeburn 3251: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3252: $mimetype)=@_;
1.477 raeburn 3253: my $fetchresult;
1.638 albertel 3254: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3255: if ($action eq 'propagate') {
1.638 albertel 3256: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3257: $home);
1.481 raeburn 3258: } else {
1.477 raeburn 3259: my $fpath = '';
3260: my $fname = $file;
1.478 albertel 3261: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3262: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3263: my $filepath = &build_filepath($fpath);
1.481 raeburn 3264: if ($action eq 'copy') {
3265: if ($source eq '') {
3266: $fetchresult = 'no source file';
3267: return $fetchresult;
3268: } else {
3269: my $destination = $filepath.'/'.$fname;
3270: rename($source,$destination);
3271: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3272: $home);
1.481 raeburn 3273: }
3274: } elsif ($action eq 'uploaddoc') {
1.1172.2.93.4 7(raebur 3275:7): open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3276: print $fh $env{'form.'.$source};
1.481 raeburn 3277: close($fh);
1.637 raeburn 3278: if ($parser eq 'parse') {
1.1024 raeburn 3279: my $mm = new File::MMagic;
1.1095 raeburn 3280: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3281: if ($type eq 'text/html') {
1.1024 raeburn 3282: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3283: unless ($parse_result eq 'ok') {
3284: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3285: }
1.637 raeburn 3286: }
1.1095 raeburn 3287: if (ref($mimetype)) {
3288: $$mimetype = $type;
3289: }
1.637 raeburn 3290: }
1.477 raeburn 3291: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3292: $home);
1.481 raeburn 3293: if ($fetchresult eq 'ok') {
3294: return '/uploaded/'.$fpath.'/'.$fname;
3295: } else {
3296: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3297: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3298: return '/adm/notfound.html';
3299: }
1.477 raeburn 3300: }
3301: }
1.485 raeburn 3302: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3303: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3304: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3305: }
3306: return $fetchresult;
3307: }
3308:
1.637 raeburn 3309: sub build_filepath {
3310: my ($fpath) = @_;
3311: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3312: unless ($fpath eq '') {
3313: my @parts=split('/',$fpath);
3314: foreach my $part (@parts) {
3315: $filepath.= '/'.$part;
3316: if ((-e $filepath)!=1) {
3317: mkdir($filepath,0777);
3318: }
3319: }
3320: }
3321: return $filepath;
3322: }
3323:
3324: sub store_edited_file {
1.638 albertel 3325: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3326: my $file = $primary_url;
3327: $file =~ s#^/uploaded/$docudom/$docuname/##;
3328: my $fpath = '';
3329: my $fname = $file;
3330: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3331: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3332: my $filepath = &build_filepath($fpath);
1.1172.2.93.4 7(raebur 3333:7): open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3334: print $fh $content;
3335: close($fh);
1.638 albertel 3336: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3337: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3338: $home);
1.637 raeburn 3339: if ($$fetchresult eq 'ok') {
3340: return '/uploaded/'.$fpath.'/'.$fname;
3341: } else {
1.638 albertel 3342: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3343: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3344: return '/adm/notfound.html';
3345: }
3346: }
3347:
1.531 albertel 3348: sub clean_filename {
1.831 albertel 3349: my ($fname,$args)=@_;
1.315 www 3350: # Replace Windows backslashes by forward slashes
1.257 www 3351: $fname=~s/\\/\//g;
1.831 albertel 3352: if (!$args->{'keep_path'}) {
3353: # Get rid of everything but the actual filename
3354: $fname=~s/^.*\/([^\/]+)$/$1/;
3355: }
1.315 www 3356: # Replace spaces by underscores
3357: $fname=~s/\s+/\_/g;
3358: # Replace all other weird characters by nothing
1.831 albertel 3359: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3360: # Replace all .\d. sequences with _\d. so they no longer look like version
3361: # numbers
3362: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3363: return $fname;
3364: }
1.1051 raeburn 3365: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3366: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3367: # image with the same aspect ratio as the original, but with dimensions which do
3368: # not exceed $resizewidth and $resizeheight.
3369:
1.984 neumanie 3370: sub resizeImage {
1.1051 raeburn 3371: my ($img_path,$resizewidth,$resizeheight) = @_;
3372: my $ima = Image::Magick->new;
3373: my $resized;
3374: if (-e $img_path) {
3375: $ima->Read($img_path);
3376: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3377: my $width = $ima->Get('width');
3378: my $height = $ima->Get('height');
3379: if ($width > $resizewidth) {
3380: my $factor = $width/$resizewidth;
3381: my $newheight = $height/$factor;
3382: $ima->Scale(width=>$resizewidth,height=>$newheight);
3383: $resized = 1;
3384: }
3385: }
3386: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3387: my $width = $ima->Get('width');
3388: my $height = $ima->Get('height');
3389: if ($height > $resizeheight) {
3390: my $factor = $height/$resizeheight;
3391: my $newwidth = $width/$factor;
3392: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3393: $resized = 1;
3394: }
3395: }
3396: if ($resized) {
3397: $ima->Write($img_path);
3398: }
3399: }
3400: return;
1.977 amueller 3401: }
3402:
1.608 albertel 3403: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3404: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3405: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3406: # $context - possible values: coursedoc, existingfile, overwrite,
3407: # canceloverwrite, or ''.
3408: # if 'coursedoc': upload to the current course
3409: # if 'existingfile': write file to tmp/overwrites directory
3410: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3411: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3412: # $subdir - directory in userfile to store the file into
1.858 raeburn 3413: # $parser - instruction to parse file for objects ($parser = parse)
3414: # $allfiles - reference to hash for embedded objects
3415: # $codebase - reference to hash for codebase of java objects
3416: # $desuname - username for permanent storage of uploaded file
3417: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3418: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3419: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3420: # $resizewidth - width (pixels) to which to resize uploaded image
3421: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3422: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3423: # from File::MMagic.
1.858 raeburn 3424: #
1.686 albertel 3425: # output: url of file in userspace, or error: <message>
3426: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3427:
1.531 albertel 3428: sub userfileupload {
1.1090 raeburn 3429: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3430: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3431: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3432: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3433: $fname=&clean_filename($fname);
1.1090 raeburn 3434: # See if there is anything left
1.257 www 3435: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3436: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3437: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3438: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3439: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3440: my $now = time;
1.1090 raeburn 3441: my $filepath;
1.1095 raeburn 3442: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3443: $filepath = 'tmp/helprequests/'.$now;
3444: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3445: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3446: '_'.$env{'user.domain'}.'/pending';
3447: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3448: my ($docuname,$docudom);
1.1172.2.93.4 5(raebur 3449:7): if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3450: $docudom = $destudom;
3451: } else {
3452: $docudom = $env{'user.domain'};
3453: }
1.1172.2.93.4 5(raebur 3454:7): if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3455: $docuname = $destuname;
3456: } else {
3457: $docuname = $env{'user.name'};
3458: }
3459: if (exists($env{'form.group'})) {
3460: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3461: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3462: }
3463: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3464: if ($context eq 'canceloverwrite') {
3465: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3466: if (-e $tempfile) {
3467: my @info = stat($tempfile);
3468: if ($info[9] eq $env{'form.timestamp'}) {
3469: unlink($tempfile);
3470: }
3471: }
3472: return;
1.523 raeburn 3473: }
3474: }
1.1090 raeburn 3475: # Create the directory if not present
1.741 raeburn 3476: my @parts=split(/\//,$filepath);
3477: my $fullpath = $perlvar{'lonDaemons'};
3478: for (my $i=0;$i<@parts;$i++) {
3479: $fullpath .= '/'.$parts[$i];
3480: if ((-e $fullpath)!=1) {
3481: mkdir($fullpath,0777);
3482: }
3483: }
1.1172.2.93.4 7(raebur 3484:7): open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3485: print $fh $env{'form.'.$formname};
3486: close($fh);
1.1090 raeburn 3487: if ($context eq 'existingfile') {
3488: my @info = stat($fullpath.'/'.$fname);
3489: return ($fullpath.'/'.$fname,$info[9]);
3490: } else {
3491: return $fullpath.'/'.$fname;
3492: }
1.523 raeburn 3493: }
1.995 raeburn 3494: if ($subdir eq 'scantron') {
3495: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3496: } else {
1.995 raeburn 3497: $fname="$subdir/$fname";
3498: }
1.1090 raeburn 3499: if ($context eq 'coursedoc') {
1.638 albertel 3500: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3501: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3502: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3503: return &finishuserfileupload($docuname,$docudom,
3504: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3505: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3506: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3507: } else {
1.1172.2.21 raeburn 3508: if ($env{'form.folder'}) {
3509: $fname=$env{'form.folder'}.'/'.$fname;
3510: }
1.638 albertel 3511: return &process_coursefile('uploaddoc',$docuname,$docudom,
3512: $fname,$formname,$parser,
1.1095 raeburn 3513: $allfiles,$codebase,$mimetype);
1.481 raeburn 3514: }
1.719 banghart 3515: } elsif (defined($destuname)) {
3516: my $docuname=$destuname;
3517: my $docudom=$destudom;
1.860 raeburn 3518: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3519: $parser,$allfiles,$codebase,
1.1051 raeburn 3520: $thumbwidth,$thumbheight,
1.1095 raeburn 3521: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3522: } else {
1.638 albertel 3523: my $docuname=$env{'user.name'};
3524: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3525: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3526: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3527: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3528: }
1.860 raeburn 3529: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3530: $parser,$allfiles,$codebase,
1.1051 raeburn 3531: $thumbwidth,$thumbheight,
1.1095 raeburn 3532: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3533: }
1.271 www 3534: }
3535:
3536: sub finishuserfileupload {
1.860 raeburn 3537: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3538: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3539: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3540: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3541:
1.860 raeburn 3542: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3543: $file=$fname;
3544: if ($fname=~m|/|) {
3545: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3546: $path.=$fnamepath.'/';
3547: }
1.259 www 3548: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3549: my $count;
3550: for ($count=4;$count<=$#parts;$count++) {
3551: $filepath.="/$parts[$count]";
3552: if ((-e $filepath)!=1) {
3553: mkdir($filepath,0777);
3554: }
3555: }
1.984 neumanie 3556:
1.258 www 3557: # Save the file
3558: {
1.1172.2.93.4 7(raebur 3559:7): if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3560: &logthis('Failed to create '.$filepath.'/'.$file);
3561: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3562: return '/adm/notfound.html';
3563: }
1.1090 raeburn 3564: if ($context eq 'overwrite') {
1.1117 foxr 3565: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3566: my $target = $filepath.'/'.$file;
3567: if (-e $source) {
3568: my @info = stat($source);
3569: if ($info[9] eq $env{'form.timestamp'}) {
3570: unless (&File::Copy::move($source,$target)) {
3571: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3572: return "Moving from $source failed";
3573: }
3574: } else {
3575: return "Temporary file: $source had unexpected date/time for last modification";
3576: }
3577: } else {
3578: return "Temporary file: $source missing";
3579: }
3580: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3581: &logthis('Failed to write to '.$filepath.'/'.$file);
3582: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3583: return '/adm/notfound.html';
3584: }
1.570 albertel 3585: close(FH);
1.1051 raeburn 3586: if ($resizewidth && $resizeheight) {
3587: my $mm = new File::MMagic;
3588: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3589: if ($mime_type =~ m{^image/}) {
3590: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3591: }
1.977 amueller 3592: }
1.258 www 3593: }
1.1152 raeburn 3594: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3595: if (ref($mimetype)) {
3596: if ($$mimetype eq '') {
3597: my $mm = new File::MMagic;
3598: my $type = $mm->checktype_filename($filepath.'/'.$file);
3599: $$mimetype = $type;
3600: }
3601: }
3602: }
1.637 raeburn 3603: if ($parser eq 'parse') {
1.1152 raeburn 3604: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3605: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3606: $allfiles,$codebase);
3607: unless ($parse_result eq 'ok') {
3608: &logthis('Failed to parse '.$filepath.$file.
3609: ' for embedded media: '.$parse_result);
3610: }
1.637 raeburn 3611: }
3612: }
1.860 raeburn 3613: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3614: my $input = $filepath.'/'.$file;
3615: my $output = $filepath.'/'.'tn-'.$file;
3616: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.93.4 7(raebur 3617:7): my @args = ('convert','-sample',$thumbsize,$input,$output);
3618:7): system({$args[0]} @args);
1.860 raeburn 3619: if (-e $filepath.'/'.'tn-'.$file) {
3620: $fetchthumb = 1;
3621: }
3622: }
1.858 raeburn 3623:
1.259 www 3624: # Notify homeserver to grep it
3625: #
1.984 neumanie 3626: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3627: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3628: if ($fetchresult eq 'ok') {
1.860 raeburn 3629: if ($fetchthumb) {
3630: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3631: if ($thumbresult ne 'ok') {
3632: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3633: $docuhome.': '.$thumbresult);
3634: }
3635: }
1.259 www 3636: #
1.258 www 3637: # Return the URL to it
1.494 albertel 3638: return '/uploaded/'.$path.$file;
1.263 www 3639: } else {
1.494 albertel 3640: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3641: ': '.$fetchresult);
1.263 www 3642: return '/adm/notfound.html';
1.858 raeburn 3643: }
1.493 albertel 3644: }
3645:
1.637 raeburn 3646: sub extract_embedded_items {
1.961 raeburn 3647: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3648: my @state = ();
1.1164 raeburn 3649: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3650: my %javafiles = (
3651: codebase => '',
3652: code => '',
3653: archive => ''
3654: );
3655: my %mediafiles = (
3656: src => '',
3657: movie => '',
3658: );
1.648 raeburn 3659: my $p;
3660: if ($content) {
3661: $p = HTML::LCParser->new($content);
3662: } else {
1.961 raeburn 3663: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3664: }
1.641 albertel 3665: while (my $t=$p->get_token()) {
1.640 albertel 3666: if ($t->[0] eq 'S') {
3667: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3668: push(@state, $tagname);
1.648 raeburn 3669: if (lc($tagname) eq 'allow') {
3670: &add_filetype($allfiles,$attr->{'src'},'src');
3671: }
1.640 albertel 3672: if (lc($tagname) eq 'img') {
3673: &add_filetype($allfiles,$attr->{'src'},'src');
3674: }
1.886 albertel 3675: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3676: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3677: &add_filetype($allfiles,$attr->{'href'},'href');
3678: }
1.886 albertel 3679: }
1.645 raeburn 3680: if (lc($tagname) eq 'script') {
1.1164 raeburn 3681: my $src;
1.645 raeburn 3682: if ($attr->{'archive'} =~ /\.jar$/i) {
3683: &add_filetype($allfiles,$attr->{'archive'},'archive');
3684: } else {
1.1164 raeburn 3685: if ($attr->{'src'} ne '') {
3686: $src = $attr->{'src'};
3687: &add_filetype($allfiles,$src,'src');
3688: }
3689: }
3690: my $text = $p->get_trimmed_text();
3691: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3692: my @swfargs = split(/,/,$1);
3693: foreach my $item (@swfargs) {
3694: $item =~ s/["']//g;
3695: $item =~ s/^\s+//;
3696: $item =~ s/\s+$//;
3697: }
3698: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3699: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3700: push(@{$related{$swfargs[0]}},$swfargs[2]);
3701: } else {
3702: $related{$swfargs[0]} = [$swfargs[2]];
3703: }
3704: }
1.645 raeburn 3705: }
3706: }
3707: if (lc($tagname) eq 'link') {
3708: if (lc($attr->{'rel'}) eq 'stylesheet') {
3709: &add_filetype($allfiles,$attr->{'href'},'href');
3710: }
3711: }
1.640 albertel 3712: if (lc($tagname) eq 'object' ||
3713: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3714: foreach my $item (keys(%javafiles)) {
3715: $javafiles{$item} = '';
3716: }
1.1164 raeburn 3717: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3718: $lastids{lc($tagname)} = $attr->{'id'};
3719: }
1.640 albertel 3720: }
3721: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3722: my $name = lc($attr->{'name'});
3723: foreach my $item (keys(%javafiles)) {
3724: if ($name eq $item) {
3725: $javafiles{$item} = $attr->{'value'};
3726: last;
3727: }
3728: }
1.1164 raeburn 3729: my $pathfrom;
1.640 albertel 3730: foreach my $item (keys(%mediafiles)) {
3731: if ($name eq $item) {
1.1164 raeburn 3732: $pathfrom = $attr->{'value'};
3733: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3734: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3735: last;
3736: }
3737: }
1.1164 raeburn 3738: if ($name eq 'flashvars') {
3739: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3740: }
3741: if ($pathfrom ne '') {
3742: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3743: $pathfrom);
3744: }
1.640 albertel 3745: }
3746: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3747: foreach my $item (keys(%javafiles)) {
3748: if ($attr->{$item}) {
3749: $javafiles{$item} = $attr->{$item};
3750: last;
3751: }
3752: }
3753: foreach my $item (keys(%mediafiles)) {
3754: if ($attr->{$item}) {
3755: &add_filetype($allfiles,$attr->{$item},$item);
3756: last;
3757: }
3758: }
1.1164 raeburn 3759: if (lc($tagname) eq 'embed') {
3760: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3761: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3762: $attr->{'src'});
3763: }
3764: }
1.640 albertel 3765: }
1.1172.2.35 raeburn 3766: if (lc($tagname) eq 'iframe') {
3767: my $src = $attr->{'src'} ;
3768: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3769: &add_filetype($allfiles,$src,'src');
3770: } elsif ($src =~ m{^/}) {
3771: if ($env{'request.course.id'}) {
3772: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3773: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3774: my $url = &hreflocation('',$fullpath);
3775: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3776: my $relpath = $1;
3777: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3778: &add_filetype($allfiles,$1,'src');
3779: }
3780: }
3781: }
3782: }
3783: }
1.1164 raeburn 3784: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3785: pop(@state);
1.1164 raeburn 3786: }
1.640 albertel 3787: } elsif ($t->[0] eq 'E') {
3788: my ($tagname) = ($t->[1]);
3789: if ($javafiles{'codebase'} ne '') {
3790: $javafiles{'codebase'} .= '/';
3791: }
3792: if (lc($tagname) eq 'applet' ||
3793: lc($tagname) eq 'object' ||
3794: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3795: ) {
3796: foreach my $item (keys(%javafiles)) {
3797: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3798: my $file=$javafiles{'codebase'}.$javafiles{$item};
3799: &add_filetype($allfiles,$file,$item);
3800: }
3801: }
3802: }
3803: pop @state;
3804: }
3805: }
1.1164 raeburn 3806: foreach my $id (sort(keys(%flashvars))) {
3807: if ($shockwave{$id} ne '') {
3808: my @pairs = split(/\&/,$flashvars{$id});
3809: foreach my $pair (@pairs) {
3810: my ($key,$value) = split(/\=/,$pair);
3811: if ($key eq 'thumb') {
3812: &add_filetype($allfiles,$value,$key);
3813: } elsif ($key eq 'content') {
3814: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3815: my ($ext) = ($value =~ /\.([^.]+)$/);
3816: if ($ext ne '') {
3817: &add_filetype($allfiles,$path.$value,$ext);
3818: }
3819: }
3820: }
3821: }
3822: }
1.637 raeburn 3823: return 'ok';
3824: }
3825:
1.639 albertel 3826: sub add_filetype {
3827: my ($allfiles,$file,$type)=@_;
3828: if (exists($allfiles->{$file})) {
3829: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3830: push(@{$allfiles->{$file}}, &escape($type));
3831: }
3832: } else {
3833: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3834: }
3835: }
3836:
1.1164 raeburn 3837: sub embedded_dependency {
3838: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3839: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3840: if (($identifier ne '') &&
3841: (ref($related->{$identifier}) eq 'ARRAY') &&
3842: ($pathfrom ne '')) {
3843: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3844: foreach my $dep (@{$related->{$identifier}}) {
3845: &add_filetype($allfiles,$path.$dep,'object');
3846: }
3847: }
3848: }
3849: return;
3850: }
3851:
1.493 albertel 3852: sub removeuploadedurl {
1.984 neumanie 3853: my ($url)=@_;
3854: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3855: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3856: }
3857:
3858: sub removeuserfile {
3859: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3860: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3861: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3862: if ($result eq 'ok') {
1.798 raeburn 3863: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3864: my $metafile = $fname.'.meta';
3865: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3866: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3867: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3868: my $sqlresult =
1.823 albertel 3869: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3870: 'portfolio_metadata',$group,
3871: 'delete');
1.798 raeburn 3872: }
3873: }
3874: return $result;
1.257 www 3875: }
1.15 www 3876:
1.530 albertel 3877: sub mkdiruserfile {
3878: my ($docuname,$docudom,$dir)=@_;
3879: my $home=&homeserver($docuname,$docudom);
3880: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3881: }
3882:
1.531 albertel 3883: sub renameuserfile {
3884: my ($docuname,$docudom,$old,$new)=@_;
3885: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3886: my $result = &reply("renameuserfile:$docudom:$docuname:".
3887: &escape("$old").':'.&escape("$new"),$home);
3888: if ($result eq 'ok') {
3889: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3890: my $oldmeta = $old.'.meta';
3891: my $newmeta = $new.'.meta';
3892: my $metaresult =
3893: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3894: my $url = "/uploaded/$docudom/$docuname/$old";
3895: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3896: my $sqlresult =
1.823 albertel 3897: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3898: 'portfolio_metadata',$group,
3899: 'delete');
1.798 raeburn 3900: }
3901: }
3902: return $result;
1.531 albertel 3903: }
3904:
1.14 www 3905: # ------------------------------------------------------------------------- Log
3906:
3907: sub log {
3908: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3909: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3910: }
3911:
3912: # ------------------------------------------------------------------ Course Log
1.352 www 3913: #
3914: # This routine flushes several buffers of non-mission-critical nature
3915: #
1.157 www 3916:
3917: sub flushcourselogs {
1.352 www 3918: &logthis('Flushing log buffers');
3919: #
3920: # course logs
3921: # This is a log of all transactions in a course, which can be used
3922: # for data mining purposes
3923: #
3924: # It also collects the courseid database, which lists last transaction
3925: # times and course titles for all courseids
3926: #
3927: my %courseidbuffer=();
1.921 raeburn 3928: foreach my $crsid (keys(%courselogs)) {
1.352 www 3929: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3930: &escape($courselogs{$crsid}),
3931: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3932: delete $courselogs{$crsid};
3933: } else {
3934: &logthis('Failed to flush log buffer for '.$crsid);
3935: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3936: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3937: " exceeded maximum size, deleting.</font>");
3938: delete $courselogs{$crsid};
3939: }
1.352 www 3940: }
1.920 raeburn 3941: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3942: 'description' => $coursedescrbuf{$crsid},
3943: 'inst_code' => $courseinstcodebuf{$crsid},
3944: 'type' => $coursetypebuf{$crsid},
3945: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3946: };
1.191 harris41 3947: }
1.352 www 3948: #
3949: # Write course id database (reverse lookup) to homeserver of courses
3950: # Is used in pickcourse
3951: #
1.840 albertel 3952: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3953: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3954: $courseidbuffer{$crs_home},
3955: $crs_home,'timeonly');
1.352 www 3956: }
3957: #
3958: # File accesses
3959: # Writes to the dynamic metadata of resources to get hit counts, etc.
3960: #
1.449 matthew 3961: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3962: if ($entry =~ /___count$/) {
3963: my ($dom,$name);
1.807 albertel 3964: ($dom,$name,undef)=
1.811 albertel 3965: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3966: if (! defined($dom) || $dom eq '' ||
3967: ! defined($name) || $name eq '') {
1.620 albertel 3968: my $cid = $env{'request.course.id'};
3969: $dom = $env{'request.'.$cid.'.domain'};
3970: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3971: }
1.450 matthew 3972: my $value = $accesshash{$entry};
3973: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3974: my %temphash=($url => $value);
1.449 matthew 3975: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3976: if ($result eq 'ok') {
3977: delete $accesshash{$entry};
3978: }
3979: } else {
1.811 albertel 3980: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3981: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3982: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3983: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3984: delete $accesshash{$entry};
3985: }
1.185 www 3986: }
1.191 harris41 3987: }
1.352 www 3988: #
3989: # Roles
3990: # Reverse lookup of user roles for course faculty/staff and co-authorship
3991: #
1.800 albertel 3992: foreach my $entry (keys(%userrolehash)) {
1.351 www 3993: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3994: split(/\:/,$entry);
3995: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3996: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3997: $rudom,$runame) eq 'ok') {
3998: delete $userrolehash{$entry};
3999: }
4000: }
1.662 raeburn 4001: #
1.1172.2.90 raeburn 4002: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4003: #
4004: my %domrolebuffer = ();
1.1000 raeburn 4005: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4006: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4007: if ($domrolebuffer{$rudom}) {
4008: $domrolebuffer{$rudom}.='&'.&escape($entry).
4009: '='.&escape($domainrolehash{$entry});
4010: } else {
4011: $domrolebuffer{$rudom}.=&escape($entry).
4012: '='.&escape($domainrolehash{$entry});
4013: }
4014: delete $domainrolehash{$entry};
4015: }
4016: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4017: my %servers;
4018: if (defined(&domain($dom,'primary'))) {
4019: my $primary=&domain($dom,'primary');
4020: my $hostname=&hostname($primary);
4021: $servers{$primary} = $hostname;
4022: } else {
4023: %servers = &get_servers($dom,'library');
4024: }
1.841 albertel 4025: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4026: if (&reply('domroleput:'.$dom.':'.
4027: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4028: last;
4029: } else {
1.841 albertel 4030: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4031: }
1.662 raeburn 4032: }
4033: }
1.186 www 4034: $dumpcount++;
1.157 www 4035: }
4036:
4037: sub courselog {
4038: my $what=shift;
1.158 www 4039: $what=time.':'.$what;
1.620 albertel 4040: unless ($env{'request.course.id'}) { return ''; }
4041: $coursedombuf{$env{'request.course.id'}}=
4042: $env{'course.'.$env{'request.course.id'}.'.domain'};
4043: $coursenumbuf{$env{'request.course.id'}}=
4044: $env{'course.'.$env{'request.course.id'}.'.num'};
4045: $coursehombuf{$env{'request.course.id'}}=
4046: $env{'course.'.$env{'request.course.id'}.'.home'};
4047: $coursedescrbuf{$env{'request.course.id'}}=
4048: $env{'course.'.$env{'request.course.id'}.'.description'};
4049: $courseinstcodebuf{$env{'request.course.id'}}=
4050: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4051: $courseownerbuf{$env{'request.course.id'}}=
4052: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4053: $coursetypebuf{$env{'request.course.id'}}=
4054: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4055: if (defined $courselogs{$env{'request.course.id'}}) {
4056: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4057: } else {
1.620 albertel 4058: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4059: }
1.620 albertel 4060: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4061: &flushcourselogs();
4062: }
1.158 www 4063: }
4064:
4065: sub courseacclog {
4066: my $fnsymb=shift;
1.620 albertel 4067: unless ($env{'request.course.id'}) { return ''; }
4068: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4069: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4070: $what.=':POST';
1.583 matthew 4071: # FIXME: Probably ought to escape things....
1.800 albertel 4072: foreach my $key (keys(%env)) {
4073: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4074: my $formitem = $1;
4075: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4076: $what.=':'.$formitem.'='.$env{$key};
4077: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4078: $what.=':'.$formitem.'='.$env{$key};
4079: }
1.158 www 4080: }
1.191 harris41 4081: }
1.583 matthew 4082: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4083: # FIXME: We should not be depending on a form parameter that someone
4084: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4085: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4086: $what.= ':POST';
4087: # FIXME: Probably ought to escape things....
4088: foreach my $element ('courseexp','crsfulltext','crsrelated',
4089: 'crsdiscuss') {
1.620 albertel 4090: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4091: }
4092: }
1.158 www 4093: }
4094: &courselog($what);
1.149 www 4095: }
4096:
1.185 www 4097: sub countacc {
4098: my $url=&declutter(shift);
1.458 matthew 4099: return if (! defined($url) || $url eq '');
1.620 albertel 4100: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4101: #
4102: # Mark that this url was used in this course
4103: #
1.620 albertel 4104: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4105: #
4106: # Increase the access count for this resource in this child process
4107: #
1.281 www 4108: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4109: $accesshash{$key}++;
1.185 www 4110: }
1.349 www 4111:
1.361 www 4112: sub linklog {
4113: my ($from,$to)=@_;
4114: $from=&declutter($from);
4115: $to=&declutter($to);
4116: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4117: $accesshash{$to.'___'.$from.'___goto'}=1;
4118: }
1.1160 www 4119:
4120: sub statslog {
4121: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4122: if ($users<2) { return; }
4123: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4124: 'course' => $env{'request.course.id'},
4125: 'sections' => '"all"',
4126: 'num_students' => $users,
4127: 'part' => $part,
4128: 'symb' => $symb,
4129: 'mean_tries' => $av_attempts,
4130: 'deg_of_diff' => $degdiff});
4131: foreach my $key (keys(%dynstore)) {
4132: $accesshash{$key}=$dynstore{$key};
4133: }
4134: }
1.361 www 4135:
1.349 www 4136: sub userrolelog {
4137: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4138: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4139: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4140: $userrolehash
4141: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4142: =$tend.':'.$tstart;
1.662 raeburn 4143: }
1.1169 droeschl 4144: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4145: $userrolehash
4146: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4147: =$tend.':'.$tstart;
4148: }
1.1172.2.90 raeburn 4149: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4150: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4151: $domainrolehash
4152: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4153: = $tend.':'.$tstart;
4154: }
1.351 www 4155: }
4156:
1.957 raeburn 4157: sub courserolelog {
4158: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4159: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4160: my $cdom = $1;
4161: my $cnum = $2;
4162: my $sec = $3;
4163: my $namespace = 'rolelog';
4164: my %storehash = (
4165: role => $trole,
4166: start => $tstart,
4167: end => $tend,
4168: selfenroll => $selfenroll,
4169: context => $context,
4170: );
4171: if ($trole eq 'gr') {
4172: $namespace = 'groupslog';
4173: $storehash{'group'} = $sec;
4174: } else {
4175: $storehash{'section'} = $sec;
4176: }
4177: &write_log('course',$namespace,\%storehash,$delflag,$username,
4178: $domain,$cnum,$cdom);
4179: if (($trole ne 'st') || ($sec ne '')) {
4180: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4181: }
4182: }
4183: return;
4184: }
4185:
1.1172.2.9 raeburn 4186: sub domainrolelog {
4187: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4188: if ($area =~ m{^/($match_domain)/$}) {
4189: my $cdom = $1;
4190: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4191: my $namespace = 'rolelog';
4192: my %storehash = (
4193: role => $trole,
4194: start => $tstart,
4195: end => $tend,
4196: context => $context,
4197: );
4198: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4199: $domain,$domconfiguser,$cdom);
4200: }
4201: return;
4202:
4203: }
4204:
4205: sub coauthorrolelog {
4206: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4207: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4208: my $audom = $1;
4209: my $auname = $2;
4210: my $namespace = 'rolelog';
4211: my %storehash = (
4212: role => $trole,
4213: start => $tstart,
4214: end => $tend,
4215: context => $context,
4216: );
4217: &write_log('author',$namespace,\%storehash,$delflag,$username,
4218: $domain,$auname,$audom);
4219: }
4220: return;
4221: }
4222:
1.351 www 4223: sub get_course_adv_roles {
1.948 raeburn 4224: my ($cid,$codes) = @_;
1.620 albertel 4225: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4226: my %coursehash=&coursedescription($cid);
1.988 raeburn 4227: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4228: my %nothide=();
1.800 albertel 4229: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4230: if ($user !~ /:/) {
4231: $nothide{join(':',split(/[\@]/,$user))}=1;
4232: } else {
4233: $nothide{$user}=1;
4234: }
1.470 www 4235: }
1.1172.2.23 raeburn 4236: my @possdoms = ($coursehash{'domain'});
4237: if ($coursehash{'checkforpriv'}) {
4238: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4239: }
1.351 www 4240: my %returnhash=();
4241: my %dumphash=
4242: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4243: my $now=time;
1.997 raeburn 4244: my %privileged;
1.1000 raeburn 4245: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4246: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4247: if (($tstart) && ($tstart<0)) { next; }
4248: if (($tend) && ($tend<$now)) { next; }
4249: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4250: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4251: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4252: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4253: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4254: if ($role eq 'cr') { next; }
1.948 raeburn 4255: if ($codes) {
4256: if ($section) { $role .= ':'.$section; }
4257: if ($returnhash{$role}) {
4258: $returnhash{$role}.=','.$username.':'.$domain;
4259: } else {
4260: $returnhash{$role}=$username.':'.$domain;
4261: }
1.351 www 4262: } else {
1.988 raeburn 4263: my $key=&plaintext($role,$crstype);
1.973 bisitz 4264: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4265: if ($returnhash{$key}) {
4266: $returnhash{$key}.=','.$username.':'.$domain;
4267: } else {
4268: $returnhash{$key}=$username.':'.$domain;
4269: }
1.351 www 4270: }
1.948 raeburn 4271: }
1.400 www 4272: return %returnhash;
4273: }
4274:
4275: sub get_my_roles {
1.937 raeburn 4276: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4277: unless (defined($uname)) { $uname=$env{'user.name'}; }
4278: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4279: my (%dumphash,%nothide);
1.1086 raeburn 4280: if ($context eq 'userroles') {
1.1166 raeburn 4281: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4282: } else {
1.1172.2.23 raeburn 4283: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4284: if ($hidepriv) {
4285: my %coursehash=&coursedescription($udom.'_'.$uname);
4286: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4287: if ($user !~ /:/) {
4288: $nothide{join(':',split(/[\@]/,$user))} = 1;
4289: } else {
4290: $nothide{$user} = 1;
4291: }
4292: }
4293: }
1.858 raeburn 4294: }
1.400 www 4295: my %returnhash=();
4296: my $now=time;
1.999 raeburn 4297: my %privileged;
1.800 albertel 4298: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4299: my ($role,$tend,$tstart);
4300: if ($context eq 'userroles') {
1.1149 raeburn 4301: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4302: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4303: } else {
4304: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4305: }
1.400 www 4306: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4307: my $status = 'active';
1.939 raeburn 4308: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4309: $status = 'previous';
4310: }
4311: if (($tstart) && ($now<$tstart)) {
4312: $status = 'future';
4313: }
4314: if (ref($types) eq 'ARRAY') {
4315: if (!grep(/^\Q$status\E$/,@{$types})) {
4316: next;
4317: }
4318: } else {
4319: if ($status ne 'active') {
4320: next;
4321: }
4322: }
1.867 raeburn 4323: my ($rolecode,$username,$domain,$section,$area);
4324: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4325: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4326: (undef,$domain,$username,$section) = split(/\//,$area);
4327: } else {
4328: ($role,$username,$domain,$section) = split(/\:/,$entry);
4329: }
1.832 raeburn 4330: if (ref($roledoms) eq 'ARRAY') {
4331: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4332: next;
4333: }
4334: }
4335: if (ref($roles) eq 'ARRAY') {
4336: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4337: if ($role =~ /^cr\//) {
4338: if (!grep(/^cr$/,@{$roles})) {
4339: next;
4340: }
1.1104 raeburn 4341: } elsif ($role =~ /^gr\//) {
4342: if (!grep(/^gr$/,@{$roles})) {
4343: next;
4344: }
1.922 raeburn 4345: } else {
4346: next;
4347: }
1.832 raeburn 4348: }
1.867 raeburn 4349: }
1.937 raeburn 4350: if ($hidepriv) {
1.1172.2.23 raeburn 4351: my @privroles = ('dc','su');
1.999 raeburn 4352: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4353: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4354: } else {
1.1172.2.23 raeburn 4355: my $possdoms = [$domain];
4356: if (ref($roledoms) eq 'ARRAY') {
4357: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4358: }
1.1172.2.23 raeburn 4359: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4360: if (!$nothide{$username.':'.$domain}) {
4361: next;
4362: }
4363: }
1.937 raeburn 4364: }
4365: }
1.933 raeburn 4366: if ($withsec) {
4367: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4368: $tstart.':'.$tend;
4369: } else {
4370: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4371: }
1.832 raeburn 4372: }
1.373 www 4373: return %returnhash;
1.399 www 4374: }
4375:
1.1172.2.89 raeburn 4376: sub get_all_adhocroles {
4377: my ($dom) = @_;
4378: my @roles_by_num = ();
4379: my %domdefaults = &get_domain_defaults($dom);
4380: my (%description,%access_in_dom,%access_info);
4381: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4382: my $count = 0;
4383: my %domcurrent = %{$domdefaults{'adhocroles'}};
4384: my %ordered;
4385: foreach my $role (sort(keys(%domcurrent))) {
4386: my ($order,$desc,$access_in_dom);
4387: if (ref($domcurrent{$role}) eq 'HASH') {
4388: $order = $domcurrent{$role}{'order'};
4389: $desc = $domcurrent{$role}{'desc'};
4390: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4391: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4392: }
4393: if ($order eq '') {
4394: $order = $count;
4395: }
4396: $ordered{$order} = $role;
4397: if ($desc ne '') {
4398: $description{$role} = $desc;
4399: } else {
4400: $description{$role}= $role;
4401: }
4402: $count++;
4403: }
4404: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4405: push(@roles_by_num,$ordered{$item});
4406: }
4407: }
4408: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4409: }
4410:
4411: sub get_my_adhocroles {
4412: my ($cid,$checkreg) = @_;
4413: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4414: if ($env{'request.course.id'} eq $cid) {
4415: $cdom = $env{'course.'.$cid.'.domain'};
4416: $cnum = $env{'course.'.$cid.'.num'};
4417: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4418: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4419: $cdom = $1;
4420: $cnum = $2;
4421: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4422: $cdom,$cnum);
4423: }
4424: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4425: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4426: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4427: if ($rosterhash{$user} ne '') {
4428: my $type = (split(/:/,$rosterhash{$user}))[5];
4429: return ([],{}) if ($type eq 'auto');
4430: }
4431: }
4432: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4433: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4434: my $then=$env{'user.login.time'};
4435: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4436: if (!$update) {
4437: $update = $then;
4438: }
4439: my @liveroles;
4440: foreach my $role ('dh','da') {
4441: if ($env{"user.role.$role./$cdom/"}) {
4442: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4443: my $limit = $update;
4444: if ($env{'request.role'} eq "$role./$cdom/") {
4445: $limit = $then;
4446: }
4447: my $activerole = 1;
4448: if ($tstart && $tstart>$limit) { $activerole = 0; }
4449: if ($tend && $tend <$limit) { $activerole = 0; }
4450: if ($activerole) {
4451: push(@liveroles,$role);
4452: }
4453: }
4454: }
4455: if (@liveroles) {
1.1172.2.89 raeburn 4456: if (&homeserver($cnum,$cdom) ne 'no_host') {
4457: my ($accessref,$accessinfo,%access_in_dom);
4458: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4459: if (ref($roles_by_num) eq 'ARRAY') {
4460: if (@{$roles_by_num}) {
4461: my %settings;
4462: if ($env{'request.course.id'} eq $cid) {
4463: foreach my $envkey (keys(%env)) {
4464: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4465: $settings{$1} = $env{$envkey};
4466: }
4467: }
4468: } else {
4469: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4470: }
4471: my %setincrs;
4472: if ($settings{'internal.adhocaccess'}) {
4473: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4474: }
4475: my @statuses;
4476: if ($env{'environment.inststatus'}) {
4477: @statuses = split(/,/,$env{'environment.inststatus'});
4478: }
4479: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4480: if (ref($accessref) eq 'HASH') {
4481: %access_in_dom = %{$accessref};
4482: }
4483: foreach my $role (@{$roles_by_num}) {
4484: my ($curraccess,@okstatus,@personnel);
4485: if ($setincrs{$role}) {
4486: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4487: if ($curraccess eq 'status') {
4488: @okstatus = split(/\&/,$rest);
4489: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4490: @personnel = split(/\&/,$rest);
4491: }
4492: } else {
4493: $curraccess = $access_in_dom{$role};
4494: if (ref($accessinfo) eq 'HASH') {
4495: if ($curraccess eq 'status') {
4496: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4497: @okstatus = @{$accessinfo->{$role}};
4498: }
4499: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4500: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4501: @personnel = @{$accessinfo->{$role}};
4502: }
4503: }
4504: }
4505: }
4506: if ($curraccess eq 'none') {
4507: next;
4508: } elsif ($curraccess eq 'all') {
4509: push(@possroles,$role);
1.1172.2.90 raeburn 4510: } elsif ($curraccess eq 'dh') {
4511: if (grep(/^dh$/,@liveroles)) {
4512: push(@possroles,$role);
4513: } else {
4514: next;
4515: }
4516: } elsif ($curraccess eq 'da') {
4517: if (grep(/^da$/,@liveroles)) {
4518: push(@possroles,$role);
4519: } else {
4520: next;
4521: }
1.1172.2.89 raeburn 4522: } elsif ($curraccess eq 'status') {
4523: if (@okstatus) {
4524: if (!@statuses) {
4525: if (grep(/^default$/,@okstatus)) {
4526: push(@possroles,$role);
4527: }
4528: } else {
4529: foreach my $status (@okstatus) {
4530: if (grep(/^\Q$status\E$/,@statuses)) {
4531: push(@possroles,$role);
4532: last;
4533: }
4534: }
4535: }
4536: }
4537: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4538: if (grep(/^\Q$user\E$/,@personnel)) {
4539: if ($curraccess eq 'exc') {
4540: push(@possroles,$role);
4541: }
4542: } elsif ($curraccess eq 'inc') {
4543: push(@possroles,$role);
4544: }
4545: }
4546: }
4547: }
4548: }
4549: }
4550: }
4551: }
4552: }
4553: unless (ref($description) eq 'HASH') {
4554: if (ref($roles_by_num) eq 'ARRAY') {
4555: my %desc;
4556: map { $desc{$_} = $_; } (@{$roles_by_num});
4557: $description = \%desc;
4558: } else {
4559: $description = {};
4560: }
4561: }
4562: return (\@possroles,$description);
4563: }
4564:
1.399 www 4565: # ----------------------------------------------------- Frontpage Announcements
4566: #
4567: #
4568:
4569: sub postannounce {
4570: my ($server,$text)=@_;
1.844 albertel 4571: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4572: unless ($text=~/\w/) { $text=''; }
4573: return &reply('setannounce:'.&escape($text),$server);
4574: }
4575:
4576: sub getannounce {
1.448 albertel 4577:
1.1172.2.93.4 7(raebur 4578:7): if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4579: my $announcement='';
1.800 albertel 4580: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4581: close($fh);
1.399 www 4582: if ($announcement=~/\w/) {
4583: return
4584: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4585: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4586: } else {
4587: return '';
4588: }
4589: } else {
4590: return '';
4591: }
1.351 www 4592: }
1.353 www 4593:
4594: # ---------------------------------------------------------- Course ID routines
4595: # Deal with domain's nohist_courseid.db files
4596: #
4597:
4598: sub courseidput {
1.921 raeburn 4599: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4600: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4601: my $outcome;
4602: if ($caller eq 'timeonly') {
4603: my $cids = '';
4604: foreach my $item (keys(%$storehash)) {
4605: $cids.=&escape($item).'&';
4606: }
4607: $cids=~s/\&$//;
4608: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4609: $coursehome);
4610: } else {
4611: my $items = '';
4612: foreach my $item (keys(%$storehash)) {
4613: $items.= &escape($item).'='.
4614: &freeze_escape($$storehash{$item}).'&';
4615: }
4616: $items=~s/\&$//;
4617: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4618: $coursehome);
1.918 raeburn 4619: }
4620: if ($outcome eq 'unknown_cmd') {
4621: my $what;
4622: foreach my $cid (keys(%$storehash)) {
4623: $what .= &escape($cid).'=';
1.921 raeburn 4624: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4625: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4626: }
4627: $what =~ s/\:$/&/;
4628: }
4629: $what =~ s/\&$//;
4630: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4631: } else {
4632: return $outcome;
4633: }
1.353 www 4634: }
4635:
4636: sub courseiddump {
1.921 raeburn 4637: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4638: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4639: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4640: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4641: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4642: my $as_hash = 1;
4643: my %returnhash;
4644: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4645: my %libserv = &all_library();
4646: foreach my $tryserver (keys(%libserv)) {
4647: if ( ( $hostidflag == 1
4648: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4649: || (!defined($hostidflag)) ) {
4650:
1.918 raeburn 4651: if (($domfilter eq '') ||
4652: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4653: my $rep;
4654: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4655: $rep = &LONCAPA::Lond::dump_course_id_handler(
4656: join(":", (&host_domain($tryserver), $sincefilter,
4657: &escape($descfilter), &escape($instcodefilter),
4658: &escape($ownerfilter), &escape($coursefilter),
4659: &escape($typefilter), &escape($regexp_ok),
4660: $as_hash, &escape($selfenrollonly),
4661: &escape($catfilter), $showhidden, $caller,
4662: &escape($cloner), &escape($cc_clone), $cloneonly,
4663: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4664: &escape($creationcontext),$domcloner,$hasuniquecode,
4665: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4666: } else {
4667: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4668: $sincefilter.':'.&escape($descfilter).':'.
4669: &escape($instcodefilter).':'.&escape($ownerfilter).
4670: ':'.&escape($coursefilter).':'.&escape($typefilter).
4671: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4672: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4673: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4674: &escape($cc_clone).':'.$cloneonly.':'.
4675: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4676: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4677: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4678: }
4679:
1.918 raeburn 4680: my @pairs=split(/\&/,$rep);
4681: foreach my $item (@pairs) {
4682: my ($key,$value)=split(/\=/,$item,2);
4683: $key = &unescape($key);
4684: next if ($key =~ /^error: 2 /);
4685: my $result = &thaw_unescape($value);
4686: if (ref($result) eq 'HASH') {
4687: $returnhash{$key}=$result;
4688: } else {
1.921 raeburn 4689: my @responses = split(/:/,$value);
4690: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4691: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4692: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4693: }
1.1008 raeburn 4694: }
1.353 www 4695: }
4696: }
4697: }
4698: }
4699: return %returnhash;
4700: }
4701:
1.1055 raeburn 4702: sub courselastaccess {
4703: my ($cdom,$cnum,$hostidref) = @_;
4704: my %returnhash;
4705: if ($cdom && $cnum) {
4706: my $chome = &homeserver($cnum,$cdom);
4707: if ($chome ne 'no_host') {
4708: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4709: &extract_lastaccess(\%returnhash,$rep);
4710: }
4711: } else {
4712: if (!$cdom) { $cdom=''; }
4713: my %libserv = &all_library();
4714: foreach my $tryserver (keys(%libserv)) {
4715: if (ref($hostidref) eq 'ARRAY') {
4716: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4717: }
4718: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4719: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4720: &extract_lastaccess(\%returnhash,$rep);
4721: }
4722: }
4723: }
4724: return %returnhash;
4725: }
4726:
4727: sub extract_lastaccess {
4728: my ($returnhash,$rep) = @_;
4729: if (ref($returnhash) eq 'HASH') {
4730: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4731: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4732: $rep eq '') {
4733: my @pairs=split(/\&/,$rep);
4734: foreach my $item (@pairs) {
4735: my ($key,$value)=split(/\=/,$item,2);
4736: $key = &unescape($key);
4737: next if ($key =~ /^error: 2 /);
4738: $returnhash->{$key} = &thaw_unescape($value);
4739: }
4740: }
4741: }
4742: return;
4743: }
4744:
1.658 raeburn 4745: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4746:
4747: sub dcmailput {
1.685 raeburn 4748: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4749: my $status = &Apache::lonnet::critical(
1.740 www 4750: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4751: &escape($message),$server);
1.662 raeburn 4752: return $status;
4753: }
4754:
1.658 raeburn 4755: sub dcmaildump {
4756: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4757: my %returnhash=();
1.846 albertel 4758:
4759: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4760: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4761: &escape($enddate).':';
4762: my @esc_senders=map { &escape($_)} @$senders;
4763: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4764: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4765: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4766: if (($key) && ($value)) {
4767: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4768: }
4769: }
4770: }
4771: return %returnhash;
4772: }
1.662 raeburn 4773: # ---------------------------------------------------------- Domain roles
4774:
4775: sub get_domain_roles {
4776: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4777: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4778: $startdate = '.';
4779: }
1.1018 raeburn 4780: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4781: $enddate = '.';
4782: }
1.922 raeburn 4783: my $rolelist;
4784: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4785: $rolelist = join('&',@{$roles});
1.922 raeburn 4786: }
1.662 raeburn 4787: my %personnel = ();
1.841 albertel 4788:
4789: my %servers = &get_servers($dom,'library');
4790: foreach my $tryserver (keys(%servers)) {
4791: %{$personnel{$tryserver}}=();
4792: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4793: &escape($startdate).':'.
4794: &escape($enddate).':'.
4795: &escape($rolelist), $tryserver))) {
4796: my ($key,$value) = split(/\=/,$line,2);
4797: if (($key) && ($value)) {
4798: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4799: }
4800: }
1.662 raeburn 4801: }
4802: return %personnel;
4803: }
1.658 raeburn 4804:
1.1172.2.89 raeburn 4805: sub get_active_domroles {
4806: my ($dom,$roles) = @_;
4807: return () unless (ref($roles) eq 'ARRAY');
4808: my $now = time;
4809: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4810: my %domroles;
4811: foreach my $server (keys(%dompersonnel)) {
4812: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4813: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4814: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4815: }
4816: }
4817: return %domroles;
4818: }
4819:
1.1057 www 4820: # ----------------------------------------------------------- Interval timing
1.149 www 4821:
1.1153 www 4822: {
4823: # Caches needed for speedup of navmaps
4824: # We don't want to cache this for very long at all (5 seconds at most)
4825: #
4826: # The user for whom we cache
4827: my $cachedkey='';
4828: # The cached times for this user
4829: my %cachedtimes=();
4830: # When this was last done
1.1172.2.66 raeburn 4831: my $cachedtime='';
1.1153 www 4832:
4833: sub load_all_first_access {
1.1172.2.93.4 1(raebur 4834:7): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4835: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4 1(raebur 4836:7): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4837:7): (!$ignorecache)) {
1.1154 raeburn 4838: return;
4839: }
4840: $cachedtime=time;
4841: $cachedkey=$uname.':'.$udom;
4842: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4843: }
4844:
1.504 albertel 4845: sub get_first_access {
1.1172.2.93.4 1(raebur 4846:7): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4847: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4848: if ($argsymb) { $symb=$argsymb; }
4849: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4850: if ($argmap) { $map = $argmap; }
1.926 albertel 4851: if ($type eq 'course') {
4852: $res='course';
4853: } elsif ($type eq 'map') {
1.588 albertel 4854: $res=&symbread($map);
4855: } else {
4856: $res=$symb;
4857: }
1.1172.2.93.4 1(raebur 4858:7): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4859: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4860: }
4861:
4862: sub set_first_access {
1.1162 raeburn 4863: my ($type,$interval)=@_;
1.790 albertel 4864: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4865: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4866: if ($type eq 'course') {
4867: $res='course';
4868: } elsif ($type eq 'map') {
1.588 albertel 4869: $res=&symbread($map);
4870: } else {
4871: $res=$symb;
4872: }
1.1153 www 4873: $cachedkey='';
1.1162 raeburn 4874: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4875: if (!$firstaccess) {
1.1162 raeburn 4876: my $start = time;
4877: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4878: $udom,$uname);
4879: if ($putres eq 'ok') {
4880: &put('timerinterval',{"$courseid\0$res"=>$interval},
4881: $udom,$uname);
4882: &appenv(
4883: {
4884: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4885: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4886: }
4887: );
4888: }
4889: return $putres;
1.505 albertel 4890: }
4891: return 'already_set';
1.504 albertel 4892: }
1.1153 www 4893: }
1.1172.2.32 raeburn 4894:
4895: sub checkout {
4896: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4897: my $now=time;
4898: my $lonhost=$perlvar{'lonHostID'};
4899: my $infostr=&escape(
4900: 'CHECKOUTTOKEN&'.
4901: $tuname.'&'.
4902: $tudom.'&'.
4903: $tcrsid.'&'.
4904: $symb.'&'.
4905: $now.'&'.$ENV{'REMOTE_ADDR'});
4906: my $token=&reply('tmpput:'.$infostr,$lonhost);
4907: if ($token=~/^error\:/) {
4908: &logthis("<font color=\"blue\">WARNING: ".
4909: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4910: "</font>");
4911: return '';
4912: }
4913:
4914: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4915: $token=~tr/a-z/A-Z/;
4916:
4917: my %infohash=('resource.0.outtoken' => $token,
4918: 'resource.0.checkouttime' => $now,
4919: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4920:
4921: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4922: return '';
4923: } else {
4924: &logthis("<font color=\"blue\">WARNING: ".
4925: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4926: "</font>");
4927: }
4928:
4929: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4930: &escape('Checkout '.$infostr.' - '.
4931: $token)) ne 'ok') {
4932: return '';
4933: } else {
4934: &logthis("<font color=\"blue\">WARNING: ".
4935: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4936: "</font>");
4937: }
4938: return $token;
4939: }
4940:
4941: # ------------------------------------------------------------ Check in an item
4942:
4943: sub checkin {
4944: my $token=shift;
4945: my $now=time;
4946: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4947: $lonhost=~tr/A-Z/a-z/;
4948: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4949: $dtoken=~s/\W/\_/g;
4950: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4951: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4952:
4953: unless (($tuname) && ($tudom)) {
4954: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4955: return '';
4956: }
4957:
4958: unless (&allowed('mgr',$tcrsid)) {
4959: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4960: $env{'user.name'}.' - '.$env{'user.domain'});
4961: return '';
4962: }
4963:
4964: my %infohash=('resource.0.intoken' => $token,
4965: 'resource.0.checkintime' => $now,
4966: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4967:
4968: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4969: return '';
4970: }
4971:
4972: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4973: &escape('Checkin - '.$token)) ne 'ok') {
4974: return '';
4975: }
4976:
4977: return ($symb,$tuname,$tudom,$tcrsid);
4978: }
4979:
1.110 www 4980: # --------------------------------------------- Set Expire Date for Spreadsheet
4981:
4982: sub expirespread {
4983: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4984: my $cid=$env{'request.course.id'};
1.110 www 4985: if ($cid) {
4986: my $now=time;
4987: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4988: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4989: $env{'course.'.$cid.'.num'}.
1.110 www 4990: ':nohist_expirationdates:'.
4991: &escape($key).'='.$now,
1.620 albertel 4992: $env{'course.'.$cid.'.home'})
1.110 www 4993: }
4994: return 'ok';
1.14 www 4995: }
4996:
1.109 www 4997: # ----------------------------------------------------- Devalidate Spreadsheets
4998:
4999: sub devalidate {
1.325 www 5000: my ($symb,$uname,$udom)=@_;
1.620 albertel 5001: my $cid=$env{'request.course.id'};
1.109 www 5002: if ($cid) {
1.391 matthew 5003: # delete the stored spreadsheets for
5004: # - the student level sheet of this user in course's homespace
5005: # - the assessment level sheet for this resource
5006: # for this user in user's homespace
1.553 albertel 5007: # - current conditional state info
1.325 www 5008: my $key=$uname.':'.$udom.':';
1.109 www 5009: my $status=
1.299 matthew 5010: &del('nohist_calculatedsheets',
1.391 matthew 5011: [$key.'studentcalc:'],
1.620 albertel 5012: $env{'course.'.$cid.'.domain'},
5013: $env{'course.'.$cid.'.num'})
1.133 albertel 5014: .' '.
5015: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5016: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5017: unless ($status eq 'ok ok') {
5018: &logthis('Could not devalidate spreadsheet '.
1.325 www 5019: $uname.' at '.$udom.' for '.
1.109 www 5020: $symb.': '.$status);
1.133 albertel 5021: }
1.553 albertel 5022: &delenv('user.state.'.$cid);
1.109 www 5023: }
5024: }
5025:
1.265 albertel 5026: sub get_scalar {
5027: my ($string,$end) = @_;
5028: my $value;
5029: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5030: $value = $1;
5031: } elsif ($$string =~ s/^([^&]*?)&//) {
5032: $value = $1;
5033: }
5034: return &unescape($value);
5035: }
5036:
5037: sub array2str {
5038: my (@array) = @_;
5039: my $result=&arrayref2str(\@array);
5040: $result=~s/^__ARRAY_REF__//;
5041: $result=~s/__END_ARRAY_REF__$//;
5042: return $result;
5043: }
5044:
1.204 albertel 5045: sub arrayref2str {
5046: my ($arrayref) = @_;
1.265 albertel 5047: my $result='__ARRAY_REF__';
1.204 albertel 5048: foreach my $elem (@$arrayref) {
1.265 albertel 5049: if(ref($elem) eq 'ARRAY') {
5050: $result.=&arrayref2str($elem).'&';
5051: } elsif(ref($elem) eq 'HASH') {
5052: $result.=&hashref2str($elem).'&';
5053: } elsif(ref($elem)) {
5054: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5055: } else {
5056: $result.=&escape($elem).'&';
5057: }
5058: }
5059: $result=~s/\&$//;
1.265 albertel 5060: $result .= '__END_ARRAY_REF__';
1.204 albertel 5061: return $result;
5062: }
5063:
1.168 albertel 5064: sub hash2str {
1.204 albertel 5065: my (%hash) = @_;
5066: my $result=&hashref2str(\%hash);
1.265 albertel 5067: $result=~s/^__HASH_REF__//;
5068: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5069: return $result;
5070: }
5071:
5072: sub hashref2str {
5073: my ($hashref)=@_;
1.265 albertel 5074: my $result='__HASH_REF__';
1.800 albertel 5075: foreach my $key (sort(keys(%$hashref))) {
5076: if (ref($key) eq 'ARRAY') {
5077: $result.=&arrayref2str($key).'=';
5078: } elsif (ref($key) eq 'HASH') {
5079: $result.=&hashref2str($key).'=';
5080: } elsif (ref($key)) {
1.265 albertel 5081: $result.='=';
1.800 albertel 5082: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5083: } else {
1.1132 raeburn 5084: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5085: }
5086:
1.800 albertel 5087: if(ref($hashref->{$key}) eq 'ARRAY') {
5088: $result.=&arrayref2str($hashref->{$key}).'&';
5089: } elsif(ref($hashref->{$key}) eq 'HASH') {
5090: $result.=&hashref2str($hashref->{$key}).'&';
5091: } elsif(ref($hashref->{$key})) {
1.265 albertel 5092: $result.='&';
1.800 albertel 5093: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5094: } else {
1.800 albertel 5095: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5096: }
5097: }
1.168 albertel 5098: $result=~s/\&$//;
1.265 albertel 5099: $result .= '__END_HASH_REF__';
1.168 albertel 5100: return $result;
5101: }
5102:
5103: sub str2hash {
1.265 albertel 5104: my ($string)=@_;
5105: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5106: return %$hash;
5107: }
5108:
5109: sub str2hashref {
1.168 albertel 5110: my ($string) = @_;
1.265 albertel 5111:
5112: my %hash;
5113:
5114: if($string !~ /^__HASH_REF__/) {
5115: if (! ($string eq '' || !defined($string))) {
5116: $hash{'error'}='Not hash reference';
5117: }
5118: return (\%hash, $string);
5119: }
5120:
5121: $string =~ s/^__HASH_REF__//;
5122:
5123: while($string !~ /^__END_HASH_REF__/) {
5124: #key
5125: my $key='';
5126: if($string =~ /^__HASH_REF__/) {
5127: ($key, $string)=&str2hashref($string);
5128: if(defined($key->{'error'})) {
5129: $hash{'error'}='Bad data';
5130: return (\%hash, $string);
5131: }
5132: } elsif($string =~ /^__ARRAY_REF__/) {
5133: ($key, $string)=&str2arrayref($string);
5134: if($key->[0] eq 'Array reference error') {
5135: $hash{'error'}='Bad data';
5136: return (\%hash, $string);
5137: }
5138: } else {
5139: $string =~ s/^(.*?)=//;
1.267 albertel 5140: $key=&unescape($1);
1.265 albertel 5141: }
5142: $string =~ s/^=//;
5143:
5144: #value
5145: my $value='';
5146: if($string =~ /^__HASH_REF__/) {
5147: ($value, $string)=&str2hashref($string);
5148: if(defined($value->{'error'})) {
5149: $hash{'error'}='Bad data';
5150: return (\%hash, $string);
5151: }
5152: } elsif($string =~ /^__ARRAY_REF__/) {
5153: ($value, $string)=&str2arrayref($string);
5154: if($value->[0] eq 'Array reference error') {
5155: $hash{'error'}='Bad data';
5156: return (\%hash, $string);
5157: }
5158: } else {
5159: $value=&get_scalar(\$string,'__END_HASH_REF__');
5160: }
5161: $string =~ s/^&//;
5162:
5163: $hash{$key}=$value;
1.204 albertel 5164: }
1.265 albertel 5165:
5166: $string =~ s/^__END_HASH_REF__//;
5167:
5168: return (\%hash, $string);
1.204 albertel 5169: }
5170:
5171: sub str2array {
1.265 albertel 5172: my ($string)=@_;
5173: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5174: return @$array;
5175: }
5176:
5177: sub str2arrayref {
1.204 albertel 5178: my ($string) = @_;
1.265 albertel 5179: my @array;
5180:
5181: if($string !~ /^__ARRAY_REF__/) {
5182: if (! ($string eq '' || !defined($string))) {
5183: $array[0]='Array reference error';
5184: }
5185: return (\@array, $string);
5186: }
5187:
5188: $string =~ s/^__ARRAY_REF__//;
5189:
5190: while($string !~ /^__END_ARRAY_REF__/) {
5191: my $value='';
5192: if($string =~ /^__HASH_REF__/) {
5193: ($value, $string)=&str2hashref($string);
5194: if(defined($value->{'error'})) {
5195: $array[0] ='Array reference error';
5196: return (\@array, $string);
5197: }
5198: } elsif($string =~ /^__ARRAY_REF__/) {
5199: ($value, $string)=&str2arrayref($string);
5200: if($value->[0] eq 'Array reference error') {
5201: $array[0] ='Array reference error';
5202: return (\@array, $string);
5203: }
5204: } else {
5205: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5206: }
5207: $string =~ s/^&//;
5208:
5209: push(@array, $value);
1.191 harris41 5210: }
1.265 albertel 5211:
5212: $string =~ s/^__END_ARRAY_REF__//;
5213:
5214: return (\@array, $string);
1.168 albertel 5215: }
5216:
1.167 albertel 5217: # -------------------------------------------------------------------Temp Store
5218:
1.168 albertel 5219: sub tmpreset {
5220: my ($symb,$namespace,$domain,$stuname) = @_;
5221: if (!$symb) {
5222: $symb=&symbread();
1.620 albertel 5223: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5224: }
5225: $symb=escape($symb);
5226:
1.620 albertel 5227: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5228: $namespace=~s/\//\_/g;
5229: $namespace=~s/\W//g;
5230:
1.620 albertel 5231: if (!$domain) { $domain=$env{'user.domain'}; }
5232: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5233: if ($domain eq 'public' && $stuname eq 'public') {
5234: $stuname=$ENV{'REMOTE_ADDR'};
5235: }
1.1117 foxr 5236: my $path=LONCAPA::tempdir();
1.168 albertel 5237: my %hash;
5238: if (tie(%hash,'GDBM_File',
5239: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5240: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5241: foreach my $key (keys(%hash)) {
1.180 albertel 5242: if ($key=~ /:$symb/) {
1.168 albertel 5243: delete($hash{$key});
5244: }
5245: }
5246: }
5247: }
5248:
1.167 albertel 5249: sub tmpstore {
1.168 albertel 5250: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5251:
5252: if (!$symb) {
5253: $symb=&symbread();
1.620 albertel 5254: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5255: }
5256: $symb=escape($symb);
5257:
5258: if (!$namespace) {
5259: # I don't think we would ever want to store this for a course.
5260: # it seems this will only be used if we don't have a course.
1.620 albertel 5261: #$namespace=$env{'request.course.id'};
1.168 albertel 5262: #if (!$namespace) {
1.620 albertel 5263: $namespace=$env{'request.state'};
1.168 albertel 5264: #}
5265: }
5266: $namespace=~s/\//\_/g;
5267: $namespace=~s/\W//g;
1.620 albertel 5268: if (!$domain) { $domain=$env{'user.domain'}; }
5269: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5270: if ($domain eq 'public' && $stuname eq 'public') {
5271: $stuname=$ENV{'REMOTE_ADDR'};
5272: }
1.168 albertel 5273: my $now=time;
5274: my %hash;
1.1117 foxr 5275: my $path=LONCAPA::tempdir();
1.168 albertel 5276: if (tie(%hash,'GDBM_File',
5277: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5278: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5279: $hash{"version:$symb"}++;
5280: my $version=$hash{"version:$symb"};
5281: my $allkeys='';
5282: foreach my $key (keys(%$storehash)) {
5283: $allkeys.=$key.':';
1.591 albertel 5284: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5285: }
5286: $hash{"$version:$symb:timestamp"}=$now;
5287: $allkeys.='timestamp';
5288: $hash{"$version:keys:$symb"}=$allkeys;
5289: if (untie(%hash)) {
5290: return 'ok';
5291: } else {
5292: return "error:$!";
5293: }
5294: } else {
5295: return "error:$!";
5296: }
5297: }
1.167 albertel 5298:
1.168 albertel 5299: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5300:
1.168 albertel 5301: sub tmprestore {
5302: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5303:
1.168 albertel 5304: if (!$symb) {
5305: $symb=&symbread();
1.620 albertel 5306: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5307: }
5308: $symb=escape($symb);
5309:
1.620 albertel 5310: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5311:
1.620 albertel 5312: if (!$domain) { $domain=$env{'user.domain'}; }
5313: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5314: if ($domain eq 'public' && $stuname eq 'public') {
5315: $stuname=$ENV{'REMOTE_ADDR'};
5316: }
1.168 albertel 5317: my %returnhash;
5318: $namespace=~s/\//\_/g;
5319: $namespace=~s/\W//g;
5320: my %hash;
1.1117 foxr 5321: my $path=LONCAPA::tempdir();
1.168 albertel 5322: if (tie(%hash,'GDBM_File',
5323: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5324: &GDBM_READER(),0640)) {
1.168 albertel 5325: my $version=$hash{"version:$symb"};
5326: $returnhash{'version'}=$version;
5327: my $scope;
5328: for ($scope=1;$scope<=$version;$scope++) {
5329: my $vkeys=$hash{"$scope:keys:$symb"};
5330: my @keys=split(/:/,$vkeys);
5331: my $key;
5332: $returnhash{"$scope:keys"}=$vkeys;
5333: foreach $key (@keys) {
1.591 albertel 5334: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5335: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5336: }
5337: }
1.168 albertel 5338: if (!(untie(%hash))) {
5339: return "error:$!";
5340: }
5341: } else {
5342: return "error:$!";
5343: }
5344: return %returnhash;
1.167 albertel 5345: }
5346:
1.9 www 5347: # ----------------------------------------------------------------------- Store
5348:
5349: sub store {
1.1172.2.64 raeburn 5350: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5351: my $home='';
5352:
1.168 albertel 5353: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5354:
1.213 www 5355: $symb=&symbclean($symb);
1.122 albertel 5356: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5357:
1.620 albertel 5358: if (!$domain) { $domain=$env{'user.domain'}; }
5359: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5360:
5361: &devalidate($symb,$stuname,$domain);
1.109 www 5362:
5363: $symb=escape($symb);
1.187 www 5364: if (!$namespace) {
1.620 albertel 5365: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5366: return '';
5367: }
5368: }
1.620 albertel 5369: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5370:
5371: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5372: $$storehash{'host'}=$perlvar{'lonHostID'};
5373:
1.12 www 5374: my $namevalue='';
1.800 albertel 5375: foreach my $key (keys(%$storehash)) {
5376: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5377: }
1.12 www 5378: $namevalue=~s/\&$//;
1.187 www 5379: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5380: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5381: }
5382:
1.47 www 5383: # -------------------------------------------------------------- Critical Store
5384:
5385: sub cstore {
1.1172.2.64 raeburn 5386: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5387: my $home='';
5388:
1.168 albertel 5389: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5390:
1.213 www 5391: $symb=&symbclean($symb);
1.122 albertel 5392: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5393:
1.620 albertel 5394: if (!$domain) { $domain=$env{'user.domain'}; }
5395: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5396:
5397: &devalidate($symb,$stuname,$domain);
1.109 www 5398:
5399: $symb=escape($symb);
1.187 www 5400: if (!$namespace) {
1.620 albertel 5401: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5402: return '';
5403: }
5404: }
1.620 albertel 5405: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5406:
5407: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5408: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5409:
1.47 www 5410: my $namevalue='';
1.800 albertel 5411: foreach my $key (keys(%$storehash)) {
5412: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5413: }
1.47 www 5414: $namevalue=~s/\&$//;
1.187 www 5415: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5416: return critical
1.1172.2.64 raeburn 5417: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5418: }
5419:
1.9 www 5420: # --------------------------------------------------------------------- Restore
5421:
5422: sub restore {
1.124 www 5423: my ($symb,$namespace,$domain,$stuname) = @_;
5424: my $home='';
5425:
1.168 albertel 5426: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5427:
1.122 albertel 5428: if (!$symb) {
1.1172.2.26 raeburn 5429: return if ($namespace eq 'courserequests');
5430: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5431: } else {
1.1172.2.26 raeburn 5432: unless ($namespace eq 'courserequests') {
5433: $symb=&escape(&symbclean($symb));
5434: }
1.122 albertel 5435: }
1.188 www 5436: if (!$namespace) {
1.620 albertel 5437: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5438: return '';
5439: }
5440: }
1.620 albertel 5441: if (!$domain) { $domain=$env{'user.domain'}; }
5442: if (!$stuname) { $stuname=$env{'user.name'}; }
5443: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5444: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5445:
1.12 www 5446: my %returnhash=();
1.800 albertel 5447: foreach my $line (split(/\&/,$answer)) {
5448: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5449: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5450: }
1.75 www 5451: my $version;
5452: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5453: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5454: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5455: }
1.75 www 5456: }
1.13 www 5457: return %returnhash;
1.34 www 5458: }
5459:
5460: # ---------------------------------------------------------- Course Description
1.1118 foxr 5461: #
5462: #
1.34 www 5463:
5464: sub coursedescription {
1.731 albertel 5465: my ($courseid,$args)=@_;
1.34 www 5466: $courseid=~s/^\///;
1.49 www 5467: $courseid=~s/\_/\//g;
1.34 www 5468: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5469: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5470: my $normalid=$cdomain.'_'.$cnum;
5471: # need to always cache even if we get errors otherwise we keep
5472: # trying and trying and trying to get the course description.
5473: my %envhash=();
5474: my %returnhash=();
1.731 albertel 5475:
5476: my $expiretime=600;
5477: if ($env{'request.course.id'} eq $normalid) {
5478: $expiretime=120;
5479: }
5480:
5481: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5482: if (!$args->{'freshen_cache'}
5483: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5484: foreach my $key (keys(%env)) {
5485: next if ($key !~ /^\Q$prefix\E(.*)/);
5486: my ($setting) = $1;
5487: $returnhash{$setting} = $env{$key};
5488: }
5489: return %returnhash;
5490: }
5491:
1.1118 foxr 5492: # get the data again
5493:
1.731 albertel 5494: if (!$args->{'one_time'}) {
5495: $envhash{'course.'.$normalid.'.last_cache'}=time;
5496: }
1.811 albertel 5497:
1.34 www 5498: if ($chome ne 'no_host') {
1.302 albertel 5499: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5500: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5501: my $username = $env{'user.name'}; # Defult username
5502: if(defined $args->{'user'}) {
5503: $username = $args->{'user'};
5504: }
1.129 albertel 5505: $returnhash{'home'}= $chome;
5506: $returnhash{'domain'} = $cdomain;
5507: $returnhash{'num'} = $cnum;
1.741 raeburn 5508: if (!defined($returnhash{'type'})) {
5509: $returnhash{'type'} = 'Course';
5510: }
1.130 albertel 5511: while (my ($name,$value) = each %returnhash) {
1.53 www 5512: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5513: }
1.270 www 5514: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5515: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5516: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5517: $envhash{'course.'.$normalid.'.home'}=$chome;
5518: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5519: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5520: }
5521: }
1.731 albertel 5522: if (!$args->{'one_time'}) {
1.949 raeburn 5523: &appenv(\%envhash);
1.731 albertel 5524: }
1.302 albertel 5525: return %returnhash;
1.461 www 5526: }
5527:
1.1080 raeburn 5528: sub update_released_required {
5529: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5530: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5531: $cid = $env{'request.course.id'};
5532: $cdom = $env{'course.'.$cid.'.domain'};
5533: $cnum = $env{'course.'.$cid.'.num'};
5534: $chome = $env{'course.'.$cid.'.home'};
5535: }
5536: if ($needsrelease) {
5537: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5538: my $needsupdate;
5539: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5540: $needsupdate = 1;
5541: } else {
5542: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5543: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5544: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5545: $needsupdate = 1;
5546: }
5547: }
5548: if ($needsupdate) {
5549: my %needshash = (
5550: 'internal.releaserequired' => $needsrelease,
5551: );
5552: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5553: if ($putresult eq 'ok') {
5554: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5555: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5556: if (ref($crsinfo{$cid}) eq 'HASH') {
5557: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5558: &courseidput($cdom,\%crsinfo,$chome,'notime');
5559: }
5560: }
5561: }
5562: }
5563: return;
5564: }
5565:
1.461 www 5566: # -------------------------------------------------See if a user is privileged
5567:
5568: sub privileged {
1.1172.2.23 raeburn 5569: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5570: my $now = time;
1.1172.2.23 raeburn 5571: my $roles;
5572: if (ref($possroles) eq 'ARRAY') {
5573: $roles = $possroles;
5574: } else {
5575: $roles = ['dc','su'];
5576: }
5577: if (ref($possdomains) eq 'ARRAY') {
5578: my %privileged = &privileged_by_domain($possdomains,$roles);
5579: foreach my $dom (@{$possdomains}) {
5580: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5581: (ref($privileged{$dom}) eq 'HASH')) {
5582: foreach my $role (@{$roles}) {
5583: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5584: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5585: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5586: return 1 unless (($end && $end < $now) ||
5587: ($start && $start > $now));
5588: }
5589: }
5590: }
5591: }
5592: }
5593: } else {
5594: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5595: my $now = time;
1.1170 droeschl 5596:
1.1172.2.58 raeburn 5597: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5598: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5599: if (grep(/^\Q$trole\E$/,@{$roles})) {
5600: return 1 unless ($tend && $tend < $now)
5601: or ($tstart && $tstart > $now);
1.1170 droeschl 5602: }
1.1172.2.23 raeburn 5603: }
5604: }
1.461 www 5605: return 0;
1.9 www 5606: }
1.1 albertel 5607:
1.1172.2.23 raeburn 5608: sub privileged_by_domain {
5609: my ($domains,$roles) = @_;
5610: my %privileged = ();
5611: my $cachetime = 60*60*24;
5612: my $now = time;
5613: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5614: return %privileged;
5615: }
5616: foreach my $dom (@{$domains}) {
5617: next if (ref($privileged{$dom}) eq 'HASH');
5618: my $needroles;
5619: foreach my $role (@{$roles}) {
5620: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5621: if (defined($cached)) {
5622: if (ref($result) eq 'HASH') {
5623: $privileged{$dom}{$role} = $result;
5624: }
5625: } else {
5626: $needroles = 1;
5627: }
5628: }
5629: if ($needroles) {
5630: my %dompersonnel = &get_domain_roles($dom,$roles);
5631: $privileged{$dom} = {};
5632: foreach my $server (keys(%dompersonnel)) {
5633: if (ref($dompersonnel{$server}) eq 'HASH') {
5634: foreach my $item (keys(%{$dompersonnel{$server}})) {
5635: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5636: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5637: next if ($end && $end < $now);
5638: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5639: $dompersonnel{$server}{$item};
5640: }
5641: }
5642: }
5643: if (ref($privileged{$dom}) eq 'HASH') {
5644: foreach my $role (@{$roles}) {
5645: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5646: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5647: } else {
5648: my %hash = ();
5649: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5650: }
5651: }
5652: }
5653: }
5654: }
5655: return %privileged;
5656: }
5657:
1.103 harris41 5658: # -------------------------------------------------------- Get user privileges
1.11 www 5659:
5660: sub rolesinit {
1.1169 droeschl 5661: my ($domain, $username) = @_;
5662: my %userroles = ('user.login.time' => time);
5663: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5664:
5665: # firstaccess and timerinterval are related to timed maps/resources.
5666: # also, blocking can be triggered by an activating timer
5667: # it's saved in the user's %env.
5668: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5669: my %timerinterval = &dump('timerinterval', $domain, $username);
5670: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5671: %timerintchk, %timerintenv);
5672:
1.1162 raeburn 5673: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5674: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5675: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5676: }
1.1169 droeschl 5677:
1.1162 raeburn 5678: foreach my $key (keys(%timerinterval)) {
5679: my ($cid,$rest) = split(/\0/,$key);
5680: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5681: }
1.1169 droeschl 5682:
1.11 www 5683: my %allroles=();
1.1162 raeburn 5684: my %allgroups=();
1.11 www 5685:
1.1172.2.58 raeburn 5686: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5687: my $role = $rolesdump{$area};
5688: $area =~ s/\_\w\w$//;
5689:
5690: my ($trole, $tend, $tstart, $group_privs);
5691:
5692: if ($role =~ /^cr/) {
5693: # Custom role, defined by a user
5694: # e.g., user.role.cr/msu/smith/mynewrole
5695: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5696: $trole = $1;
5697: ($tend, $tstart) = split('_', $2);
5698: } else {
5699: $trole = $role;
5700: }
5701: } elsif ($role =~ m|^gr/|) {
5702: # Role of member in a group, defined within a course/community
5703: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5704: ($trole, $tend, $tstart) = split(/_/, $role);
5705: next if $tstart eq '-1';
5706: ($trole, $group_privs) = split(/\//, $trole);
5707: $group_privs = &unescape($group_privs);
5708: } else {
5709: # Just a normal role, defined in roles.tab
5710: ($trole, $tend, $tstart) = split(/_/,$role);
5711: }
5712:
5713: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5714: $username);
5715: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5716:
5717: # role expired or not available yet?
5718: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5719: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5720:
5721: next if $area eq '' or $trole eq '';
5722:
5723: my $spec = "$trole.$area";
5724: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5725:
5726: if ($trole =~ /^cr\//) {
5727: # Custom role, defined by a user
5728: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5729: } elsif ($trole eq 'gr') {
5730: # Role of a member in a group, defined within a course/community
5731: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5732: next;
5733: } else {
5734: # Normal role, defined in roles.tab
5735: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5736: }
5737:
5738: my $cid = $tdomain.'_'.$trest;
5739: unless ($firstaccchk{$cid}) {
5740: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5741: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5742: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5743: $coursetimerstarts{$cid}{$item};
5744: }
5745: }
5746: $firstaccchk{$cid} = 1;
5747: }
5748: unless ($timerintchk{$cid}) {
5749: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5750: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5751: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5752: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5753: }
1.12 www 5754: }
1.1169 droeschl 5755: $timerintchk{$cid} = 1;
1.191 harris41 5756: }
1.11 www 5757: }
1.1169 droeschl 5758:
1.1172.2.91 raeburn 5759: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5760: \%allroles, \%allgroups);
1.1169 droeschl 5761: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 5762: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5763:
1.1162 raeburn 5764: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5765: }
5766:
1.567 raeburn 5767: sub set_arearole {
1.1172.2.19 raeburn 5768: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5769: unless ($nolog) {
1.567 raeburn 5770: # log the associated role with the area
1.1172.2.19 raeburn 5771: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5772: }
1.743 albertel 5773: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5774: }
5775:
5776: sub custom_roleprivs {
5777: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5778: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5779: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5780: if (&hostname($homsvr) ne '') {
1.567 raeburn 5781: my ($rdummy,$roledef)=
5782: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5783: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5784: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5785: if (defined($syspriv)) {
1.1043 raeburn 5786: if ($trest =~ /^$match_community$/) {
5787: $syspriv =~ s/bre\&S//;
5788: }
1.567 raeburn 5789: $$allroles{'cm./'}.=':'.$syspriv;
5790: $$allroles{$spec.'./'}.=':'.$syspriv;
5791: }
5792: if ($tdomain ne '') {
5793: if (defined($dompriv)) {
5794: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5795: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5796: }
5797: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 5798: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5799: my $rolename = $1;
5800: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5801: }
1.567 raeburn 5802: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5803: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5804: }
5805: }
5806: }
5807: }
5808: }
5809:
1.1172.2.89 raeburn 5810: sub course_adhocrole_privs {
5811: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5812: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5813: if ($overrides{"internal.adhocpriv.$rolename"}) {
5814: my (%currprivs,%storeprivs);
5815: foreach my $item (split(/:/,$coursepriv)) {
5816: my ($priv,$restrict) = split(/\&/,$item);
5817: $currprivs{$priv} = $restrict;
5818: }
5819: my (%possadd,%possremove,%full);
5820: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5821: my ($priv,$restrict)=split(/\&/,$item);
5822: $full{$priv} = $restrict;
5823: }
5824: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5825: next if ($item eq '');
5826: my ($rule,$rest) = split(/=/,$item);
5827: next unless (($rule eq 'off') || ($rule eq 'on'));
5828: foreach my $priv (split(/:/,$rest)) {
5829: if ($priv ne '') {
5830: if ($rule eq 'off') {
5831: $possremove{$priv} = 1;
5832: } else {
5833: $possadd{$priv} = 1;
5834: }
5835: }
5836: }
5837: }
5838: foreach my $priv (sort(keys(%full))) {
5839: if (exists($currprivs{$priv})) {
5840: unless (exists($possremove{$priv})) {
5841: $storeprivs{$priv} = $currprivs{$priv};
5842: }
5843: } elsif (exists($possadd{$priv})) {
5844: $storeprivs{$priv} = $full{$priv};
5845: }
5846: }
5847: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5848: }
5849: return $coursepriv;
5850: }
5851:
1.678 raeburn 5852: sub group_roleprivs {
5853: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5854: my $access = 1;
5855: my $now = time;
5856: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5857: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5858: if ($access) {
1.811 albertel 5859: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5860: $$allgroups{$course}{$group} .=':'.$group_privs;
5861: }
5862: }
1.567 raeburn 5863:
5864: sub standard_roleprivs {
5865: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5866: if (defined($pr{$trole.':s'})) {
5867: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5868: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5869: }
5870: if ($tdomain ne '') {
5871: if (defined($pr{$trole.':d'})) {
5872: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5873: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5874: }
5875: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5876: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5877: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5878: }
5879: }
5880: }
5881:
5882: sub set_userprivs {
1.1064 raeburn 5883: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5884: my $author=0;
5885: my $adv=0;
1.1172.2.91 raeburn 5886: my $rar=0;
1.678 raeburn 5887: my %grouproles = ();
5888: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5889: my @groupkeys;
1.1000 raeburn 5890: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5891: push(@groupkeys,$role);
5892: }
5893: if (ref($groups_roles) eq 'HASH') {
5894: foreach my $key (keys(%{$groups_roles})) {
5895: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5896: push(@groupkeys,$key);
5897: }
5898: }
5899: }
5900: if (@groupkeys > 0) {
5901: foreach my $role (@groupkeys) {
5902: my ($trole,$area,$sec,$extendedarea);
5903: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5904: $trole = $1;
5905: $area = $2;
5906: $sec = $3;
5907: $extendedarea = $area.$sec;
5908: if (exists($$allgroups{$area})) {
5909: foreach my $group (keys(%{$$allgroups{$area}})) {
5910: my $spec = $trole.'.'.$extendedarea;
5911: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5912: $$allgroups{$area}{$group};
1.1064 raeburn 5913: }
1.678 raeburn 5914: }
5915: }
5916: }
5917: }
5918: }
1.800 albertel 5919: foreach my $group (keys(%grouproles)) {
5920: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5921: }
1.800 albertel 5922: foreach my $role (keys(%{$allroles})) {
5923: my %thesepriv;
1.941 raeburn 5924: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5925: foreach my $item (split(/:/,$$allroles{$role})) {
5926: if ($item ne '') {
5927: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5928: if ($restrictions eq '') {
5929: $thesepriv{$privilege}='F';
5930: } elsif ($thesepriv{$privilege} ne 'F') {
5931: $thesepriv{$privilege}.=$restrictions;
5932: }
5933: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 5934: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5935: }
5936: }
5937: my $thesestr='';
1.1104 raeburn 5938: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5939: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5940: }
5941: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5942: }
1.1172.2.91 raeburn 5943: return ($author,$adv,$rar);
1.567 raeburn 5944: }
5945:
1.994 raeburn 5946: sub role_status {
1.1104 raeburn 5947: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5948: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5949: my ($one,$two) = split(m{\./},$rolekey,2);
5950: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5951: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5952: $$where = '/'.$two;
1.994 raeburn 5953: $$trolecode=$$role.'.'.$$where;
5954: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5955: $$tstatus='is';
1.1104 raeburn 5956: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5957: $$tstatus='future';
1.1034 raeburn 5958: if ($$tstart<$now) {
5959: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5960: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5961: my (%allroles,%allgroups,$group_privs,
5962: %groups_roles,@rolecodes);
1.1002 raeburn 5963: my %userroles = (
5964: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5965: );
1.1064 raeburn 5966: @rolecodes = ('cm');
1.1002 raeburn 5967: my $spec=$$role.'.'.$$where;
5968: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5969: if ($$role =~ /^cr\//) {
5970: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5971: push(@rolecodes,'cr');
1.1002 raeburn 5972: } elsif ($$role eq 'gr') {
1.1064 raeburn 5973: push(@rolecodes,$$role);
1.1002 raeburn 5974: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5975: $env{'user.name'});
1.1064 raeburn 5976: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5977: (undef,my $group_privs) = split(/\//,$trole);
5978: $group_privs = &unescape($group_privs);
5979: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5980: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 5981: &get_groups_roles($tdomain,$trest,
5982: \%course_roles,\@rolecodes,
5983: \%groups_roles);
1.1002 raeburn 5984: } else {
1.1064 raeburn 5985: push(@rolecodes,$$role);
1.1002 raeburn 5986: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5987: }
1.1172.2.91 raeburn 5988: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
5989: \%groups_roles);
1.1064 raeburn 5990: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 5991: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 5992: }
5993: }
1.1034 raeburn 5994: $$tstatus = 'is';
1.1002 raeburn 5995: }
1.994 raeburn 5996: }
5997: if ($$tend) {
1.1104 raeburn 5998: if ($$tend<$update) {
1.994 raeburn 5999: $$tstatus='expired';
6000: } elsif ($$tend<$now) {
6001: $$tstatus='will_not';
6002: }
6003: }
6004: }
6005: }
6006: }
6007:
1.1104 raeburn 6008: sub get_groups_roles {
6009: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6010: return unless((ref($cdom_courseroles) eq 'HASH') &&
6011: (ref($rolecodes) eq 'ARRAY') &&
6012: (ref($groups_roles) eq 'HASH'));
6013: if (keys(%{$cdom_courseroles}) > 0) {
6014: my ($cnum) = ($rest =~ /^($match_courseid)/);
6015: if ($cdom ne '' && $cnum ne '') {
6016: foreach my $key (keys(%{$cdom_courseroles})) {
6017: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6018: my $crsrole = $1;
6019: my $crssec = $2;
6020: if ($crsrole =~ /^cr/) {
6021: unless (grep(/^cr$/,@{$rolecodes})) {
6022: push(@{$rolecodes},'cr');
6023: }
6024: } else {
6025: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6026: push(@{$rolecodes},$crsrole);
6027: }
6028: }
6029: my $rolekey = "$crsrole./$cdom/$cnum";
6030: if ($crssec ne '') {
6031: $rolekey .= "/$crssec";
6032: }
6033: $rolekey .= './';
6034: $groups_roles->{$rolekey} = $rolecodes;
6035: }
6036: }
6037: }
6038: }
6039: return;
6040: }
6041:
6042: sub delete_env_groupprivs {
6043: my ($where,$courseroles,$possroles) = @_;
6044: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6045: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6046: unless (ref($courseroles->{$udom}) eq 'HASH') {
6047: %{$courseroles->{$udom}} =
6048: &get_my_roles('','','userroles',['active'],
6049: $possroles,[$udom],1);
6050: }
6051: if (ref($courseroles->{$udom}) eq 'HASH') {
6052: foreach my $item (keys(%{$courseroles->{$udom}})) {
6053: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6054: my $area = '/'.$cdom.'/'.$cnum;
6055: my $privkey = "user.priv.$crsrole.$area";
6056: if ($crssec ne '') {
6057: $privkey .= '/'.$crssec;
6058: }
6059: $privkey .= ".$area/$group";
6060: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6061: }
6062: }
6063: return;
6064: }
6065:
1.994 raeburn 6066: sub check_adhoc_privs {
1.1172.2.86 raeburn 6067: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6068: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6069: if ($sec) {
6070: $cckey .= '/'.$sec;
6071: }
1.1172.2.9 raeburn 6072: my $setprivs;
1.994 raeburn 6073: if ($env{$cckey}) {
6074: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6075: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6076: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6077: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6078: $setprivs = 1;
1.994 raeburn 6079: }
6080: } else {
1.1172.2.87 raeburn 6081: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6082: $setprivs = 1;
1.994 raeburn 6083: }
1.1172.2.9 raeburn 6084: return $setprivs;
1.994 raeburn 6085: }
6086:
6087: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6088: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6089: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6090: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6091: if ($sec ne '') {
6092: $area .= '/'.$sec;
6093: }
1.994 raeburn 6094: my $spec = $role.'.'.$area;
6095: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6096: $env{'user.name'},1);
1.1172.2.84 raeburn 6097: my %rolehash = ();
1.1172.2.89 raeburn 6098: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6099: my $rolename = $1;
1.1172.2.84 raeburn 6100: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6101: my %domdef = &get_domain_defaults($dcdom);
6102: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6103: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6104: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6105: }
6106: }
1.1172.2.84 raeburn 6107: } else {
6108: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6109: }
1.1172.2.91 raeburn 6110: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6111: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6112: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6113: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6114: &appenv( {'request.role' => $spec,
6115: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6116: 'request.course.sec' => $sec,
1.1088 raeburn 6117: }
6118: );
6119: my $tadv=0;
6120: if (&allowed('adv') eq 'F') { $tadv=1; }
6121: &appenv({'request.role.adv' => $tadv});
6122: }
1.994 raeburn 6123: }
6124:
1.12 www 6125: # --------------------------------------------------------------- get interface
6126:
6127: sub get {
1.131 albertel 6128: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6129: my $items='';
1.800 albertel 6130: foreach my $item (@$storearr) {
6131: $items.=&escape($item).'&';
1.191 harris41 6132: }
1.12 www 6133: $items=~s/\&$//;
1.620 albertel 6134: if (!$udomain) { $udomain=$env{'user.domain'}; }
6135: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6136: my $uhome=&homeserver($uname,$udomain);
6137:
1.133 albertel 6138: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6139: my @pairs=split(/\&/,$rep);
1.273 albertel 6140: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6141: return @pairs;
6142: }
1.15 www 6143: my %returnhash=();
1.42 www 6144: my $i=0;
1.800 albertel 6145: foreach my $item (@$storearr) {
6146: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6147: $i++;
1.191 harris41 6148: }
1.15 www 6149: return %returnhash;
1.27 www 6150: }
6151:
6152: # --------------------------------------------------------------- del interface
6153:
6154: sub del {
1.133 albertel 6155: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6156: my $items='';
1.800 albertel 6157: foreach my $item (@$storearr) {
6158: $items.=&escape($item).'&';
1.191 harris41 6159: }
1.984 neumanie 6160:
1.27 www 6161: $items=~s/\&$//;
1.620 albertel 6162: if (!$udomain) { $udomain=$env{'user.domain'}; }
6163: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6164: my $uhome=&homeserver($uname,$udomain);
6165: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6166: }
6167:
6168: # -------------------------------------------------------------- dump interface
6169:
1.1172.2.22 raeburn 6170: sub unserialize {
6171: my ($rep, $escapedkeys) = @_;
6172:
6173: return {} if $rep =~ /^error/;
6174:
6175: my %returnhash=();
6176: foreach my $item (split(/\&/,$rep)) {
6177: my ($key, $value) = split(/=/, $item, 2);
6178: $key = unescape($key) unless $escapedkeys;
6179: next if $key =~ /^error: 2 /;
6180: $returnhash{$key} = &thaw_unescape($value);
6181: }
6182: return \%returnhash;
6183: }
6184:
6185: # see Lond::dump_with_regexp
6186: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6187: sub dump {
1.1172.2.22 raeburn 6188: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6189: if (!$udomain) { $udomain=$env{'user.domain'}; }
6190: if (!$uname) { $uname=$env{'user.name'}; }
6191: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6192:
1.1172.2.55 raeburn 6193: if ($regexp) {
6194: $regexp=&escape($regexp);
6195: } else {
6196: $regexp='.';
6197: }
1.1172.2.22 raeburn 6198: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6199: # user is hosted on this machine
1.1172.2.55 raeburn 6200: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6201: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6202: return %{&unserialize($reply, $escapedkeys)};
6203: }
1.1166 raeburn 6204: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6205: my @pairs=split(/\&/,$rep);
6206: my %returnhash=();
1.1098 foxr 6207: if (!($rep =~ /^error/ )) {
6208: foreach my $item (@pairs) {
6209: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6210: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6211: next if ($key =~ /^error: 2 /);
6212: $returnhash{$key}=&thaw_unescape($value);
6213: }
1.755 albertel 6214: }
6215: return %returnhash;
1.407 www 6216: }
6217:
1.1098 foxr 6218:
1.717 albertel 6219: # --------------------------------------------------------- dumpstore interface
6220:
6221: sub dumpstore {
6222: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6223: # same as dump but keys must be escaped. They may contain colon separated
6224: # lists of values that may themself contain colons (e.g. symbs).
6225: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6226: }
6227:
1.407 www 6228: # -------------------------------------------------------------- keys interface
6229:
6230: sub getkeys {
6231: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6232: if (!$udomain) { $udomain=$env{'user.domain'}; }
6233: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6234: my $uhome=&homeserver($uname,$udomain);
6235: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6236: my @keyarray=();
1.800 albertel 6237: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6238: next if ($key =~ /^error: 2 /);
1.800 albertel 6239: push(@keyarray,&unescape($key));
1.407 www 6240: }
6241: return @keyarray;
1.318 matthew 6242: }
6243:
1.319 matthew 6244: # --------------------------------------------------------------- currentdump
6245: sub currentdump {
1.328 matthew 6246: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6247: $courseid = $env{'request.course.id'} if (! defined($courseid));
6248: $sdom = $env{'user.domain'} if (! defined($sdom));
6249: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6250: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6251: my $rep;
6252:
6253: if (grep { $_ eq $uhome } current_machine_ids()) {
6254: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6255: $courseid)));
6256: } else {
6257: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6258: }
6259:
1.318 matthew 6260: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6261: #
1.318 matthew 6262: my %returnhash=();
1.319 matthew 6263: #
1.1172.2.93.4 2(raebur 6264:7): if ($rep eq 'unknown_cmd') {
1.319 matthew 6265: # an old lond will not know currentdump
6266: # Do a dump and make it look like a currentdump
1.822 albertel 6267: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6268: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6269: my %hash = @tmp;
6270: @tmp=();
1.424 matthew 6271: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6272: } else {
6273: my @pairs=split(/\&/,$rep);
1.800 albertel 6274: foreach my $pair (@pairs) {
6275: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6276: my ($symb,$param) = split(/:/,$key);
6277: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6278: &thaw_unescape($value);
1.319 matthew 6279: }
1.191 harris41 6280: }
1.12 www 6281: return %returnhash;
1.424 matthew 6282: }
6283:
6284: sub convert_dump_to_currentdump{
6285: my %hash = %{shift()};
6286: my %returnhash;
6287: # Code ripped from lond, essentially. The only difference
6288: # here is the unescaping done by lonnet::dump(). Conceivably
6289: # we might run in to problems with parameter names =~ /^v\./
6290: while (my ($key,$value) = each(%hash)) {
6291: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6292: $symb = &unescape($symb);
6293: $param = &unescape($param);
1.424 matthew 6294: next if ($v eq 'version' || $symb eq 'keys');
6295: next if (exists($returnhash{$symb}) &&
6296: exists($returnhash{$symb}->{$param}) &&
6297: $returnhash{$symb}->{'v.'.$param} > $v);
6298: $returnhash{$symb}->{$param}=$value;
6299: $returnhash{$symb}->{'v.'.$param}=$v;
6300: }
6301: #
6302: # Remove all of the keys in the hashes which keep track of
6303: # the version of the parameter.
6304: while (my ($symb,$param_hash) = each(%returnhash)) {
6305: # use a foreach because we are going to delete from the hash.
6306: foreach my $key (keys(%$param_hash)) {
6307: delete($param_hash->{$key}) if ($key =~ /^v\./);
6308: }
6309: }
6310: return \%returnhash;
1.12 www 6311: }
6312:
1.627 albertel 6313: # ------------------------------------------------------ critical inc interface
6314:
6315: sub cinc {
6316: return &inc(@_,'critical');
6317: }
6318:
1.449 matthew 6319: # --------------------------------------------------------------- inc interface
6320:
6321: sub inc {
1.627 albertel 6322: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6323: if (!$udomain) { $udomain=$env{'user.domain'}; }
6324: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6325: my $uhome=&homeserver($uname,$udomain);
6326: my $items='';
6327: if (! ref($store)) {
6328: # got a single value, so use that instead
6329: $items = &escape($store).'=&';
6330: } elsif (ref($store) eq 'SCALAR') {
6331: $items = &escape($$store).'=&';
6332: } elsif (ref($store) eq 'ARRAY') {
6333: $items = join('=&',map {&escape($_);} @{$store});
6334: } elsif (ref($store) eq 'HASH') {
6335: while (my($key,$value) = each(%{$store})) {
6336: $items.= &escape($key).'='.&escape($value).'&';
6337: }
6338: }
6339: $items=~s/\&$//;
1.627 albertel 6340: if ($critical) {
6341: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6342: } else {
6343: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6344: }
1.449 matthew 6345: }
6346:
1.12 www 6347: # --------------------------------------------------------------- put interface
6348:
6349: sub put {
1.134 albertel 6350: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6351: if (!$udomain) { $udomain=$env{'user.domain'}; }
6352: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6353: my $uhome=&homeserver($uname,$udomain);
1.12 www 6354: my $items='';
1.800 albertel 6355: foreach my $item (keys(%$storehash)) {
6356: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6357: }
1.12 www 6358: $items=~s/\&$//;
1.134 albertel 6359: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6360: }
6361:
1.631 albertel 6362: # ------------------------------------------------------------ newput interface
6363:
6364: sub newput {
6365: my ($namespace,$storehash,$udomain,$uname)=@_;
6366: if (!$udomain) { $udomain=$env{'user.domain'}; }
6367: if (!$uname) { $uname=$env{'user.name'}; }
6368: my $uhome=&homeserver($uname,$udomain);
6369: my $items='';
6370: foreach my $key (keys(%$storehash)) {
6371: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6372: }
6373: $items=~s/\&$//;
6374: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6375: }
6376:
6377: # --------------------------------------------------------- putstore interface
6378:
1.524 raeburn 6379: sub putstore {
1.1172.2.59 raeburn 6380: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6381: if (!$udomain) { $udomain=$env{'user.domain'}; }
6382: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6383: my $uhome=&homeserver($uname,$udomain);
6384: my $items='';
1.715 albertel 6385: foreach my $key (keys(%$storehash)) {
6386: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6387: }
1.715 albertel 6388: $items=~s/\&$//;
1.716 albertel 6389: my $esc_symb=&escape($symb);
6390: my $esc_v=&escape($version);
1.715 albertel 6391: my $reply =
1.716 albertel 6392: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6393: $uhome);
1.1172.2.59 raeburn 6394: if (($tolog) && ($reply eq 'ok')) {
6395: my $namevalue='';
6396: foreach my $key (keys(%{$storehash})) {
6397: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6398: }
6399: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6400: '&host='.&escape($perlvar{'lonHostID'}).
6401: '&version='.$esc_v.
6402: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6403: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6404: }
1.715 albertel 6405: if ($reply eq 'unknown_cmd') {
1.716 albertel 6406: # gfall back to way things use to be done
1.715 albertel 6407: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6408: $uname);
1.524 raeburn 6409: }
1.715 albertel 6410: return $reply;
6411: }
6412:
6413: sub old_putstore {
1.716 albertel 6414: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6415: if (!$udomain) { $udomain=$env{'user.domain'}; }
6416: if (!$uname) { $uname=$env{'user.name'}; }
6417: my $uhome=&homeserver($uname,$udomain);
6418: my %newstorehash;
1.800 albertel 6419: foreach my $item (keys(%$storehash)) {
6420: my $key = $version.':'.&escape($symb).':'.$item;
6421: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6422: }
6423: my $items='';
6424: my %allitems = ();
1.800 albertel 6425: foreach my $item (keys(%newstorehash)) {
6426: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6427: my $key = $1.':keys:'.$2;
6428: $allitems{$key} .= $3.':';
6429: }
1.800 albertel 6430: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6431: }
1.800 albertel 6432: foreach my $item (keys(%allitems)) {
6433: $allitems{$item} =~ s/\:$//;
6434: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6435: }
6436: $items=~s/\&$//;
6437: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6438: }
6439:
1.47 www 6440: # ------------------------------------------------------ critical put interface
6441:
6442: sub cput {
1.134 albertel 6443: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6444: if (!$udomain) { $udomain=$env{'user.domain'}; }
6445: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6446: my $uhome=&homeserver($uname,$udomain);
1.47 www 6447: my $items='';
1.800 albertel 6448: foreach my $item (keys(%$storehash)) {
6449: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6450: }
1.47 www 6451: $items=~s/\&$//;
1.134 albertel 6452: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6453: }
6454:
6455: # -------------------------------------------------------------- eget interface
6456:
6457: sub eget {
1.133 albertel 6458: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6459: my $items='';
1.800 albertel 6460: foreach my $item (@$storearr) {
6461: $items.=&escape($item).'&';
1.191 harris41 6462: }
1.12 www 6463: $items=~s/\&$//;
1.620 albertel 6464: if (!$udomain) { $udomain=$env{'user.domain'}; }
6465: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6466: my $uhome=&homeserver($uname,$udomain);
6467: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6468: my @pairs=split(/\&/,$rep);
6469: my %returnhash=();
1.42 www 6470: my $i=0;
1.800 albertel 6471: foreach my $item (@$storearr) {
6472: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6473: $i++;
1.191 harris41 6474: }
1.12 www 6475: return %returnhash;
6476: }
6477:
1.667 albertel 6478: # ------------------------------------------------------------ tmpput interface
6479: sub tmpput {
1.802 raeburn 6480: my ($storehash,$server,$context)=@_;
1.667 albertel 6481: my $items='';
1.800 albertel 6482: foreach my $item (keys(%$storehash)) {
6483: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6484: }
6485: $items=~s/\&$//;
1.802 raeburn 6486: if (defined($context)) {
6487: $items .= ':'.&escape($context);
6488: }
1.667 albertel 6489: return &reply("tmpput:$items",$server);
6490: }
6491:
6492: # ------------------------------------------------------------ tmpget interface
6493: sub tmpget {
1.688 albertel 6494: my ($token,$server)=@_;
6495: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6496: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6497: my %returnhash;
1.1172.2.85 raeburn 6498: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6499: return %returnhash;
6500: }
1.667 albertel 6501: foreach my $item (split(/\&/,$rep)) {
6502: my ($key,$value)=split(/=/,$item);
6503: $returnhash{&unescape($key)}=&thaw_unescape($value);
6504: }
6505: return %returnhash;
6506: }
6507:
1.1113 raeburn 6508: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6509: sub tmpdel {
6510: my ($token,$server)=@_;
6511: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6512: return &reply("tmpdel:$token",$server);
6513: }
6514:
1.1172.2.13 raeburn 6515: # ------------------------------------------------------------ get_timebased_id
6516:
6517: sub get_timebased_id {
6518: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6519: $maxtries) = @_;
6520: my ($newid,$error,$dellock);
6521: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6522: return ('','ok','invalid call to get suffix');
6523: }
6524:
6525: # set defaults for any optional args for which values were not supplied
6526: if ($who eq '') {
6527: $who = $env{'user.name'}.':'.$env{'user.domain'};
6528: }
6529: if (!$locktries) {
6530: $locktries = 3;
6531: }
6532: if (!$maxtries) {
6533: $maxtries = 10;
6534: }
6535:
6536: if (($cdom eq '') || ($cnum eq '')) {
6537: if ($env{'request.course.id'}) {
6538: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6539: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6540: }
6541: if (($cdom eq '') || ($cnum eq '')) {
6542: return ('','ok','call to get suffix not in course context');
6543: }
6544: }
6545:
6546: # construct locking item
6547: my $lockhash = {
6548: $prefix."\0".'locked_'.$keyid => $who,
6549: };
6550: my $tries = 0;
6551:
6552: # attempt to get lock on nohist_$namespace file
6553: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6554: while (($gotlock ne 'ok') && $tries <$locktries) {
6555: $tries ++;
6556: sleep 1;
6557: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6558: }
6559:
6560: # attempt to get unique identifier, based on current timestamp
6561: if ($gotlock eq 'ok') {
6562: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6563: my $id = time;
6564: $newid = $id;
1.1172.2.56 raeburn 6565: if ($idtype eq 'addcode') {
6566: $newid .= &sixnum_code();
6567: }
1.1172.2.13 raeburn 6568: my $idtries = 0;
6569: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6570: if ($idtype eq 'concat') {
6571: $newid = $id.$idtries;
1.1172.2.56 raeburn 6572: } elsif ($idtype eq 'addcode') {
6573: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6574: } else {
6575: $newid ++;
6576: }
6577: $idtries ++;
6578: }
6579: if (!exists($inuse{$prefix."\0".$newid})) {
6580: my %new_item = (
6581: $prefix."\0".$newid => $who,
6582: );
6583: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6584: $cdom,$cnum);
6585: if ($putresult ne 'ok') {
6586: undef($newid);
6587: $error = 'error saving new item: '.$putresult;
6588: }
6589: } else {
1.1172.2.56 raeburn 6590: undef($newid);
1.1172.2.13 raeburn 6591: $error = ('error: no unique suffix available for the new item ');
6592: }
6593: # remove lock
6594: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6595: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6596: } else {
6597: $error = "error: could not obtain lockfile\n";
6598: $dellock = 'ok';
1.1172.2.58 raeburn 6599: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6600: $dellock = 'nolock';
6601: }
1.1172.2.13 raeburn 6602: }
6603: return ($newid,$dellock,$error);
6604: }
6605:
1.1172.2.56 raeburn 6606: sub sixnum_code {
6607: my $code;
6608: for (0..6) {
6609: $code .= int( rand(9) );
6610: }
6611: return $code;
6612: }
6613:
1.765 albertel 6614: # -------------------------------------------------- portfolio access checking
6615:
6616: sub portfolio_access {
1.1172.2.77 raeburn 6617: my ($requrl,$clientip) = @_;
1.765 albertel 6618: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6619: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6620: if ($result) {
6621: my %setters;
6622: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6623: my ($startblock,$endblock) =
6624: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6625: if ($startblock && $endblock) {
6626: return 'B';
6627: }
6628: } else {
6629: my ($startblock,$endblock) =
6630: &Apache::loncommon::blockcheck(\%setters,'port');
6631: if ($startblock && $endblock) {
6632: return 'B';
6633: }
6634: }
6635: }
1.765 albertel 6636: if ($result eq 'ok') {
1.766 albertel 6637: return 'F';
1.765 albertel 6638: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6639: return 'A';
1.765 albertel 6640: }
1.766 albertel 6641: return '';
1.765 albertel 6642: }
6643:
6644: sub get_portfolio_access {
1.1172.2.77 raeburn 6645: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6646:
6647: if (!ref($access_hash)) {
6648: my $current_perms = &get_portfile_permissions($udom,$unum);
6649: my %access_controls = &get_access_controls($current_perms,$group,
6650: $file_name);
6651: $access_hash = $access_controls{$file_name};
6652: }
6653:
1.1172.2.77 raeburn 6654: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6655: my $now = time;
6656: if (ref($access_hash) eq 'HASH') {
6657: foreach my $key (keys(%{$access_hash})) {
6658: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6659: if ($start > $now) {
6660: next;
6661: }
6662: if ($end && $end<$now) {
6663: next;
6664: }
6665: if ($scope eq 'public') {
6666: $public = $key;
6667: last;
6668: } elsif ($scope eq 'guest') {
6669: $guest = $key;
6670: } elsif ($scope eq 'domains') {
6671: push(@domains,$key);
6672: } elsif ($scope eq 'users') {
6673: push(@users,$key);
6674: } elsif ($scope eq 'course') {
6675: push(@courses,$key);
6676: } elsif ($scope eq 'group') {
6677: push(@groups,$key);
1.1172.2.77 raeburn 6678: } elsif ($scope eq 'ip') {
6679: push(@ips,$key);
1.765 albertel 6680: }
6681: }
6682: if ($public) {
6683: return 'ok';
1.1172.2.77 raeburn 6684: } elsif (@ips > 0) {
6685: my $allowed;
6686: foreach my $ipkey (@ips) {
6687: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6688: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6689: $allowed = 1;
6690: last;
6691: }
6692: }
6693: }
6694: if ($allowed) {
6695: return 'ok';
6696: }
1.765 albertel 6697: }
6698: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6699: if ($guest) {
6700: return $guest;
6701: }
6702: } else {
6703: if (@domains > 0) {
6704: foreach my $domkey (@domains) {
6705: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6706: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6707: return 'ok';
6708: }
6709: }
6710: }
6711: }
6712: if (@users > 0) {
6713: foreach my $userkey (@users) {
1.865 raeburn 6714: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6715: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6716: if (ref($item) eq 'HASH') {
6717: if (($item->{'uname'} eq $env{'user.name'}) &&
6718: ($item->{'udom'} eq $env{'user.domain'})) {
6719: return 'ok';
6720: }
6721: }
6722: }
6723: }
1.765 albertel 6724: }
6725: }
6726: my %roleshash;
6727: my @courses_and_groups = @courses;
6728: push(@courses_and_groups,@groups);
6729: if (@courses_and_groups > 0) {
6730: my (%allgroups,%allroles);
6731: my ($start,$end,$role,$sec,$group);
6732: foreach my $envkey (%env) {
1.1060 raeburn 6733: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6734: my $cid = $2.'_'.$3;
6735: if ($1 eq 'gr') {
6736: $group = $4;
6737: $allgroups{$cid}{$group} = $env{$envkey};
6738: } else {
6739: if ($4 eq '') {
6740: $sec = 'none';
6741: } else {
6742: $sec = $4;
6743: }
6744: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6745: }
1.811 albertel 6746: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6747: my $cid = $2.'_'.$3;
6748: if ($4 eq '') {
6749: $sec = 'none';
6750: } else {
6751: $sec = $4;
6752: }
6753: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6754: }
6755: }
6756: if (keys(%allroles) == 0) {
6757: return;
6758: }
6759: foreach my $key (@courses_and_groups) {
6760: my %content = %{$$access_hash{$key}};
6761: my $cnum = $content{'number'};
6762: my $cdom = $content{'domain'};
6763: my $cid = $cdom.'_'.$cnum;
6764: if (!exists($allroles{$cid})) {
6765: next;
6766: }
6767: foreach my $role_id (keys(%{$content{'roles'}})) {
6768: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6769: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6770: my @status = @{$content{'roles'}{$role_id}{'access'}};
6771: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6772: foreach my $role (keys(%{$allroles{$cid}})) {
6773: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6774: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6775: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6776: if (grep/^all$/,@sections) {
6777: return 'ok';
6778: } else {
6779: if (grep/^$sec$/,@sections) {
6780: return 'ok';
6781: }
6782: }
6783: }
6784: }
6785: if (keys(%{$allgroups{$cid}}) == 0) {
6786: if (grep/^none$/,@groups) {
6787: return 'ok';
6788: }
6789: } else {
6790: if (grep/^all$/,@groups) {
6791: return 'ok';
6792: }
6793: foreach my $group (keys(%{$allgroups{$cid}})) {
6794: if (grep/^$group$/,@groups) {
6795: return 'ok';
6796: }
6797: }
6798: }
6799: }
6800: }
6801: }
6802: }
6803: }
6804: if ($guest) {
6805: return $guest;
6806: }
6807: }
6808: }
6809: return;
6810: }
6811:
6812: sub course_group_datechecker {
6813: my ($dates,$now,$status) = @_;
6814: my ($start,$end) = split(/\./,$dates);
6815: if (!$start && !$end) {
6816: return 'ok';
6817: }
6818: if (grep/^active$/,@{$status}) {
6819: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6820: return 'ok';
6821: }
6822: }
6823: if (grep/^previous$/,@{$status}) {
6824: if ($end > $now ) {
6825: return 'ok';
6826: }
6827: }
6828: if (grep/^future$/,@{$status}) {
6829: if ($start > $now) {
6830: return 'ok';
6831: }
6832: }
6833: return;
6834: }
6835:
6836: sub parse_portfolio_url {
6837: my ($url) = @_;
6838:
6839: my ($type,$udom,$unum,$group,$file_name);
6840:
1.823 albertel 6841: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6842: $type = 1;
6843: $udom = $1;
6844: $unum = $2;
6845: $file_name = $3;
1.823 albertel 6846: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6847: $type = 2;
6848: $udom = $1;
6849: $unum = $2;
6850: $group = $3;
6851: $file_name = $3.'/'.$4;
6852: }
6853: if (wantarray) {
6854: return ($type,$udom,$unum,$file_name,$group);
6855: }
6856: return $type;
6857: }
6858:
6859: sub is_portfolio_url {
6860: my ($url) = @_;
6861: return scalar(&parse_portfolio_url($url));
6862: }
6863:
1.798 raeburn 6864: sub is_portfolio_file {
6865: my ($file) = @_;
1.820 raeburn 6866: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6867: return 1;
6868: }
6869: return;
6870: }
6871:
1.976 raeburn 6872: sub usertools_access {
1.1084 raeburn 6873: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6874: my ($access,%tools);
6875: if ($context eq '') {
6876: $context = 'tools';
6877: }
6878: if ($context eq 'requestcourses') {
6879: %tools = (
6880: official => 1,
6881: unofficial => 1,
1.1006 raeburn 6882: community => 1,
1.1172.2.37 raeburn 6883: textbook => 1,
1.985 raeburn 6884: );
1.1172.2.9 raeburn 6885: } elsif ($context eq 'requestauthor') {
6886: %tools = (
6887: requestauthor => 1,
6888: );
1.985 raeburn 6889: } else {
6890: %tools = (
6891: aboutme => 1,
6892: blog => 1,
1.1172.2.6 raeburn 6893: webdav => 1,
1.985 raeburn 6894: portfolio => 1,
6895: );
6896: }
1.976 raeburn 6897: return if (!defined($tools{$tool}));
6898:
1.1172.2.35 raeburn 6899: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6900: $udom = $env{'user.domain'};
6901: $uname = $env{'user.name'};
6902: }
6903:
1.978 raeburn 6904: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6905: if ($action ne 'reload') {
1.985 raeburn 6906: if ($context eq 'requestcourses') {
6907: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6908: } elsif ($context eq 'requestauthor') {
6909: return $env{'environment.canrequest.author'};
1.985 raeburn 6910: } else {
6911: return $env{'environment.availabletools.'.$tool};
6912: }
6913: }
1.976 raeburn 6914: }
6915:
1.1172.2.9 raeburn 6916: my ($toolstatus,$inststatus,$envkey);
6917: if ($context eq 'requestauthor') {
6918: $envkey = $context;
6919: } else {
6920: $envkey = $context.'.'.$tool;
6921: }
1.976 raeburn 6922:
1.985 raeburn 6923: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6924: ($action ne 'reload')) {
1.1172.2.9 raeburn 6925: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6926: $inststatus = $env{'environment.inststatus'};
6927: } else {
1.1084 raeburn 6928: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6929: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6930: $inststatus = $userenvref->{'inststatus'};
6931: } else {
1.1172.2.9 raeburn 6932: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6933: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6934: $inststatus = $userenv{'inststatus'};
6935: }
1.976 raeburn 6936: }
6937:
6938: if ($toolstatus ne '') {
6939: if ($toolstatus) {
6940: $access = 1;
6941: } else {
6942: $access = 0;
6943: }
6944: return $access;
6945: }
6946:
1.1084 raeburn 6947: my ($is_adv,%domdef);
6948: if (ref($is_advref) eq 'HASH') {
6949: $is_adv = $is_advref->{'is_adv'};
6950: } else {
6951: $is_adv = &is_advanced_user($udom,$uname);
6952: }
6953: if (ref($domdefref) eq 'HASH') {
6954: %domdef = %{$domdefref};
6955: } else {
6956: %domdef = &get_domain_defaults($udom);
6957: }
1.976 raeburn 6958: if (ref($domdef{$tool}) eq 'HASH') {
6959: if ($is_adv) {
6960: if ($domdef{$tool}{'_LC_adv'} ne '') {
6961: if ($domdef{$tool}{'_LC_adv'}) {
6962: $access = 1;
6963: } else {
6964: $access = 0;
6965: }
6966: return $access;
6967: }
6968: }
6969: if ($inststatus ne '') {
6970: my ($hasaccess,$hasnoaccess);
6971: foreach my $affiliation (split(/:/,$inststatus)) {
6972: if ($domdef{$tool}{$affiliation} ne '') {
6973: if ($domdef{$tool}{$affiliation}) {
6974: $hasaccess = 1;
6975: } else {
6976: $hasnoaccess = 1;
6977: }
6978: }
6979: }
6980: if ($hasaccess || $hasnoaccess) {
6981: if ($hasaccess) {
6982: $access = 1;
6983: } elsif ($hasnoaccess) {
6984: $access = 0;
6985: }
6986: return $access;
6987: }
6988: } else {
6989: if ($domdef{$tool}{'default'} ne '') {
6990: if ($domdef{$tool}{'default'}) {
6991: $access = 1;
6992: } elsif ($domdef{$tool}{'default'} == 0) {
6993: $access = 0;
6994: }
6995: return $access;
6996: }
6997: }
6998: } else {
1.1172.2.6 raeburn 6999: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7000: $access = 1;
7001: } else {
7002: $access = 0;
7003: }
1.976 raeburn 7004: return $access;
7005: }
7006: }
7007:
1.1050 raeburn 7008: sub is_course_owner {
7009: my ($cdom,$cnum,$udom,$uname) = @_;
7010: if (($udom eq '') || ($uname eq '')) {
7011: $udom = $env{'user.domain'};
7012: $uname = $env{'user.name'};
7013: }
7014: unless (($udom eq '') || ($uname eq '')) {
7015: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7016: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7017: return 1;
7018: } else {
7019: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7020: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7021: return 1;
7022: }
7023: }
7024: }
7025: }
7026: return;
7027: }
7028:
1.976 raeburn 7029: sub is_advanced_user {
7030: my ($udom,$uname) = @_;
1.1085 raeburn 7031: if ($udom ne '' && $uname ne '') {
7032: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7033: if (wantarray) {
7034: return ($env{'user.adv'},$env{'user.author'});
7035: } else {
7036: return $env{'user.adv'};
7037: }
1.1085 raeburn 7038: }
7039: }
1.976 raeburn 7040: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7041: my %allroles;
1.1128 raeburn 7042: my ($is_adv,$is_author);
1.976 raeburn 7043: foreach my $role (keys(%roleshash)) {
7044: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7045: my $area = '/'.$tdomain.'/'.$trest;
7046: if ($sec ne '') {
7047: $area .= '/'.$sec;
7048: }
7049: if (($area ne '') && ($trole ne '')) {
7050: my $spec=$trole.'.'.$area;
7051: if ($trole =~ /^cr\//) {
7052: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7053: } elsif ($trole ne 'gr') {
7054: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7055: }
1.1128 raeburn 7056: if ($trole eq 'au') {
7057: $is_author = 1;
7058: }
1.976 raeburn 7059: }
7060: }
7061: foreach my $role (keys(%allroles)) {
7062: last if ($is_adv);
7063: foreach my $item (split(/:/,$allroles{$role})) {
7064: if ($item ne '') {
7065: my ($privilege,$restrictions)=split(/&/,$item);
7066: if ($privilege eq 'adv') {
7067: $is_adv = 1;
7068: last;
7069: }
7070: }
7071: }
7072: }
1.1128 raeburn 7073: if (wantarray) {
7074: return ($is_adv,$is_author);
7075: }
1.976 raeburn 7076: return $is_adv;
7077: }
1.798 raeburn 7078:
1.1035 raeburn 7079: sub check_can_request {
1.1036 raeburn 7080: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7081: my $canreq = 0;
7082: my ($types,$typename) = &Apache::loncommon::course_types();
7083: my @options = ('approval','validate','autolimit');
7084: my $optregex = join('|',@options);
7085: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7086: foreach my $type (@{$types}) {
7087: if (&usertools_access($env{'user.name'},
7088: $env{'user.domain'},
7089: $type,undef,'requestcourses')) {
7090: $canreq ++;
1.1036 raeburn 7091: if (ref($request_domains) eq 'HASH') {
7092: push(@{$request_domains->{$type}},$env{'user.domain'});
7093: }
1.1035 raeburn 7094: if ($dom eq $env{'user.domain'}) {
7095: $can_request->{$type} = 1;
7096: }
7097: }
7098: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7099: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7100: if (@curr > 0) {
1.1036 raeburn 7101: foreach my $item (@curr) {
7102: if (ref($request_domains) eq 'HASH') {
7103: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7104: if ($otherdom ne '') {
7105: if (ref($request_domains->{$type}) eq 'ARRAY') {
7106: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7107: push(@{$request_domains->{$type}},$otherdom);
7108: }
7109: } else {
7110: push(@{$request_domains->{$type}},$otherdom);
7111: }
7112: }
7113: }
7114: }
7115: unless($dom eq $env{'user.domain'}) {
7116: $canreq ++;
1.1035 raeburn 7117: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7118: $can_request->{$type} = 1;
7119: }
7120: }
7121: }
7122: }
7123: }
7124: }
7125: return $canreq;
7126: }
7127:
1.341 www 7128: # ---------------------------------------------- Custom access rule evaluation
7129:
7130: sub customaccess {
7131: my ($priv,$uri)=@_;
1.807 albertel 7132: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7133: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7134: $udom = &LONCAPA::clean_domain($udom);
7135: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7136: my $access=0;
1.800 albertel 7137: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7138: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7139: if ($type eq 'user') {
7140: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7141: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7142: if ($tdom) {
7143: if ($tdom ne $env{'user.domain'}) { next; }
7144: }
1.896 albertel 7145: if ($tuname) {
7146: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7147: }
7148: $access=($effect eq 'allow');
7149: last;
7150: }
7151: } else {
7152: if ($role) {
7153: if ($role ne $urole) { next; }
7154: }
7155: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7156: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7157: if ($tdom) {
7158: if ($tdom ne $udom) { next; }
7159: }
7160: if ($tcrs) {
7161: if ($tcrs ne $ucrs) { next; }
7162: }
7163: if ($tsec) {
7164: if ($tsec ne $usec) { next; }
7165: }
7166: $access=($effect eq 'allow');
7167: last;
7168: }
7169: if ($realm eq '' && $role eq '') {
7170: $access=($effect eq 'allow');
7171: }
1.402 bowersj2 7172: }
1.341 www 7173: }
7174: return $access;
7175: }
7176:
1.103 harris41 7177: # ------------------------------------------------- Check for a user privilege
1.12 www 7178:
7179: sub allowed {
1.1172.2.65 raeburn 7180: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7181: my $ver_orguri=$uri;
1.439 www 7182: $uri=&deversion($uri);
1.152 www 7183: my $orguri=$uri;
1.52 www 7184: $uri=&declutter($uri);
1.809 raeburn 7185:
1.810 raeburn 7186: if ($priv eq 'evb') {
7187: # Evade communication block restrictions for specified role in a course
7188: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7189: return $1;
7190: } else {
7191: return;
7192: }
7193: }
7194:
1.620 albertel 7195: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7196: # Free bre access to adm and meta resources
1.1172.2.93.4 2(raebur 7197:7): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7198: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7199: && ($priv eq 'bre')) {
1.14 www 7200: return 'F';
1.159 www 7201: }
7202:
1.545 banghart 7203: # Free bre access to user's own portfolio contents
1.714 raeburn 7204: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7205: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7206: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7207: my %setters;
7208: my ($startblock,$endblock) =
7209: &Apache::loncommon::blockcheck(\%setters,'port');
7210: if ($startblock && $endblock) {
7211: return 'B';
7212: } else {
7213: return 'F';
7214: }
1.545 banghart 7215: }
7216:
1.762 raeburn 7217: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7218: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7219: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7220: if (exists($env{'request.course.id'})) {
7221: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7222: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7223: if (($domain eq $cdom) && ($name eq $cnum)) {
7224: my $courseprivid=$env{'request.course.id'};
7225: $courseprivid=~s/\_/\//;
7226: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7227: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7228: return $1;
1.762 raeburn 7229: } else {
7230: if ($env{'request.course.sec'}) {
7231: $courseprivid.='/'.$env{'request.course.sec'};
7232: }
7233: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7234: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7235: return $2;
7236: }
1.714 raeburn 7237: }
7238: }
7239: }
7240: }
7241:
1.159 www 7242: # Free bre to public access
7243:
7244: if ($priv eq 'bre') {
1.238 www 7245: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7246: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7247: return 'F';
7248: }
1.238 www 7249: if ($copyright eq 'priv') {
7250: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7251: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7252: return '';
7253: }
7254: }
7255: if ($copyright eq 'domain') {
7256: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7257: unless (($env{'user.domain'} eq $1) ||
7258: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7259: return '';
7260: }
1.262 matthew 7261: }
1.620 albertel 7262: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7263: # Library role, so allow browsing of resources in this domain.
7264: return 'F';
1.238 www 7265: }
1.341 www 7266: if ($copyright eq 'custom') {
7267: unless (&customaccess($priv,$uri)) { return ''; }
7268: }
1.14 www 7269: }
1.264 matthew 7270: # Domain coordinator is trying to create a course
1.620 albertel 7271: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7272: # uri is the requested domain in this case.
7273: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7274: # a role of dc for the domain in question.
1.620 albertel 7275: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7276: }
1.29 www 7277:
1.52 www 7278: my $thisallowed='';
7279: my $statecond=0;
7280: my $courseprivid='';
7281:
1.1039 raeburn 7282: my $ownaccess;
1.1043 raeburn 7283: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7284: if (($priv eq 'bro') && ($env{'user.author'})) {
7285: if ($uri eq '') {
7286: $ownaccess = 1;
7287: } else {
7288: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7289: my $udom = $env{'user.domain'};
7290: my $uname = $env{'user.name'};
7291: if ($uri =~ m{^\Q$udom\E/?$}) {
7292: $ownaccess = 1;
1.1040 raeburn 7293: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7294: unless ($uri =~ m{\.\./}) {
7295: $ownaccess = 1;
7296: }
7297: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7298: my $now = time;
7299: if ($uri =~ m{^([^/]+)/?$}) {
7300: my $adom = $1;
7301: foreach my $key (keys(%env)) {
1.1042 raeburn 7302: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7303: my ($start,$end) = split('.',$env{$key});
7304: if (($now >= $start) && (!$end || $end < $now)) {
7305: $ownaccess = 1;
7306: last;
7307: }
7308: }
7309: }
7310: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7311: my $adom = $1;
7312: my $aname = $2;
1.1042 raeburn 7313: foreach my $role ('ca','aa') {
7314: if ($env{"user.role.$role./$adom/$aname"}) {
7315: my ($start,$end) =
7316: split('.',$env{"user.role.$role./$adom/$aname"});
7317: if (($now >= $start) && (!$end || $end < $now)) {
7318: $ownaccess = 1;
7319: last;
7320: }
1.1039 raeburn 7321: }
7322: }
7323: }
7324: }
7325: }
7326: }
7327: }
7328:
1.52 www 7329: # Course
7330:
1.620 albertel 7331: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7332: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7333: $thisallowed.=$1;
7334: }
1.52 www 7335: }
1.29 www 7336:
1.52 www 7337: # Domain
7338:
1.620 albertel 7339: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7340: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7341: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7342: $thisallowed.=$1;
7343: }
1.12 www 7344: }
1.52 www 7345:
1.1141 raeburn 7346: # User who is not author or co-author might still be able to edit
7347: # resource of an author in the domain (e.g., if Domain Coordinator).
7348: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7349: (&allowed('mdc',$env{'request.course.id'}))) {
7350: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7351: $thisallowed.=$1;
7352: }
7353: }
7354:
1.52 www 7355: # Course: uri itself is a course
1.66 www 7356: my $courseuri=$uri;
7357: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7358: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7359:
1.620 albertel 7360: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7361: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7362: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7363: $thisallowed.=$1;
7364: }
1.12 www 7365: }
1.29 www 7366:
1.665 albertel 7367: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7368: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7369: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7370: $thisallowed='';
1.671 raeburn 7371: my ($match)=&is_on_map($uri);
7372: if ($match) {
7373: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7374: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7375: my $value = $1;
7376: if ($noblockcheck) {
7377: $thisallowed.=$value;
1.1162 raeburn 7378: } else {
1.1172.2.65 raeburn 7379: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7380: if (@blockers > 0) {
7381: $thisallowed = 'B';
7382: } else {
7383: $thisallowed.=$value;
7384: }
1.1162 raeburn 7385: }
1.671 raeburn 7386: }
7387: } else {
1.705 albertel 7388: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7389: if ($refuri) {
7390: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7391: $thisallowed='F';
1.671 raeburn 7392: } else {
7393: $refuri=&declutter($refuri);
7394: my ($match) = &is_on_map($refuri);
7395: if ($match) {
1.1172.2.65 raeburn 7396: if ($noblockcheck) {
1.1162 raeburn 7397: $thisallowed='F';
1.1172.2.65 raeburn 7398: } else {
7399: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7400: if (@blockers > 0) {
7401: $thisallowed = 'B';
7402: } else {
7403: $thisallowed='F';
7404: }
1.1162 raeburn 7405: }
1.671 raeburn 7406: }
1.669 raeburn 7407: }
1.671 raeburn 7408: }
7409: }
1.314 www 7410: }
1.492 albertel 7411:
1.766 albertel 7412: if ($priv eq 'bre'
7413: && $thisallowed ne 'F'
7414: && $thisallowed ne '2'
7415: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7416: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7417: }
7418:
1.52 www 7419: # Full access at system, domain or course-wide level? Exit.
1.29 www 7420: if ($thisallowed=~/F/) {
7421: return 'F';
7422: }
7423:
1.52 www 7424: # If this is generating or modifying users, exit with special codes
1.29 www 7425:
1.643 www 7426: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7427: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7428: my ($audom,$auname)=split('/',$uri);
1.643 www 7429: # no author name given, so this just checks on the general right to make a co-author in this domain
7430: unless ($auname) { return $thisallowed; }
7431: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7432: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7433: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7434: ($audom ne $env{'request.role.domain'}))) { return ''; }
7435: }
1.52 www 7436: return $thisallowed;
7437: }
7438: #
1.103 harris41 7439: # Gathered so far: system, domain and course wide privileges
1.52 www 7440: #
7441: # Course: See if uri or referer is an individual resource that is part of
7442: # the course
7443:
1.620 albertel 7444: if ($env{'request.course.id'}) {
1.232 www 7445:
1.620 albertel 7446: $courseprivid=$env{'request.course.id'};
7447: if ($env{'request.course.sec'}) {
7448: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7449: }
7450: $courseprivid=~s/\_/\//;
7451: my $checkreferer=1;
1.232 www 7452: my ($match,$cond)=&is_on_map($uri);
7453: if ($match) {
7454: $statecond=$cond;
1.620 albertel 7455: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7456: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7457: my $value = $1;
7458: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7459: if ($noblockcheck) {
1.1162 raeburn 7460: $thisallowed.=$value;
1.1172.2.65 raeburn 7461: } else {
7462: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7463: if (@blockers > 0) {
7464: $thisallowed = 'B';
7465: } else {
7466: $thisallowed.=$value;
7467: }
1.1162 raeburn 7468: }
7469: } else {
7470: $thisallowed.=$value;
7471: }
1.52 www 7472: $checkreferer=0;
7473: }
1.29 www 7474: }
1.83 www 7475:
1.148 www 7476: if ($checkreferer) {
1.620 albertel 7477: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7478: unless ($refuri) {
1.800 albertel 7479: foreach my $key (keys(%env)) {
7480: if ($key=~/^httpref\..*\*/) {
7481: my $pattern=$key;
1.156 www 7482: $pattern=~s/^httpref\.\/res\///;
1.148 www 7483: $pattern=~s/\*/\[\^\/\]\+/g;
7484: $pattern=~s/\//\\\//g;
1.152 www 7485: if ($orguri=~/$pattern/) {
1.800 albertel 7486: $refuri=$env{$key};
1.148 www 7487: }
7488: }
1.191 harris41 7489: }
1.148 www 7490: }
1.232 www 7491:
1.148 www 7492: if ($refuri) {
1.152 www 7493: $refuri=&declutter($refuri);
1.232 www 7494: my ($match,$cond)=&is_on_map($refuri);
7495: if ($match) {
7496: my $refstatecond=$cond;
1.620 albertel 7497: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7498: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7499: my $value = $1;
7500: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7501: if ($noblockcheck) {
1.1162 raeburn 7502: $thisallowed.=$value;
1.1172.2.65 raeburn 7503: } else {
7504: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7505: if (@blockers > 0) {
7506: $thisallowed = 'B';
7507: } else {
7508: $thisallowed.=$value;
7509: }
1.1162 raeburn 7510: }
7511: } else {
7512: $thisallowed.=$value;
7513: }
1.53 www 7514: $uri=$refuri;
7515: $statecond=$refstatecond;
1.52 www 7516: }
7517: }
1.148 www 7518: }
1.29 www 7519: }
1.52 www 7520: }
1.29 www 7521:
1.52 www 7522: #
1.103 harris41 7523: # Gathered now: all privileges that could apply, and condition number
1.52 www 7524: #
7525: #
7526: # Full or no access?
7527: #
1.29 www 7528:
1.52 www 7529: if ($thisallowed=~/F/) {
7530: return 'F';
7531: }
1.29 www 7532:
1.52 www 7533: unless ($thisallowed) {
7534: return '';
7535: }
1.29 www 7536:
1.52 www 7537: # Restrictions exist, deal with them
7538: #
7539: # C:according to course preferences
7540: # R:according to resource settings
7541: # L:unless locked
7542: # X:according to user session state
7543: #
7544:
7545: # Possibly locked functionality, check all courses
1.54 www 7546: # Locks might take effect only after 10 minutes cache expiration for other
7547: # courses, and 2 minutes for current course
1.52 www 7548:
7549: my $envkey;
7550: if ($thisallowed=~/L/) {
1.1000 raeburn 7551: foreach $envkey (keys(%env)) {
1.54 www 7552: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7553: my $courseid=$2;
7554: my $roleid=$1.'.'.$2;
1.92 www 7555: $courseid=~s/^\///;
1.54 www 7556: my $expiretime=600;
1.620 albertel 7557: if ($env{'request.role'} eq $roleid) {
1.54 www 7558: $expiretime=120;
7559: }
7560: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7561: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7562: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7563: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7564: }
1.620 albertel 7565: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7566: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7567: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7568: &log($env{'user.domain'},$env{'user.name'},
7569: $env{'user.home'},
1.57 www 7570: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7571: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7572: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7573: return '';
7574: }
7575: }
1.620 albertel 7576: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7577: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7578: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7579: &log($env{'user.domain'},$env{'user.name'},
7580: $env{'user.home'},
1.57 www 7581: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7582: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7583: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7584: return '';
7585: }
7586: }
7587: }
1.29 www 7588: }
1.52 www 7589: }
7590:
7591: #
7592: # Rest of the restrictions depend on selected course
7593: #
7594:
1.620 albertel 7595: unless ($env{'request.course.id'}) {
1.766 albertel 7596: if ($thisallowed eq 'A') {
7597: return 'A';
1.814 raeburn 7598: } elsif ($thisallowed eq 'B') {
7599: return 'B';
1.766 albertel 7600: } else {
7601: return '1';
7602: }
1.52 www 7603: }
1.29 www 7604:
1.52 www 7605: #
7606: # Now user is definitely in a course
7607: #
1.53 www 7608:
7609:
7610: # Course preferences
7611:
7612: if ($thisallowed=~/C/) {
1.620 albertel 7613: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7614: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7615: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7616: =~/\Q$rolecode\E/) {
1.1103 raeburn 7617: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7618: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7619: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7620: $env{'request.course.id'});
7621: }
1.237 www 7622: return '';
7623: }
7624:
1.620 albertel 7625: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7626: =~/\Q$unamedom\E/) {
1.1103 raeburn 7627: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7628: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7629: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7630: $env{'request.course.id'});
7631: }
1.54 www 7632: return '';
7633: }
1.53 www 7634: }
7635:
7636: # Resource preferences
7637:
7638: if ($thisallowed=~/R/) {
1.620 albertel 7639: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7640: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7641: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7642: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7643: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7644: }
7645: return '';
1.54 www 7646: }
1.53 www 7647: }
1.30 www 7648:
1.246 www 7649: # Restricted by state or randomout?
1.30 www 7650:
1.52 www 7651: if ($thisallowed=~/X/) {
1.620 albertel 7652: if ($env{'acc.randomout'}) {
1.579 albertel 7653: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7654: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7655: return '';
7656: }
1.247 www 7657: }
7658: if (&condval($statecond)) {
1.52 www 7659: return '2';
7660: } else {
7661: return '';
7662: }
7663: }
1.30 www 7664:
1.766 albertel 7665: if ($thisallowed eq 'A') {
7666: return 'A';
1.814 raeburn 7667: } elsif ($thisallowed eq 'B') {
7668: return 'B';
1.766 albertel 7669: }
1.52 www 7670: return 'F';
1.232 www 7671: }
1.1162 raeburn 7672:
1.1172.2.13 raeburn 7673: # ------------------------------------------- Check construction space access
7674:
7675: sub constructaccess {
7676: my ($url,$setpriv)=@_;
7677:
7678: # We do not allow editing of previous versions of files
7679: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7680:
7681: # Get username and domain from URL
7682: my ($ownername,$ownerdomain,$ownerhome);
7683:
7684: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7685: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7686:
7687: # The URL does not really point to any authorspace, forget it
7688: unless (($ownername) && ($ownerdomain)) { return ''; }
7689:
7690: # Now we need to see if the user has access to the authorspace of
7691: # $ownername at $ownerdomain
7692:
7693: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7694: # Real author for this?
7695: $ownerhome = $env{'user.home'};
7696: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7697: return ($ownername,$ownerdomain,$ownerhome);
7698: }
7699: } else {
7700: # Co-author for this?
7701: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7702: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7703: $ownerhome = &homeserver($ownername,$ownerdomain);
7704: return ($ownername,$ownerdomain,$ownerhome);
7705: }
7706: }
7707:
7708: # We don't have any access right now. If we are not possibly going to do anything about this,
7709: # we might as well leave
7710: unless ($setpriv) { return ''; }
7711:
7712: # Backdoor access?
7713: my $allowed=&allowed('eco',$ownerdomain);
7714: # Nope
7715: unless ($allowed) { return ''; }
7716: # Looks like we may have access, but could be locked by the owner of the construction space
7717: if ($allowed eq 'U') {
7718: my %blocked=&get('environment',['domcoord.author'],
7719: $ownerdomain,$ownername);
7720: # Is blocked by owner
7721: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7722: }
7723: if (($allowed eq 'F') || ($allowed eq 'U')) {
7724: # Grant temporary access
7725: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7726: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7727: if (!$update) { $update = $then; }
7728: my $refresh=$env{'user.refresh.time'};
7729: if (!$refresh) { $refresh = $update; }
7730: my $now = time;
7731: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7732: $now,'ca','constructaccess');
7733: $ownerhome = &homeserver($ownername,$ownerdomain);
7734: return($ownername,$ownerdomain,$ownerhome);
7735: }
7736: # No business here
7737: return '';
7738: }
7739:
1.1172.2.66 raeburn 7740: # ----------------------------------------------------------- Content Blocking
7741:
7742: {
7743: # Caches for faster Course Contents display where content blocking
7744: # is in operation (i.e., interval param set) for timed quiz.
7745: #
7746: # User for whom data are being temporarily cached.
7747: my $cacheduser='';
7748: # Cached blockers for this user (a hash of blocking items).
7749: my %cachedblockers=();
7750: # When the data were last cached.
7751: my $cachedlast='';
7752:
7753: sub load_all_blockers {
7754: my ($uname,$udom,$blocks)=@_;
7755: if (($uname ne '') && ($udom ne '')) {
7756: if (($cacheduser eq $uname.':'.$udom) &&
7757: (abs($cachedlast-time)<5)) {
7758: return;
7759: }
7760: }
7761: $cachedlast=time;
7762: $cacheduser=$uname.':'.$udom;
7763: %cachedblockers = &get_commblock_resources($blocks);
7764: }
7765:
1.1162 raeburn 7766: sub get_comm_blocks {
7767: my ($cdom,$cnum) = @_;
7768: if ($cdom eq '' || $cnum eq '') {
7769: return unless ($env{'request.course.id'});
7770: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7771: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7772: }
7773: my %commblocks;
7774: my $hashid=$cdom.'_'.$cnum;
7775: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7776: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7777: %commblocks = %{$blocksref};
7778: } else {
7779: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7780: my $cachetime = 600;
7781: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7782: }
7783: return %commblocks;
7784: }
7785:
1.1172.2.66 raeburn 7786: sub get_commblock_resources {
7787: my ($blocks) = @_;
7788: my %blockers = ();
7789: return %blockers unless ($env{'request.course.id'});
7790: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7791: my %commblocks;
7792: if (ref($blocks) eq 'HASH') {
7793: %commblocks = %{$blocks};
7794: } else {
7795: %commblocks = &get_comm_blocks();
7796: }
1.1172.2.66 raeburn 7797: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7798: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7799: return %blockers unless (ref($navmap));
7800: my $now = time;
1.1162 raeburn 7801: foreach my $block (keys(%commblocks)) {
7802: if ($block =~ /^(\d+)____(\d+)$/) {
7803: my ($start,$end) = ($1,$2);
7804: if ($start <= $now && $end >= $now) {
7805: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7806: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7807: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7808: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7809: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7810: }
7811: }
7812: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7813: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7814: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7815: }
7816: }
7817: }
7818: }
7819: }
7820: } elsif ($block =~ /^firstaccess____(.+)$/) {
7821: my $item = $1;
1.1163 raeburn 7822: my @to_test;
1.1162 raeburn 7823: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7824: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7825: my @interval;
7826: my $type = 'map';
7827: if ($item eq 'course') {
7828: $type = 'course';
7829: @interval=&EXT("resource.0.interval");
7830: } else {
7831: if ($item =~ /___\d+___/) {
7832: $type = 'resource';
7833: @interval=&EXT("resource.0.interval",$item);
7834: if (ref($navmap)) {
7835: my $res = $navmap->getBySymb($item);
7836: push(@to_test,$res);
7837: }
1.1162 raeburn 7838: } else {
1.1172.2.66 raeburn 7839: my $mapsymb = &symbread($item,1);
7840: if ($mapsymb) {
7841: if (ref($navmap)) {
7842: my $mapres = $navmap->getBySymb($mapsymb);
7843: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7844: foreach my $res (@to_test) {
7845: my $symb = $res->symb();
7846: next if ($symb eq $mapsymb);
7847: if ($symb ne '') {
7848: @interval=&EXT("resource.0.interval",$symb);
7849: if ($interval[1] eq 'map') {
7850: last;
1.1162 raeburn 7851: }
7852: }
7853: }
7854: }
7855: }
7856: }
1.1172.2.66 raeburn 7857: }
1.1172.2.93.4 1(raebur 7858:7): if ($interval[0] =~ /^(\d+)/) {
7859:7): my $timelimit = $1;
1.1172.2.66 raeburn 7860: my $first_access;
7861: if ($type eq 'resource') {
7862: $first_access=&get_first_access($interval[1],$item);
7863: } elsif ($type eq 'map') {
7864: $first_access=&get_first_access($interval[1],undef,$item);
7865: } else {
7866: $first_access=&get_first_access($interval[1]);
7867: }
7868: if ($first_access) {
1.1172.2.93.4 1(raebur 7869:7): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 7870: if ($timesup > $now) {
7871: my $activeblock;
7872: foreach my $res (@to_test) {
7873: if ($res->answerable()) {
7874: $activeblock = 1;
7875: last;
7876: }
7877: }
7878: if ($activeblock) {
7879: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7880: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7881: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7882: }
7883: }
7884: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7885: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7886: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7887: }
1.1162 raeburn 7888: }
7889: }
7890: }
7891: }
7892: }
7893: }
7894: }
7895: }
7896: }
1.1172.2.66 raeburn 7897: return %blockers;
1.1162 raeburn 7898: }
7899:
1.1172.2.66 raeburn 7900: sub has_comm_blocking {
7901: my ($priv,$symb,$uri,$blocks) = @_;
7902: my @blockers;
7903: return unless ($env{'request.course.id'});
7904: return unless ($priv eq 'bre');
7905: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7906: return if ($env{'request.state'} eq 'construct');
7907: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7908: return unless (keys(%cachedblockers) > 0);
7909: my (%possibles,@symbs);
7910: if (!$symb) {
7911: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7912: }
1.1172.2.66 raeburn 7913: if ($symb) {
7914: @symbs = ($symb);
7915: } elsif (keys(%possibles)) {
7916: @symbs = keys(%possibles);
7917: }
7918: my $noblock;
7919: foreach my $symb (@symbs) {
7920: last if ($noblock);
7921: my ($map,$resid,$resurl)=&decode_symb($symb);
7922: foreach my $block (keys(%cachedblockers)) {
7923: if ($block =~ /^firstaccess____(.+)$/) {
7924: my $item = $1;
7925: if (($item eq $map) || ($item eq $symb)) {
7926: $noblock = 1;
7927: last;
7928: }
1.1162 raeburn 7929: }
1.1172.2.66 raeburn 7930: if (ref($cachedblockers{$block}) eq 'HASH') {
7931: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7932: if ($cachedblockers{$block}{'resources'}{$symb}) {
7933: unless (grep(/^\Q$block\E$/,@blockers)) {
7934: push(@blockers,$block);
7935: }
7936: }
7937: }
7938: }
7939: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7940: if ($cachedblockers{$block}{'maps'}{$map}) {
7941: unless (grep(/^\Q$block\E$/,@blockers)) {
7942: push(@blockers,$block);
7943: }
7944: }
1.1162 raeburn 7945: }
7946: }
7947: }
1.1172.2.66 raeburn 7948: return if ($noblock);
7949: return @blockers;
7950: }
1.1162 raeburn 7951: }
7952:
1.1172.2.66 raeburn 7953: # -------------------------------- Deversion and split uri into path an filename
7954:
1.1133 foxr 7955: #
1.1172.2.66 raeburn 7956: # Removes the version from a URI and
1.1133 foxr 7957: # splits it in to its filename and path to the filename.
7958: # Seems like File::Basename could have done this more clearly.
7959: # Parameters:
7960: # $uri - input URI
7961: # Returns:
7962: # Two element list consisting of
7963: # $pathname - the URI up to and excluding the trailing /
7964: # $filename - The part of the URI following the last /
7965: # NOTE:
7966: # Another realization of this is simply:
7967: # use File::Basename;
7968: # ...
7969: # $uri = shift;
7970: # $filename = basename($uri);
7971: # $path = dirname($uri);
7972: # return ($filename, $path);
7973: #
7974: # The implementation below is probably faster however.
7975: #
1.710 albertel 7976: sub split_uri_for_cond {
7977: my $uri=&deversion(&declutter(shift));
7978: my @uriparts=split(/\//,$uri);
7979: my $filename=pop(@uriparts);
7980: my $pathname=join('/',@uriparts);
7981: return ($pathname,$filename);
7982: }
1.232 www 7983: # --------------------------------------------------- Is a resource on the map?
7984:
7985: sub is_on_map {
1.710 albertel 7986: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7987: #Trying to find the conditional for the file
1.620 albertel 7988: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7989: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7990: if ($match) {
1.289 bowersj2 7991: return (1,$1);
7992: } else {
1.434 www 7993: return (0,0);
1.289 bowersj2 7994: }
1.12 www 7995: }
7996:
1.427 www 7997: # --------------------------------------------------------- Get symb from alias
7998:
7999: sub get_symb_from_alias {
8000: my $symb=shift;
8001: my ($map,$resid,$url)=&decode_symb($symb);
8002: # Already is a symb
8003: if ($url) { return $symb; }
8004: # Must be an alias
8005: my $aliassymb='';
8006: my %bighash;
1.620 albertel 8007: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8008: &GDBM_READER(),0640)) {
8009: my $rid=$bighash{'mapalias_'.$symb};
8010: if ($rid) {
8011: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8012: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8013: $resid,$bighash{'src_'.$rid});
1.427 www 8014: }
8015: untie %bighash;
8016: }
8017: return $aliassymb;
8018: }
8019:
1.12 www 8020: # ----------------------------------------------------------------- Define Role
8021:
8022: sub definerole {
8023: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8024: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8025: foreach my $role (split(':',$sysrole)) {
8026: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8027: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8028: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8029: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8030: return "refused:s:$crole&$cqual";
8031: }
8032: }
1.191 harris41 8033: }
1.800 albertel 8034: foreach my $role (split(':',$domrole)) {
8035: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8036: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8037: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8038: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8039: return "refused:d:$crole&$cqual";
8040: }
8041: }
1.191 harris41 8042: }
1.800 albertel 8043: foreach my $role (split(':',$courole)) {
8044: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8045: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8046: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8047: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8048: return "refused:c:$crole&$cqual";
8049: }
8050: }
1.191 harris41 8051: }
1.1172.2.84 raeburn 8052: my $uhome;
8053: if (($uname ne '') && ($udom ne '')) {
8054: $uhome = &homeserver($uname,$udom);
8055: return $uhome if ($uhome eq 'no_host');
8056: } else {
8057: $uname = $env{'user.name'};
8058: $udom = $env{'user.domain'};
8059: $uhome = $env{'user.home'};
8060: }
1.620 albertel 8061: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8062: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8063: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8064: return reply($command,$uhome);
1.12 www 8065: } else {
8066: return 'refused';
8067: }
1.105 harris41 8068: }
8069:
8070: # ---------------- Make a metadata query against the network of library servers
8071:
8072: sub metadata_query {
1.1172.2.33 raeburn 8073: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8074: my %rhash;
1.845 albertel 8075: my %libserv = &all_library();
1.244 matthew 8076: my @server_list = (defined($server_array) ? @$server_array
8077: : keys(%libserv) );
8078: for my $server (@server_list) {
1.1172.2.33 raeburn 8079: my $domains = '';
8080: if (ref($domains_hash) eq 'HASH') {
8081: $domains = $domains_hash->{$server};
8082: }
1.118 harris41 8083: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8084: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8085: $rhash{$server}=$reply;
8086: }
8087: else {
8088: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8089: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8090: $server);
8091: $rhash{$server}=$reply;
8092: }
1.112 harris41 8093: }
1.118 harris41 8094: return \%rhash;
1.240 www 8095: }
8096:
8097: # ----------------------------------------- Send log queries and wait for reply
8098:
8099: sub log_query {
8100: my ($uname,$udom,$query,%filters)=@_;
8101: my $uhome=&homeserver($uname,$udom);
8102: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8103: my $uhost=&hostname($uhome);
1.800 albertel 8104: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8105: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8106: $uhome);
1.479 albertel 8107: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8108: return get_query_reply($queryid);
8109: }
8110:
1.818 raeburn 8111: # -------------------------- Update MySQL table for portfolio file
8112:
8113: sub update_portfolio_table {
1.821 raeburn 8114: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8115: if ($group ne '') {
8116: $file_name =~s /^\Q$group\E//;
8117: }
1.818 raeburn 8118: my $homeserver = &homeserver($uname,$udom);
8119: my $queryid=
1.821 raeburn 8120: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8121: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8122: my $reply = &get_query_reply($queryid);
8123: return $reply;
8124: }
8125:
1.899 raeburn 8126: # -------------------------- Update MySQL allusers table
8127:
8128: sub update_allusers_table {
8129: my ($uname,$udom,$names) = @_;
8130: my $homeserver = &homeserver($uname,$udom);
8131: my $queryid=
8132: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8133: 'lastname='.&escape($names->{'lastname'}).'%%'.
8134: 'firstname='.&escape($names->{'firstname'}).'%%'.
8135: 'middlename='.&escape($names->{'middlename'}).'%%'.
8136: 'generation='.&escape($names->{'generation'}).'%%'.
8137: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8138: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8139: return;
1.899 raeburn 8140: }
8141:
1.508 raeburn 8142: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8143:
8144: sub fetch_enrollment_query {
1.511 raeburn 8145: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8146: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8147: my $maxtries = 1;
1.508 raeburn 8148: if ($context eq 'automated') {
8149: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8150: $sleep = 2;
8151: $loopmax = 100;
1.547 raeburn 8152: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8153: } else {
8154: $homeserver = &homeserver($cnum,$dom);
8155: }
1.838 albertel 8156: my $host=&hostname($homeserver);
1.506 raeburn 8157: my $cmd = '';
1.1000 raeburn 8158: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8159: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8160: }
8161: $cmd =~ s/%%$//;
8162: $cmd = &escape($cmd);
8163: my $query = 'fetchenrollment';
1.620 albertel 8164: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8165: unless ($queryid=~/^\Q$host\E\_/) {
8166: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8167: return 'error: '.$queryid;
8168: }
1.1172.2.93 raeburn 8169: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8170: my $tries = 1;
8171: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8172: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8173: $tries ++;
8174: }
1.526 raeburn 8175: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8176: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8177: } else {
1.901 albertel 8178: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8179: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8180: foreach my $line (@responses) {
8181: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8182: $$replyref{$key} = $value;
8183: }
8184: } else {
1.1117 foxr 8185: my $pathname = LONCAPA::tempdir();
1.800 albertel 8186: foreach my $line (@responses) {
8187: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8188: $$replyref{$key} = $value;
8189: if ($value > 0) {
1.800 albertel 8190: foreach my $item (@{$$affiliatesref{$key}}) {
8191: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8192: my $destname = $pathname.'/'.$filename;
8193: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8194: if ($xml_classlist =~ /^error/) {
8195: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8196: } else {
1.1172.2.93.4 7(raebur 8197:7): if ( open(FILE,">",$destname) ) {
1.506 raeburn 8198: print FILE &unescape($xml_classlist);
8199: close(FILE);
1.526 raeburn 8200: } else {
8201: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8202: }
8203: }
8204: }
8205: }
8206: }
8207: }
8208: return 'ok';
8209: }
8210: return 'error';
8211: }
8212:
1.242 www 8213: sub get_query_reply {
1.1172.2.79 raeburn 8214: my ($queryid,$sleep,$loopmax) = @_;
8215: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8216: $sleep = 0.2;
8217: }
8218: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8219: $loopmax = 100;
8220: }
1.1117 foxr 8221: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8222: my $reply='';
1.1172.2.79 raeburn 8223: for (1..$loopmax) {
8224: sleep($sleep);
1.240 www 8225: if (-e $replyfile.'.end') {
1.1172.2.93.4 7(raebur 8226:7): if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8227: $reply = join('',<$fh>);
8228: close($fh);
1.240 www 8229: } else { return 'error: reply_file_error'; }
1.242 www 8230: return &unescape($reply);
8231: }
1.240 www 8232: }
1.242 www 8233: return 'timeout:'.$queryid;
1.240 www 8234: }
8235:
8236: sub courselog_query {
1.241 www 8237: #
8238: # possible filters:
8239: # url: url or symb
8240: # username
8241: # domain
8242: # action: view, submit, grade
8243: # start: timestamp
8244: # end: timestamp
8245: #
1.240 www 8246: my (%filters)=@_;
1.620 albertel 8247: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8248: if ($filters{'url'}) {
8249: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8250: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8251: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8252: }
1.620 albertel 8253: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8254: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8255: return &log_query($cname,$cdom,'courselog',%filters);
8256: }
8257:
8258: sub userlog_query {
1.858 raeburn 8259: #
8260: # possible filters:
8261: # action: log check role
8262: # start: timestamp
8263: # end: timestamp
8264: #
1.240 www 8265: my ($uname,$udom,%filters)=@_;
8266: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8267: }
8268:
1.506 raeburn 8269: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8270:
8271: sub auto_run {
1.508 raeburn 8272: my ($cnum,$cdom) = @_;
1.876 raeburn 8273: my $response = 0;
8274: my $settings;
8275: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8276: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8277: $settings = $domconfig{'autoenroll'};
8278: if ($settings->{'run'} eq '1') {
8279: $response = 1;
8280: }
8281: } else {
1.934 raeburn 8282: my $homeserver;
8283: if (&is_course($cdom,$cnum)) {
8284: $homeserver = &homeserver($cnum,$cdom);
8285: } else {
8286: $homeserver = &domain($cdom,'primary');
8287: }
8288: if ($homeserver ne 'no_host') {
8289: $response = &reply('autorun:'.$cdom,$homeserver);
8290: }
1.876 raeburn 8291: }
1.506 raeburn 8292: return $response;
8293: }
1.776 albertel 8294:
1.506 raeburn 8295: sub auto_get_sections {
1.508 raeburn 8296: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8297: my $homeserver;
8298: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8299: $homeserver = &homeserver($cnum,$cdom);
8300: }
8301: if (!defined($homeserver)) {
8302: if ($cdom =~ /^$match_domain$/) {
8303: $homeserver = &domain($cdom,'primary');
8304: }
8305: }
8306: my @secs;
8307: if (defined($homeserver)) {
8308: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8309: unless ($response eq 'refused') {
8310: @secs = split(/:/,$response);
8311: }
1.506 raeburn 8312: }
8313: return @secs;
8314: }
1.776 albertel 8315:
1.506 raeburn 8316: sub auto_new_course {
1.1099 raeburn 8317: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8318: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8319: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8320: return $response;
8321: }
1.776 albertel 8322:
1.506 raeburn 8323: sub auto_validate_courseID {
1.508 raeburn 8324: my ($cnum,$cdom,$inst_course_id) = @_;
8325: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8326: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8327: return $response;
8328: }
1.776 albertel 8329:
1.1007 raeburn 8330: sub auto_validate_instcode {
1.1020 raeburn 8331: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8332: my ($homeserver,$response);
8333: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8334: $homeserver = &homeserver($cnum,$cdom);
8335: }
8336: if (!defined($homeserver)) {
8337: if ($cdom =~ /^$match_domain$/) {
8338: $homeserver = &domain($cdom,'primary');
8339: }
8340: }
1.1065 raeburn 8341: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8342: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8343: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8344: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8345: }
8346:
1.506 raeburn 8347: sub auto_create_password {
1.873 raeburn 8348: my ($cnum,$cdom,$authparam,$udom) = @_;
8349: my ($homeserver,$response);
1.506 raeburn 8350: my $create_passwd = 0;
8351: my $authchk = '';
1.873 raeburn 8352: if ($udom =~ /^$match_domain$/) {
8353: $homeserver = &domain($udom,'primary');
8354: }
8355: if ($homeserver eq '') {
8356: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8357: $homeserver = &homeserver($cnum,$cdom);
8358: }
8359: }
8360: if ($homeserver eq '') {
8361: $authchk = 'nodomain';
1.506 raeburn 8362: } else {
1.873 raeburn 8363: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8364: if ($response eq 'refused') {
8365: $authchk = 'refused';
8366: } else {
1.901 albertel 8367: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8368: }
1.506 raeburn 8369: }
8370: return ($authparam,$create_passwd,$authchk);
8371: }
8372:
1.706 raeburn 8373: sub auto_photo_permission {
8374: my ($cnum,$cdom,$students) = @_;
8375: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8376: my ($outcome,$perm_reqd,$conditions) =
8377: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8378: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8379: return (undef,undef);
8380: }
1.706 raeburn 8381: return ($outcome,$perm_reqd,$conditions);
8382: }
8383:
8384: sub auto_checkphotos {
8385: my ($uname,$udom,$pid) = @_;
8386: my $homeserver = &homeserver($uname,$udom);
8387: my ($result,$resulttype);
8388: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8389: &escape($uname).':'.&escape($pid),
8390: $homeserver));
1.709 albertel 8391: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8392: return (undef,undef);
8393: }
1.706 raeburn 8394: if ($outcome) {
8395: ($result,$resulttype) = split(/:/,$outcome);
8396: }
8397: return ($result,$resulttype);
8398: }
8399:
8400: sub auto_photochoice {
8401: my ($cnum,$cdom) = @_;
8402: my $homeserver = &homeserver($cnum,$cdom);
8403: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8404: &escape($cdom),
8405: $homeserver)));
1.709 albertel 8406: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8407: return (undef,undef);
8408: }
1.706 raeburn 8409: return ($update,$comment);
8410: }
8411:
8412: sub auto_photoupdate {
8413: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8414: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8415: my $host=&hostname($homeserver);
1.706 raeburn 8416: my $cmd = '';
8417: my $maxtries = 1;
1.800 albertel 8418: foreach my $affiliate (keys(%{$affiliatesref})) {
8419: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8420: }
8421: $cmd =~ s/%%$//;
8422: $cmd = &escape($cmd);
8423: my $query = 'institutionalphotos';
8424: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8425: unless ($queryid=~/^\Q$host\E\_/) {
8426: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8427: return 'error: '.$queryid;
8428: }
8429: my $reply = &get_query_reply($queryid);
8430: my $tries = 1;
8431: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8432: $reply = &get_query_reply($queryid);
8433: $tries ++;
8434: }
8435: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8436: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8437: } else {
8438: my @responses = split(/:/,$reply);
8439: my $outcome = shift(@responses);
8440: foreach my $item (@responses) {
8441: my ($key,$value) = split(/=/,$item);
8442: $$photo{$key} = $value;
8443: }
8444: return $outcome;
8445: }
8446: return 'error';
8447: }
8448:
1.521 raeburn 8449: sub auto_instcode_format {
1.793 albertel 8450: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8451: $cat_order) = @_;
1.521 raeburn 8452: my $courses = '';
1.772 raeburn 8453: my @homeservers;
1.521 raeburn 8454: if ($caller eq 'global') {
1.841 albertel 8455: my %servers = &get_servers($codedom,'library');
8456: foreach my $tryserver (keys(%servers)) {
8457: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8458: push(@homeservers,$tryserver);
8459: }
1.584 raeburn 8460: }
1.1022 raeburn 8461: } elsif ($caller eq 'requests') {
8462: if ($codedom =~ /^$match_domain$/) {
8463: my $chome = &domain($codedom,'primary');
8464: unless ($chome eq 'no_host') {
8465: push(@homeservers,$chome);
8466: }
8467: }
1.521 raeburn 8468: } else {
1.772 raeburn 8469: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8470: }
1.793 albertel 8471: foreach my $code (keys(%{$instcodes})) {
8472: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8473: }
8474: chop($courses);
1.772 raeburn 8475: my $ok_response = 0;
8476: my $response;
8477: while (@homeservers > 0 && $ok_response == 0) {
8478: my $server = shift(@homeservers);
8479: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8480: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8481: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8482: split(/:/,$response);
1.772 raeburn 8483: %{$codes} = (%{$codes},&str2hash($codes_str));
8484: push(@{$codetitles},&str2array($codetitles_str));
8485: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8486: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8487: $ok_response = 1;
8488: }
8489: }
8490: if ($ok_response) {
1.521 raeburn 8491: return 'ok';
1.772 raeburn 8492: } else {
8493: return $response;
1.521 raeburn 8494: }
8495: }
8496:
1.792 raeburn 8497: sub auto_instcode_defaults {
8498: my ($domain,$returnhash,$code_order) = @_;
8499: my @homeservers;
1.841 albertel 8500:
8501: my %servers = &get_servers($domain,'library');
8502: foreach my $tryserver (keys(%servers)) {
8503: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8504: push(@homeservers,$tryserver);
8505: }
1.792 raeburn 8506: }
1.841 albertel 8507:
1.792 raeburn 8508: my $response;
1.841 albertel 8509: foreach my $server (@homeservers) {
1.792 raeburn 8510: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8511: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8512:
8513: foreach my $pair (split(/\&/,$response)) {
8514: my ($name,$value)=split(/\=/,$pair);
8515: if ($name eq 'code_order') {
8516: @{$code_order} = split(/\&/,&unescape($value));
8517: } else {
8518: $returnhash->{&unescape($name)}=&unescape($value);
8519: }
8520: }
8521: return 'ok';
1.792 raeburn 8522: }
1.841 albertel 8523:
8524: return $response;
1.1003 raeburn 8525: }
8526:
8527: sub auto_possible_instcodes {
1.1007 raeburn 8528: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8529: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8530: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8531: return;
8532: }
1.1003 raeburn 8533: my (@homeservers,$uhome);
8534: if (defined(&domain($domain,'primary'))) {
8535: $uhome=&domain($domain,'primary');
8536: push(@homeservers,&domain($domain,'primary'));
8537: } else {
8538: my %servers = &get_servers($domain,'library');
8539: foreach my $tryserver (keys(%servers)) {
8540: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8541: push(@homeservers,$tryserver);
8542: }
8543: }
8544: }
8545: my $response;
8546: foreach my $server (@homeservers) {
8547: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8548: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8549: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8550: split(':',$response);
8551: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8552: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8553: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8554: my ($name,$value)=split('=',$item);
8555: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8556: }
8557: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8558: my ($name,$value)=split('=',$item);
8559: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8560: }
8561: return 'ok';
8562: }
8563: return $response;
8564: }
1.792 raeburn 8565:
1.1010 raeburn 8566: sub auto_courserequest_checks {
8567: my ($dom) = @_;
1.1020 raeburn 8568: my ($homeserver,%validations);
8569: if ($dom =~ /^$match_domain$/) {
8570: $homeserver = &domain($dom,'primary');
8571: }
8572: unless ($homeserver eq 'no_host') {
8573: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8574: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8575: my @items = split(/&/,$response);
8576: foreach my $item (@items) {
8577: my ($key,$value) = split('=',$item);
8578: $validations{&unescape($key)} = &thaw_unescape($value);
8579: }
8580: }
8581: }
1.1010 raeburn 8582: return %validations;
8583: }
8584:
1.1020 raeburn 8585: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8586: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8587: my ($homeserver,$response);
8588: if ($dom =~ /^$match_domain$/) {
8589: $homeserver = &domain($dom,'primary');
8590: }
1.1172.2.43 raeburn 8591: unless ($homeserver eq 'no_host') {
8592: my $customdata;
8593: if (ref($custominfo) eq 'HASH') {
8594: $customdata = &freeze_escape($custominfo);
8595: }
1.1020 raeburn 8596: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8597: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8598: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8599: $customdata,$homeserver));
1.1020 raeburn 8600: }
8601: return $response;
8602: }
8603:
1.777 albertel 8604: sub auto_validate_class_sec {
1.918 raeburn 8605: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8606: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8607: my $ownerlist;
8608: if (ref($owners) eq 'ARRAY') {
8609: $ownerlist = join(',',@{$owners});
8610: } else {
8611: $ownerlist = $owners;
8612: }
1.773 raeburn 8613: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8614: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8615: return $response;
8616: }
8617:
1.1172.2.93.4 10(raebu 8618:18): sub auto_validate_instclasses {
8619:18): my ($cdom,$cnum,$owners,$classesref) = @_;
8620:18): my ($homeserver,%validations);
8621:18): $homeserver = &homeserver($cnum,$cdom);
8622:18): unless ($homeserver eq 'no_host') {
8623:18): my $ownerlist;
8624:18): if (ref($owners) eq 'ARRAY') {
8625:18): $ownerlist = join(',',@{$owners});
8626:18): } else {
8627:18): $ownerlist = $owners;
8628:18): }
8629:18): if (ref($classesref) eq 'HASH') {
8630:18): my $classes = &freeze_escape($classesref);
8631:18): my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
8632:18): ':'.$cdom.':'.$classes,$homeserver);
8633:18): unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8634:18): my @items = split(/&/,$response);
8635:18): foreach my $item (@items) {
8636:18): my ($key,$value) = split('=',$item);
8637:18): $validations{&unescape($key)} = &thaw_unescape($value);
8638:18): }
8639:18): }
8640:18): }
8641:18): }
8642:18): return %validations;
8643:18): }
8644:18):
1.1172.2.38 raeburn 8645: sub auto_crsreq_update {
8646: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8647: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8648: my ($homeserver,%crsreqresponse);
8649: if ($cdom =~ /^$match_domain$/) {
8650: $homeserver = &domain($cdom,'primary');
8651: }
8652: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8653: my $info;
8654: if (ref($inbound) eq 'HASH') {
8655: $info = &freeze_escape($inbound);
8656: }
8657: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8658: ':'.&escape($action).':'.&escape($ownername).':'.
8659: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8660: &escape($title).':'.&escape($code).':'.
8661: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8662: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8663: my @items = split(/&/,$response);
8664: foreach my $item (@items) {
8665: my ($key,$value) = split('=',$item);
8666: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8667: }
8668: }
8669: }
8670: return \%crsreqresponse;
8671: }
8672:
1.1172.2.78 raeburn 8673: sub auto_export_grades {
8674: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8675: my ($homeserver,%exportresponse);
8676: if ($cdom =~ /^$match_domain$/) {
8677: $homeserver = &domain($cdom,'primary');
8678: }
8679: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8680: my $info;
8681: if (ref($inforef) eq 'HASH') {
8682: $info = &freeze_escape($inforef);
8683: }
8684: if (ref($gradesref) eq 'HASH') {
8685: my $grades = &freeze_escape($gradesref);
8686: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8687: $info.':'.$grades,$homeserver);
8688: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8689: my @items = split(/&/,$response);
8690: foreach my $item (@items) {
8691: my ($key,$value) = split('=',$item);
8692: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8693: }
8694: }
8695: }
8696: }
8697: return \%exportresponse;
8698: }
8699:
1.1172.2.68 raeburn 8700: sub check_instcode_cloning {
8701: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8702: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8703: return;
8704: }
8705: my $canclone;
8706: if (@{$code_order} > 0) {
8707: my $instcoderegexp ='^';
8708: my @clonecodes = split(/\&/,$cloner);
8709: foreach my $item (@{$code_order}) {
8710: if (grep(/^\Q$item\E=/,@clonecodes)) {
8711: foreach my $pair (@clonecodes) {
8712: my ($key,$val) = split(/\=/,$pair,2);
8713: $val = &unescape($val);
8714: if ($key eq $item) {
8715: $instcoderegexp .= '('.$val.')';
8716: last;
8717: }
8718: }
8719: } else {
8720: $instcoderegexp .= $codedefaults->{$item};
8721: }
8722: }
8723: $instcoderegexp .= '$';
8724: my (@from,@to);
8725: eval {
8726: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8727: (@to) = ($clonetocode =~ /$instcoderegexp/);
8728: };
8729: if ((@from > 0) && (@to > 0)) {
8730: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8731: if (!@diffs) {
8732: $canclone = 1;
8733: }
8734: }
8735: }
8736: return $canclone;
8737: }
8738:
8739: sub default_instcode_cloning {
8740: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8741: my (%codedefaults,@code_order,$canclone);
8742: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8743: %codedefaults = %{$codedefaultsref};
8744: @code_order = @{$codeorderref};
8745: } elsif ($clonedom) {
8746: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8747: }
8748: if (($domdefclone) && (@code_order)) {
8749: my @clonecodes = split(/\+/,$domdefclone);
8750: my $instcoderegexp ='^';
8751: foreach my $item (@code_order) {
8752: if (grep(/^\Q$item\E$/,@clonecodes)) {
8753: $instcoderegexp .= '('.$codedefaults{$item}.')';
8754: } else {
8755: $instcoderegexp .= $codedefaults{$item};
8756: }
8757: }
8758: $instcoderegexp .= '$';
8759: my (@from,@to);
8760: eval {
8761: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8762: (@to) = ($clonetocode =~ /$instcoderegexp/);
8763: };
8764: if ((@from > 0) && (@to > 0)) {
8765: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8766: if (!@diffs) {
8767: $canclone = 1;
8768: }
8769: }
8770: }
8771: return $canclone;
8772: }
8773:
1.679 raeburn 8774: # ------------------------------------------------------- Course Group routines
8775:
8776: sub get_coursegroups {
1.809 raeburn 8777: my ($cdom,$cnum,$group,$namespace) = @_;
8778: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8779: }
8780:
1.679 raeburn 8781: sub modify_coursegroup {
8782: my ($cdom,$cnum,$groupsettings) = @_;
8783: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8784: }
8785:
1.809 raeburn 8786: sub toggle_coursegroup_status {
8787: my ($cdom,$cnum,$group,$action) = @_;
8788: my ($from_namespace,$to_namespace);
8789: if ($action eq 'delete') {
8790: $from_namespace = 'coursegroups';
8791: $to_namespace = 'deleted_groups';
8792: } else {
8793: $from_namespace = 'deleted_groups';
8794: $to_namespace = 'coursegroups';
8795: }
8796: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8797: if (my $tmp = &error(%curr_group)) {
8798: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8799: return ('read error',$tmp);
8800: } else {
8801: my %savedsettings = %curr_group;
1.809 raeburn 8802: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8803: my $deloutcome;
8804: if ($result eq 'ok') {
1.809 raeburn 8805: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8806: } else {
8807: return ('write error',$result);
8808: }
8809: if ($deloutcome eq 'ok') {
8810: return 'ok';
8811: } else {
8812: return ('delete error',$deloutcome);
8813: }
8814: }
8815: }
8816:
1.679 raeburn 8817: sub modify_group_roles {
1.957 raeburn 8818: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8819: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8820: my $role = 'gr/'.&escape($userprivs);
8821: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8822: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8823: if ($result eq 'ok') {
8824: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8825: }
1.679 raeburn 8826: return $result;
8827: }
8828:
8829: sub modify_coursegroup_membership {
8830: my ($cdom,$cnum,$membership) = @_;
8831: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8832: return $result;
8833: }
8834:
1.682 raeburn 8835: sub get_active_groups {
8836: my ($udom,$uname,$cdom,$cnum) = @_;
8837: my $now = time;
8838: my %groups = ();
8839: foreach my $key (keys(%env)) {
1.811 albertel 8840: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8841: my ($start,$end) = split(/\./,$env{$key});
8842: if (($end!=0) && ($end<$now)) { next; }
8843: if (($start!=0) && ($start>$now)) { next; }
8844: if ($1 eq $cdom && $2 eq $cnum) {
8845: $groups{$3} = $env{$key} ;
8846: }
8847: }
8848: }
8849: return %groups;
8850: }
8851:
1.683 raeburn 8852: sub get_group_membership {
8853: my ($cdom,$cnum,$group) = @_;
8854: return(&dump('groupmembership',$cdom,$cnum,$group));
8855: }
8856:
8857: sub get_users_groups {
8858: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8859: my @usersgroups;
1.683 raeburn 8860: my $cachetime=1800;
8861:
8862: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8863: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8864: if (defined($cached)) {
1.734 albertel 8865: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8866: } else {
8867: $grouplist = '';
1.816 raeburn 8868: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8869: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8870: my $access_end = $env{'course.'.$courseid.
8871: '.default_enrollment_end_date'};
8872: my $now = time;
8873: foreach my $key (keys(%roleshash)) {
8874: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8875: my $group = $1;
8876: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8877: my $start = $2;
8878: my $end = $1;
8879: if ($start == -1) { next; } # deleted from group
8880: if (($start!=0) && ($start>$now)) { next; }
8881: if (($end!=0) && ($end<$now)) {
8882: if ($access_end && $access_end < $now) {
8883: if ($access_end - $end < 86400) {
8884: push(@usersgroups,$group);
1.733 raeburn 8885: }
8886: }
1.817 raeburn 8887: next;
1.733 raeburn 8888: }
1.817 raeburn 8889: push(@usersgroups,$group);
1.683 raeburn 8890: }
8891: }
8892: }
1.817 raeburn 8893: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8894: $grouplist = join(':',@usersgroups);
8895: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8896: }
1.733 raeburn 8897: return @usersgroups;
1.683 raeburn 8898: }
8899:
8900: sub devalidate_getgroups_cache {
8901: my ($udom,$uname,$cdom,$cnum)=@_;
8902: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8903:
1.683 raeburn 8904: my $hashid="$udom:$uname:$courseid";
8905: &devalidate_cache_new('getgroups',$hashid);
8906: }
8907:
1.12 www 8908: # ------------------------------------------------------------------ Plain Text
8909:
8910: sub plaintext {
1.988 raeburn 8911: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8912: if ($short =~ m{^cr/}) {
1.758 albertel 8913: return (split('/',$short))[-1];
8914: }
1.742 raeburn 8915: if (!defined($cid)) {
8916: $cid = $env{'request.course.id'};
8917: }
8918: my %rolenames = (
1.1008 raeburn 8919: Course => 'std',
8920: Community => 'alt1',
1.742 raeburn 8921: );
1.1037 raeburn 8922: if ($cid ne '') {
8923: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8924: unless ($forcedefault) {
8925: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8926: &Apache::lonlocal::mt_escape(\$roletext);
8927: return &Apache::lonlocal::mt($roletext);
8928: }
8929: }
8930: }
8931: if ((defined($type)) && (defined($rolenames{$type})) &&
8932: (defined($rolenames{$type})) &&
8933: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8934: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8935: } elsif ($cid ne '') {
8936: my $crstype = $env{'course.'.$cid.'.type'};
8937: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8938: (defined($prp{$short}{$rolenames{$crstype}}))) {
8939: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8940: }
1.742 raeburn 8941: }
1.1037 raeburn 8942: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8943: }
8944:
8945: # ----------------------------------------------------------------- Assign Role
8946:
8947: sub assignrole {
1.957 raeburn 8948: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8949: $context)=@_;
1.21 www 8950: my $mrole;
8951: if ($role =~ /^cr\//) {
1.393 www 8952: my $cwosec=$url;
1.811 albertel 8953: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8954: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8955: my $refused = 1;
8956: if ($context eq 'requestcourses') {
8957: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8958: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8959: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8960: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8961: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8962: if ($crsenv{'internal.courseowner'} eq
8963: $env{'user.name'}.':'.$env{'user.domain'}) {
8964: $refused = '';
8965: }
8966: }
8967: }
8968: }
8969: }
8970: if ($refused) {
8971: &logthis('Refused custom assignrole: '.
8972: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8973: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8974: return 'refused';
8975: }
1.104 www 8976: }
1.21 www 8977: $mrole='cr';
1.678 raeburn 8978: } elsif ($role =~ /^gr\//) {
8979: my $cwogrp=$url;
1.811 albertel 8980: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8981: unless (&allowed('mdg',$cwogrp)) {
8982: &logthis('Refused group assignrole: '.
8983: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8984: $env{'user.name'}.' at '.$env{'user.domain'});
8985: return 'refused';
8986: }
8987: $mrole='gr';
1.21 www 8988: } else {
1.82 www 8989: my $cwosec=$url;
1.811 albertel 8990: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8991: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8992: my $refused;
8993: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8994: if (!(&allowed('c'.$role,$url))) {
8995: $refused = 1;
8996: }
8997: } else {
8998: $refused = 1;
8999: }
1.947 raeburn 9000: if ($refused) {
1.1045 raeburn 9001: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9002: if (!$selfenroll && $context eq 'course') {
9003: my %crsenv;
9004: if ($role eq 'cc' || $role eq 'co') {
9005: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9006: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9007: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9008: if ($crsenv{'internal.courseowner'} eq
9009: $env{'user.name'}.':'.$env{'user.domain'}) {
9010: $refused = '';
9011: }
9012: }
9013: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9014: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9015: if ($crsenv{'internal.courseowner'} eq
9016: $env{'user.name'}.':'.$env{'user.domain'}) {
9017: $refused = '';
9018: }
9019: }
9020: }
9021: }
9022: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9023: $refused = '';
1.1017 raeburn 9024: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9025: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9026: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9027: my $wrongcc;
9028: if ($cnum =~ /^$match_community$/) {
9029: $wrongcc = 1 if ($role eq 'cc');
9030: } else {
9031: $wrongcc = 1 if ($role eq 'co');
9032: }
9033: unless ($wrongcc) {
9034: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9035: if ($crsenv{'internal.courseowner'} eq
9036: $env{'user.name'}.':'.$env{'user.domain'}) {
9037: $refused = '';
9038: }
1.1017 raeburn 9039: }
9040: }
1.1172.2.9 raeburn 9041: } elsif ($context eq 'requestauthor') {
9042: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9043: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9044: if ($env{'environment.requestauthor'} eq 'automatic') {
9045: $refused = '';
9046: } else {
9047: my %domdefaults = &get_domain_defaults($udom);
9048: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9049: my $checkbystatus;
9050: if ($env{'user.adv'}) {
9051: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9052: if ($disposition eq 'automatic') {
9053: $refused = '';
9054: } elsif ($disposition eq '') {
9055: $checkbystatus = 1;
9056: }
9057: } else {
9058: $checkbystatus = 1;
9059: }
9060: if ($checkbystatus) {
9061: if ($env{'environment.inststatus'}) {
9062: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9063: foreach my $type (@inststatuses) {
9064: if (($type ne '') &&
9065: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9066: $refused = '';
9067: }
9068: }
9069: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9070: $refused = '';
9071: }
9072: }
9073: }
9074: }
9075: }
1.1017 raeburn 9076: }
9077: if ($refused) {
1.947 raeburn 9078: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9079: ' '.$role.' '.$end.' '.$start.' by '.
9080: $env{'user.name'}.' at '.$env{'user.domain'});
9081: return 'refused';
9082: }
1.932 raeburn 9083: }
1.1131 raeburn 9084: } elsif ($role eq 'au') {
9085: if ($url ne '/'.$udom.'/') {
9086: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9087: ' to assign author role for '.$uname.':'.$udom.
9088: ' in domain: '.$url.' refused (wrong domain).');
9089: return 'refused';
9090: }
1.104 www 9091: }
1.21 www 9092: $mrole=$role;
9093: }
1.620 albertel 9094: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9095: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9096: if ($end) { $command.='_'.$end; }
1.21 www 9097: if ($start) {
9098: if ($end) {
1.81 www 9099: $command.='_'.$start;
1.21 www 9100: } else {
1.81 www 9101: $command.='_0_'.$start;
1.21 www 9102: }
9103: }
1.739 raeburn 9104: my $origstart = $start;
9105: my $origend = $end;
1.957 raeburn 9106: my $delflag;
1.357 www 9107: # actually delete
9108: if ($deleteflag) {
1.373 www 9109: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9110: # modify command to delete the role
1.620 albertel 9111: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9112: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9113: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9114: # set start and finish to negative values for userrolelog
9115: $start=-1;
9116: $end=-1;
1.957 raeburn 9117: $delflag = 1;
1.357 www 9118: }
9119: }
9120: # send command
1.349 www 9121: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9122: # log new user role if status is ok
1.349 www 9123: if ($answer eq 'ok') {
1.663 raeburn 9124: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9125: if (($role eq 'cc') || ($role eq 'in') ||
9126: ($role eq 'ep') || ($role eq 'ad') ||
9127: ($role eq 'ta') || ($role eq 'st') ||
9128: ($role=~/^cr/) || ($role eq 'gr') ||
9129: ($role eq 'co')) {
1.1172.2.13 raeburn 9130: # for course roles, perform group memberships changes triggered by role change.
9131: unless ($role =~ /^gr/) {
9132: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9133: $origstart,$selfenroll,$context);
9134: }
1.1172.2.9 raeburn 9135: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9136: $selfenroll,$context);
9137: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9138: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9139: ($role eq 'da')) {
1.1172.2.9 raeburn 9140: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9141: $context);
9142: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9143: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9144: $context);
9145: }
1.1053 raeburn 9146: if ($role eq 'cc') {
9147: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9148: }
1.349 www 9149: }
9150: return $answer;
1.169 harris41 9151: }
9152:
1.1053 raeburn 9153: sub autoupdate_coowners {
9154: my ($url,$end,$start,$uname,$udom) = @_;
9155: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9156: if (($cdom ne '') && ($cnum ne '')) {
9157: my $now = time;
9158: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9159: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9160: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9161: my $instcode = $coursehash{'internal.coursecode'};
9162: if ($instcode ne '') {
1.1056 raeburn 9163: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9164: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9165: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9166: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9167: if ($result eq 'valid') {
9168: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9169: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9170: push(@newcoowners,$coowner);
9171: }
9172: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9173: push(@newcoowners,$uname.':'.$udom);
9174: }
9175: @newcoowners = sort(@newcoowners);
9176: } else {
9177: push(@newcoowners,$uname.':'.$udom);
9178: }
9179: } else {
9180: if ($coursehash{'internal.co-owners'}) {
9181: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9182: unless ($coowner eq $uname.':'.$udom) {
9183: push(@newcoowners,$coowner);
9184: }
9185: }
9186: unless (@newcoowners > 0) {
9187: $delcoowners = 1;
9188: $coowners = '';
9189: }
9190: }
9191: }
9192: if (@newcoowners || $delcoowners) {
9193: &store_coowners($cdom,$cnum,$coursehash{'home'},
9194: $delcoowners,@newcoowners);
9195: }
9196: }
9197: }
9198: }
9199: }
9200: }
9201: }
9202:
9203: sub store_coowners {
9204: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9205: my $cid = $cdom.'_'.$cnum;
9206: my ($coowners,$delresult,$putresult);
9207: if (@newcoowners) {
9208: $coowners = join(',',@newcoowners);
9209: my %coownershash = (
9210: 'internal.co-owners' => $coowners,
9211: );
9212: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9213: if ($putresult eq 'ok') {
9214: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9215: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9216: }
9217: }
9218: }
9219: if ($delcoowners) {
9220: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9221: if ($delresult eq 'ok') {
9222: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9223: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9224: }
9225: }
9226: }
9227: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9228: my %crsinfo =
9229: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9230: if (ref($crsinfo{$cid}) eq 'HASH') {
9231: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9232: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9233: }
9234: }
9235: }
9236:
1.169 harris41 9237: # -------------------------------------------------- Modify user authentication
1.197 www 9238: # Overrides without validation
9239:
1.169 harris41 9240: sub modifyuserauth {
9241: my ($udom,$uname,$umode,$upass)=@_;
9242: my $uhome=&homeserver($uname,$udom);
1.197 www 9243: unless (&allowed('mau',$udom)) { return 'refused'; }
9244: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9245: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9246: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9247: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9248: &escape($upass),$uhome);
1.620 albertel 9249: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9250: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9251: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9252: &log($udom,,$uname,$uhome,
1.620 albertel 9253: 'Authentication changed by '.$env{'user.domain'}.', '.
9254: $env{'user.name'}.', '.$umode.
1.197 www 9255: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9256: unless ($reply eq 'ok') {
1.197 www 9257: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9258: return 'error: '.$reply;
9259: }
1.170 harris41 9260: return 'ok';
1.80 www 9261: }
9262:
1.81 www 9263: # --------------------------------------------------------------- Modify a user
1.80 www 9264:
1.81 www 9265: sub modifyuser {
1.206 matthew 9266: my ($udom, $uname, $uid,
9267: $umode, $upass, $first,
9268: $middle, $last, $gene,
1.1058 raeburn 9269: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9270: $udom= &LONCAPA::clean_domain($udom);
9271: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9272: my $showcandelete = 'none';
9273: if (ref($candelete) eq 'ARRAY') {
9274: if (@{$candelete} > 0) {
9275: $showcandelete = join(', ',@{$candelete});
9276: }
9277: }
1.81 www 9278: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9279: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9280: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9281: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9282: ' desiredhome not specified').
1.620 albertel 9283: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9284: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9285: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9286: my $newuser;
9287: if ($uhome eq 'no_host') {
9288: $newuser = 1;
9289: }
1.80 www 9290: # ----------------------------------------------------------------- Create User
1.406 albertel 9291: if (($uhome eq 'no_host') &&
9292: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9293: my $unhome='';
1.844 albertel 9294: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9295: $unhome = $desiredhome;
1.620 albertel 9296: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9297: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9298: } else { # load balancing routine for determining $unhome
1.81 www 9299: my $loadm=10000000;
1.841 albertel 9300: my %servers = &get_servers($udom,'library');
9301: foreach my $tryserver (keys(%servers)) {
9302: my $answer=reply('load',$tryserver);
9303: if (($answer=~/\d+/) && ($answer<$loadm)) {
9304: $loadm=$answer;
9305: $unhome=$tryserver;
9306: }
1.80 www 9307: }
9308: }
9309: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9310: return 'error: unable to find a home server for '.$uname.
9311: ' in domain '.$udom;
1.80 www 9312: }
9313: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9314: &escape($upass),$unhome);
9315: unless ($reply eq 'ok') {
9316: return 'error: '.$reply;
9317: }
1.230 stredwic 9318: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9319: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9320: return 'error: unable verify users home machine.';
1.80 www 9321: }
1.209 matthew 9322: } # End of creation of new user
1.80 www 9323: # ---------------------------------------------------------------------- Add ID
9324: if ($uid) {
9325: $uid=~tr/A-Z/a-z/;
9326: my %uidhash=&idrget($udom,$uname);
1.196 www 9327: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9328: && (!$forceid)) {
1.80 www 9329: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9330: return 'error: user id "'.$uid.'" does not match '.
9331: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9332: }
9333: } else {
9334: &idput($udom,($uname => $uid));
9335: }
9336: }
9337: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9338: my @tmp=&get('environment',
1.899 raeburn 9339: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9340: 'permanentemail','inststatus'],
1.134 albertel 9341: $udom,$uname);
1.1075 raeburn 9342: my (%names,%oldnames);
1.313 matthew 9343: if ($tmp[0] =~ m/^error:.*/) {
9344: %names=();
9345: } else {
9346: %names = @tmp;
1.1075 raeburn 9347: %oldnames = %names;
1.313 matthew 9348: }
1.388 www 9349: #
1.1058 raeburn 9350: # If name, email and/or uid are blank (e.g., because an uploaded file
9351: # of users did not contain them), do not overwrite existing values
9352: # unless field is in $candelete array ref.
9353: #
9354:
9355: my @fields = ('firstname','middlename','lastname','generation',
9356: 'permanentemail','id');
9357: my %newvalues;
9358: if (ref($candelete) eq 'ARRAY') {
9359: foreach my $field (@fields) {
9360: if (grep(/^\Q$field\E$/,@{$candelete})) {
9361: if ($field eq 'firstname') {
9362: $names{$field} = $first;
9363: } elsif ($field eq 'middlename') {
9364: $names{$field} = $middle;
9365: } elsif ($field eq 'lastname') {
9366: $names{$field} = $last;
9367: } elsif ($field eq 'generation') {
9368: $names{$field} = $gene;
9369: } elsif ($field eq 'permanentemail') {
9370: $names{$field} = $email;
9371: } elsif ($field eq 'id') {
9372: $names{$field} = $uid;
9373: }
9374: }
9375: }
9376: }
1.388 www 9377: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9378: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9379: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9380: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9381: if ($email) {
9382: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9383: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9384: }
1.899 raeburn 9385: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9386: if (defined($inststatus)) {
9387: $names{'inststatus'} = '';
9388: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9389: if (ref($usertypes) eq 'HASH') {
9390: my @okstatuses;
9391: foreach my $item (split(/:/,$inststatus)) {
9392: if (defined($usertypes->{$item})) {
9393: push(@okstatuses,$item);
9394: }
9395: }
9396: if (@okstatuses) {
9397: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9398: }
9399: }
9400: }
1.1075 raeburn 9401: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9402: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9403: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9404: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9405: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9406: } else {
9407: $logmsg .= ' during self creation';
9408: }
1.1075 raeburn 9409: my $changed;
9410: if ($newuser) {
9411: $changed = 1;
9412: } else {
9413: foreach my $field (@fields) {
9414: if ($names{$field} ne $oldnames{$field}) {
9415: $changed = 1;
9416: last;
9417: }
9418: }
9419: }
9420: unless ($changed) {
9421: $logmsg = 'No changes in user information needed for: '.$logmsg;
9422: &logthis($logmsg);
9423: return 'ok';
9424: }
9425: my $reply = &put('environment', \%names, $udom,$uname);
9426: if ($reply ne 'ok') {
9427: return 'error: '.$reply;
9428: }
1.1087 raeburn 9429: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9430: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9431: }
1.1075 raeburn 9432: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9433: &devalidate_cache_new('namescache',$uname.':'.$udom);
9434: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9435: &logthis($logmsg);
1.134 albertel 9436: return 'ok';
1.80 www 9437: }
9438:
1.81 www 9439: # -------------------------------------------------------------- Modify student
1.80 www 9440:
1.81 www 9441: sub modifystudent {
9442: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9443: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9444: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9445: if (!$cid) {
1.620 albertel 9446: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9447: return 'not_in_class';
9448: }
1.80 www 9449: }
9450: # --------------------------------------------------------------- Make the user
1.81 www 9451: my $reply=&modifyuser
1.209 matthew 9452: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9453: $desiredhome,$email,$inststatus);
1.80 www 9454: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9455: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9456: # student's environment
1.297 matthew 9457: $uid = undef if (!$forceid);
1.455 albertel 9458: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9459: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9460: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9461: return $reply;
9462: }
9463:
9464: sub modify_student_enrollment {
1.1172.2.23 raeburn 9465: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9466: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9467: my ($cdom,$cnum,$chome);
9468: if (!$cid) {
1.620 albertel 9469: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9470: return 'not_in_class';
9471: }
1.620 albertel 9472: $cdom=$env{'course.'.$cid.'.domain'};
9473: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9474: } else {
9475: ($cdom,$cnum)=split(/_/,$cid);
9476: }
1.620 albertel 9477: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9478: if (!$chome) {
1.457 raeburn 9479: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9480: }
1.455 albertel 9481: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9482: # Make sure the user exists
1.81 www 9483: my $uhome=&homeserver($uname,$udom);
9484: if (($uhome eq '') || ($uhome eq 'no_host')) {
9485: return 'error: no such user';
9486: }
1.297 matthew 9487: # Get student data if we were not given enough information
9488: if (!defined($first) || $first eq '' ||
9489: !defined($last) || $last eq '' ||
9490: !defined($uid) || $uid eq '' ||
9491: !defined($middle) || $middle eq '' ||
9492: !defined($gene) || $gene eq '') {
1.294 matthew 9493: # They did not supply us with enough data to enroll the student, so
9494: # we need to pick up more information.
1.297 matthew 9495: my %tmp = &get('environment',
1.294 matthew 9496: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9497: ,$udom,$uname);
9498:
1.800 albertel 9499: #foreach my $key (keys(%tmp)) {
9500: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9501: #}
1.294 matthew 9502: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9503: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9504: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9505: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9506: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9507: }
1.556 albertel 9508: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9509: my $user = "$uname:$udom";
9510: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9511: my $reply=cput('classlist',
1.1148 raeburn 9512: {$user =>
1.1172.2.76 raeburn 9513: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9514: $cdom,$cnum);
1.1148 raeburn 9515: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9516: &devalidate_getsection_cache($udom,$uname,$cid);
9517: } else {
1.81 www 9518: return 'error: '.$reply;
9519: }
1.297 matthew 9520: # Add student role to user
1.83 www 9521: my $uurl='/'.$cid;
1.81 www 9522: $uurl=~s/\_/\//g;
9523: if ($usec) {
9524: $uurl.='/'.$usec;
9525: }
1.1148 raeburn 9526: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9527: $selfenroll,$context);
9528: if ($result ne 'ok') {
9529: if ($old_entry{$user} ne '') {
9530: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9531: } else {
9532: $reply = &del('classlist',[$user],$cdom,$cnum);
9533: }
9534: }
9535: return $result;
1.21 www 9536: }
9537:
1.556 albertel 9538: sub format_name {
9539: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9540: my $name;
9541: if ($first ne 'lastname') {
9542: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9543: } else {
9544: if ($lastname=~/\S/) {
9545: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9546: $name=~s/\s+,/,/;
9547: } else {
9548: $name.= $firstname.' '.$middlename.' '.$generation;
9549: }
9550: }
9551: $name=~s/^\s+//;
9552: $name=~s/\s+$//;
9553: $name=~s/\s+/ /g;
9554: return $name;
9555: }
9556:
1.84 www 9557: # ------------------------------------------------- Write to course preferences
9558:
9559: sub writecoursepref {
9560: my ($courseid,%prefs)=@_;
9561: $courseid=~s/^\///;
9562: $courseid=~s/\_/\//g;
9563: my ($cdomain,$cnum)=split(/\//,$courseid);
9564: my $chome=homeserver($cnum,$cdomain);
9565: if (($chome eq '') || ($chome eq 'no_host')) {
9566: return 'error: no such course';
9567: }
9568: my $cstring='';
1.800 albertel 9569: foreach my $pref (keys(%prefs)) {
9570: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9571: }
1.84 www 9572: $cstring=~s/\&$//;
9573: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9574: }
9575:
9576: # ---------------------------------------------------------- Make/modify course
9577:
9578: sub createcourse {
1.741 raeburn 9579: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9580: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9581: $url=&declutter($url);
9582: my $cid='';
1.1028 raeburn 9583: if ($context eq 'requestcourses') {
9584: my $can_create = 0;
9585: my ($ownername,$ownerdom) = split(':',$course_owner);
9586: if ($udom eq $ownerdom) {
9587: if (&usertools_access($ownername,$ownerdom,$category,undef,
9588: $context)) {
9589: $can_create = 1;
9590: }
9591: } else {
9592: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9593: $category);
9594: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9595: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9596: if (@curr > 0) {
9597: my @options = qw(approval validate autolimit);
9598: my $optregex = join('|',@options);
9599: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9600: $can_create = 1;
9601: }
9602: }
9603: }
9604: }
9605: if ($can_create) {
9606: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9607: unless (&allowed('ccc',$udom)) {
9608: return 'refused';
9609: }
1.1017 raeburn 9610: }
9611: } else {
9612: return 'refused';
9613: }
1.1028 raeburn 9614: } elsif (!&allowed('ccc',$udom)) {
9615: return 'refused';
1.84 www 9616: }
1.1011 raeburn 9617: # --------------------------------------------------------------- Get Unique ID
9618: my $uname;
9619: if ($cnum =~ /^$match_courseid$/) {
9620: my $chome=&homeserver($cnum,$udom,'true');
9621: if (($chome eq '') || ($chome eq 'no_host')) {
9622: $uname = $cnum;
9623: } else {
1.1038 raeburn 9624: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9625: }
9626: } else {
1.1038 raeburn 9627: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9628: }
9629: return $uname if ($uname =~ /^error/);
9630: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9631: if (!defined($course_server)) {
9632: if (defined(&domain($udom,'primary'))) {
9633: $course_server = &domain($udom,'primary');
9634: } else {
9635: $course_server = $env{'user.home'};
9636: }
9637: }
9638: my %host_servers =
9639: &Apache::lonnet::get_servers($udom,'library');
9640: unless ($host_servers{$course_server}) {
9641: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9642: }
1.84 www 9643: # ------------------------------------------------------------- Make the course
9644: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9645: $course_server);
1.84 www 9646: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9647: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9648: if (($uhome eq '') || ($uhome eq 'no_host')) {
9649: return 'error: no such course';
9650: }
1.271 www 9651: # ----------------------------------------------------------------- Course made
1.516 raeburn 9652: # log existence
1.1029 raeburn 9653: my $now = time;
1.918 raeburn 9654: my $newcourse = {
9655: $udom.'_'.$uname => {
1.921 raeburn 9656: description => $description,
9657: inst_code => $inst_code,
9658: owner => $course_owner,
9659: type => $crstype,
1.1029 raeburn 9660: creator => $env{'user.name'}.':'.
9661: $env{'user.domain'},
9662: created => $now,
9663: context => $context,
1.918 raeburn 9664: },
9665: };
1.921 raeburn 9666: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9667: # set toplevel url
1.271 www 9668: my $topurl=$url;
9669: unless ($nonstandard) {
9670: # ------------------------------------------ For standard courses, make top url
9671: my $mapurl=&clutter($url);
1.278 www 9672: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9673: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9674: <map>
9675: <resource id="1" type="start"></resource>
9676: <resource id="2" src="$mapurl"></resource>
9677: <resource id="3" type="finish"></resource>
9678: <link index="1" from="1" to="2"></link>
9679: <link index="2" from="2" to="3"></link>
9680: </map>
9681: ENDINITMAP
9682: $topurl=&declutter(
1.638 albertel 9683: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9684: );
9685: }
9686: # ----------------------------------------------------------- Write preferences
1.84 www 9687: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9688: ('description' => $description,
9689: 'url' => $topurl,
9690: 'internal.creator' => $env{'user.name'}.':'.
9691: $env{'user.domain'},
9692: 'internal.created' => $now,
9693: 'internal.creationcontext' => $context)
9694: );
1.84 www 9695: return '/'.$udom.'/'.$uname;
9696: }
9697:
1.1011 raeburn 9698: # ------------------------------------------------------------------- Create ID
9699: sub generate_coursenum {
1.1038 raeburn 9700: my ($udom,$crstype) = @_;
1.1011 raeburn 9701: my $domdesc = &domain($udom);
9702: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9703: my $first;
9704: if ($crstype eq 'Community') {
9705: $first = '0';
9706: } else {
9707: $first = int(1+rand(9));
9708: }
9709: my $uname=$first.
1.1011 raeburn 9710: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9711: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9712: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9713: # ----------------------------------------------- Make sure that does not exist
9714: my $uhome=&homeserver($uname,$udom,'true');
9715: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9716: if ($crstype eq 'Community') {
9717: $first = '0';
9718: } else {
9719: $first = int(1+rand(9));
9720: }
9721: $uname=$first.
1.1011 raeburn 9722: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9723: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9724: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9725: $uhome=&homeserver($uname,$udom,'true');
9726: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9727: return 'error: unable to generate unique course-ID';
9728: }
9729: }
9730: return $uname;
9731: }
9732:
1.813 albertel 9733: sub is_course {
1.1167 droeschl 9734: my ($cdom, $cnum) = scalar(@_) == 1 ?
9735: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9736:
9737: return unless $cdom and $cnum;
9738:
9739: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9740: '.');
9741:
1.1172.2.23 raeburn 9742: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9743: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9744: }
9745:
1.1015 raeburn 9746: sub store_userdata {
9747: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9748: my $result;
1.1016 raeburn 9749: if ($datakey ne '') {
1.1013 raeburn 9750: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9751: if ($udom eq '' || $uname eq '') {
9752: $udom = $env{'user.domain'};
9753: $uname = $env{'user.name'};
9754: }
9755: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9756: if (($uhome eq '') || ($uhome eq 'no_host')) {
9757: $result = 'error: no_host';
9758: } else {
9759: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9760: $storehash->{'host'} = $perlvar{'lonHostID'};
9761:
9762: my $namevalue='';
9763: foreach my $key (keys(%{$storehash})) {
9764: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9765: }
9766: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9767: unless ($namespace eq 'courserequests') {
9768: $datakey = &escape($datakey);
9769: }
1.1105 raeburn 9770: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9771: $namevalue,$uhome);
1.1013 raeburn 9772: }
9773: } else {
9774: $result = 'error: data to store was not a hash reference';
9775: }
9776: } else {
9777: $result= 'error: invalid requestkey';
9778: }
9779: return $result;
9780: }
9781:
1.21 www 9782: # ---------------------------------------------------------- Assign Custom Role
9783:
9784: sub assigncustomrole {
1.957 raeburn 9785: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9786: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9787: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9788: }
9789:
9790: # ----------------------------------------------------------------- Revoke Role
9791:
9792: sub revokerole {
1.957 raeburn 9793: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9794: my $now=time;
1.965 raeburn 9795: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9796: }
9797:
9798: # ---------------------------------------------------------- Revoke Custom Role
9799:
9800: sub revokecustomrole {
1.957 raeburn 9801: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9802: my $now=time;
1.357 www 9803: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9804: $deleteflag,$selfenroll,$context);
1.17 www 9805: }
9806:
1.533 banghart 9807: # ------------------------------------------------------------ Disk usage
1.535 albertel 9808: sub diskusage {
1.955 raeburn 9809: my ($udom,$uname,$directorypath,$getpropath)=@_;
9810: $directorypath =~ s/\/$//;
9811: my $listing=&reply('du2:'.&escape($directorypath).':'
9812: .&escape($getpropath).':'.&escape($uname).':'
9813: .&escape($udom),homeserver($uname,$udom));
9814: if ($listing eq 'unknown_cmd') {
9815: if ($getpropath) {
9816: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9817: }
9818: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9819: }
1.514 albertel 9820: return $listing;
1.512 banghart 9821: }
9822:
1.566 banghart 9823: sub is_locked {
1.1096 raeburn 9824: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9825: my @check;
9826: my $is_locked;
1.1093 raeburn 9827: push (@check,$file_name);
1.613 albertel 9828: my %locked = &get('file_permissions',\@check,
1.620 albertel 9829: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9830: my ($tmp)=keys(%locked);
9831: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9832:
1.566 banghart 9833: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9834: $is_locked = 'false';
9835: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9836: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9837: $is_locked = 'true';
1.1096 raeburn 9838: if (ref($which) eq 'ARRAY') {
9839: push(@{$which},$entry);
9840: } else {
9841: last;
9842: }
1.745 raeburn 9843: }
9844: }
1.566 banghart 9845: } else {
9846: $is_locked = 'false';
9847: }
1.1093 raeburn 9848: return $is_locked;
1.566 banghart 9849: }
9850:
1.759 albertel 9851: sub declutter_portfile {
9852: my ($file) = @_;
1.833 albertel 9853: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9854: return $file;
9855: }
9856:
1.559 banghart 9857: # ------------------------------------------------------------- Mark as Read Only
9858:
9859: sub mark_as_readonly {
9860: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9861: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9862: my ($tmp)=keys(%current_permissions);
9863: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9864: foreach my $file (@{$files}) {
1.759 albertel 9865: $file = &declutter_portfile($file);
1.561 banghart 9866: push(@{$current_permissions{$file}},$what);
1.559 banghart 9867: }
1.613 albertel 9868: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9869: return;
9870: }
9871:
1.572 banghart 9872: # ------------------------------------------------------------Save Selected Files
9873:
9874: sub save_selected_files {
9875: my ($user, $path, @files) = @_;
9876: my $filename = $user."savedfiles";
1.573 banghart 9877: my @other_files = &files_not_in_path($user, $path);
1.1172.2.93.4 7(raebur 9878:7): open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 9879: foreach my $file (@files) {
1.620 albertel 9880: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9881: }
9882: foreach my $file (@other_files) {
1.574 banghart 9883: print (OUT $file."\n");
1.572 banghart 9884: }
1.574 banghart 9885: close (OUT);
1.572 banghart 9886: return 'ok';
9887: }
9888:
1.574 banghart 9889: sub clear_selected_files {
9890: my ($user) = @_;
9891: my $filename = $user."savedfiles";
1.1172.2.93.4 7(raebur 9892:7): open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 9893: print (OUT undef);
9894: close (OUT);
9895: return ("ok");
9896: }
9897:
1.572 banghart 9898: sub files_in_path {
9899: my ($user, $path) = @_;
9900: my $filename = $user."savedfiles";
9901: my %return_files;
1.1172.2.93.4 7(raebur 9902:7): open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 9903: while (my $line_in = <IN>) {
1.574 banghart 9904: chomp ($line_in);
9905: my @paths_and_file = split (m!/!, $line_in);
9906: my $file_part = pop (@paths_and_file);
9907: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9908: $path_part.='/';
9909: my $path_and_file = $path_part.$file_part;
9910: if ($path_part eq $path) {
9911: $return_files{$file_part}= 'selected';
9912: }
9913: }
1.574 banghart 9914: close (IN);
9915: return (\%return_files);
1.572 banghart 9916: }
9917:
9918: # called in portfolio select mode, to show files selected NOT in current directory
9919: sub files_not_in_path {
9920: my ($user, $path) = @_;
9921: my $filename = $user."savedfiles";
9922: my @return_files;
9923: my $path_part;
1.1172.2.93.4 7(raebur 9924:7): open(IN,'<',LONCAPA::tempdir().$filename);
1.800 albertel 9925: while (my $line = <IN>) {
1.572 banghart 9926: #ok, I know it's clunky, but I want it to work
1.800 albertel 9927: my @paths_and_file = split(m|/|, $line);
9928: my $file_part = pop(@paths_and_file);
9929: chomp($file_part);
9930: my $path_part = join('/', @paths_and_file);
1.572 banghart 9931: $path_part .= '/';
9932: my $path_and_file = $path_part.$file_part;
9933: if ($path_part ne $path) {
1.800 albertel 9934: push(@return_files, ($path_and_file));
1.572 banghart 9935: }
9936: }
1.800 albertel 9937: close(OUT);
1.574 banghart 9938: return (@return_files);
1.572 banghart 9939: }
9940:
1.745 raeburn 9941: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9942:
1.745 raeburn 9943: sub get_portfile_permissions {
9944: my ($domain,$user) = @_;
1.613 albertel 9945: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9946: my ($tmp)=keys(%current_permissions);
9947: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9948: return \%current_permissions;
9949: }
9950:
9951: #---------------------------------------------Get portfolio file access controls
9952:
1.749 raeburn 9953: sub get_access_controls {
1.745 raeburn 9954: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9955: my %access;
9956: my $real_file = $file;
9957: $file =~ s/\.meta$//;
1.745 raeburn 9958: if (defined($file)) {
1.749 raeburn 9959: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9960: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9961: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9962: }
9963: }
1.745 raeburn 9964: } else {
1.749 raeburn 9965: foreach my $key (keys(%{$current_permissions})) {
9966: if ($key =~ /\0accesscontrol$/) {
9967: if (defined($group)) {
9968: if ($key !~ m-^\Q$group\E/-) {
9969: next;
9970: }
9971: }
9972: my ($fullpath) = split(/\0/,$key);
9973: if (ref($$current_permissions{$key}) eq 'HASH') {
9974: foreach my $control (keys(%{$$current_permissions{$key}})) {
9975: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9976: }
9977: }
9978: }
9979: }
9980: }
9981: return %access;
9982: }
9983:
9984: sub modify_access_controls {
9985: my ($file_name,$changes,$domain,$user)=@_;
9986: my ($outcome,$deloutcome);
9987: my %store_permissions;
9988: my %new_values;
9989: my %new_control;
9990: my %translation;
9991: my @deletions = ();
9992: my $now = time;
9993: if (exists($$changes{'activate'})) {
9994: if (ref($$changes{'activate'}) eq 'HASH') {
9995: my @newitems = sort(keys(%{$$changes{'activate'}}));
9996: my $numnew = scalar(@newitems);
9997: for (my $i=0; $i<$numnew; $i++) {
9998: my $newkey = $newitems[$i];
9999: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10000: if ($newkey =~ /^\d+:/) {
10001: $newkey =~ s/^(\d+)/$newid/;
10002: $translation{$1} = $newid;
10003: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10004: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10005: $translation{$1} = $newid;
10006: }
1.749 raeburn 10007: $new_values{$file_name."\0".$newkey} =
10008: $$changes{'activate'}{$newitems[$i]};
10009: $new_control{$newkey} = $now;
10010: }
10011: }
10012: }
10013: my %todelete;
10014: my %changed_items;
10015: foreach my $action ('delete','update') {
10016: if (exists($$changes{$action})) {
10017: if (ref($$changes{$action}) eq 'HASH') {
10018: foreach my $key (keys(%{$$changes{$action}})) {
10019: my ($itemnum) = ($key =~ /^([^:]+):/);
10020: if ($action eq 'delete') {
10021: $todelete{$itemnum} = 1;
10022: } else {
10023: $changed_items{$itemnum} = $key;
10024: }
10025: }
1.745 raeburn 10026: }
10027: }
1.749 raeburn 10028: }
10029: # get lock on access controls for file.
10030: my $lockhash = {
10031: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10032: ':'.$env{'user.domain'},
10033: };
10034: my $tries = 0;
10035: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10036:
1.1172.2.79 raeburn 10037: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10038: $tries ++;
1.1172.2.79 raeburn 10039: sleep(0.1);
1.749 raeburn 10040: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10041: }
10042: if ($gotlock eq 'ok') {
10043: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10044: my ($tmp)=keys(%curr_permissions);
10045: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10046: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10047: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10048: if (ref($curr_controls) eq 'HASH') {
10049: foreach my $control_item (keys(%{$curr_controls})) {
10050: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10051: if (defined($todelete{$itemnum})) {
10052: push(@deletions,$file_name."\0".$control_item);
10053: } else {
10054: if (defined($changed_items{$itemnum})) {
10055: $new_control{$changed_items{$itemnum}} = $now;
10056: push(@deletions,$file_name."\0".$control_item);
10057: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10058: } else {
10059: $new_control{$control_item} = $$curr_controls{$control_item};
10060: }
10061: }
1.745 raeburn 10062: }
10063: }
10064: }
1.970 raeburn 10065: my ($group);
10066: if (&is_course($domain,$user)) {
10067: ($group,my $file) = split(/\//,$file_name,2);
10068: }
1.749 raeburn 10069: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10070: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10071: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10072: # remove lock
10073: my @del_lock = ($file_name."\0".'locked_access_records');
10074: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10075: my $sqlresult =
1.970 raeburn 10076: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10077: $group);
1.749 raeburn 10078: } else {
10079: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10080: }
1.749 raeburn 10081: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10082: }
10083:
1.827 raeburn 10084: sub make_public_indefinitely {
10085: my ($requrl) = @_;
10086: my $now = time;
10087: my $action = 'activate';
10088: my $aclnum = 0;
10089: if (&is_portfolio_url($requrl)) {
10090: my (undef,$udom,$unum,$file_name,$group) =
10091: &parse_portfolio_url($requrl);
10092: my $current_perms = &get_portfile_permissions($udom,$unum);
10093: my %access_controls = &get_access_controls($current_perms,
10094: $group,$file_name);
10095: foreach my $key (keys(%{$access_controls{$file_name}})) {
10096: my ($num,$scope,$end,$start) =
10097: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10098: if ($scope eq 'public') {
10099: if ($start <= $now && $end == 0) {
10100: $action = 'none';
10101: } else {
10102: $action = 'update';
10103: $aclnum = $num;
10104: }
10105: last;
10106: }
10107: }
10108: if ($action eq 'none') {
10109: return 'ok';
10110: } else {
10111: my %changes;
10112: my $newend = 0;
10113: my $newstart = $now;
10114: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10115: $changes{$action}{$newkey} = {
10116: type => 'public',
10117: time => {
10118: start => $newstart,
10119: end => $newend,
10120: },
10121: };
10122: my ($outcome,$deloutcome,$new_values,$translation) =
10123: &modify_access_controls($file_name,\%changes,$udom,$unum);
10124: return $outcome;
10125: }
10126: } else {
10127: return 'invalid';
10128: }
10129: }
10130:
1.745 raeburn 10131: #------------------------------------------------------Get Marked as Read Only
10132:
10133: sub get_marked_as_readonly {
10134: my ($domain,$user,$what,$group) = @_;
10135: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10136: my @readonly_files;
1.629 banghart 10137: my $cmp1=$what;
10138: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10139: while (my ($file_name,$value) = each(%{$current_permissions})) {
10140: if (defined($group)) {
10141: if ($file_name !~ m-^\Q$group\E/-) {
10142: next;
10143: }
10144: }
1.561 banghart 10145: if (ref($value) eq "ARRAY"){
10146: foreach my $stored_what (@{$value}) {
1.629 banghart 10147: my $cmp2=$stored_what;
1.759 albertel 10148: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10149: $cmp2=join('',@{$stored_what});
1.745 raeburn 10150: }
1.629 banghart 10151: if ($cmp1 eq $cmp2) {
1.561 banghart 10152: push(@readonly_files, $file_name);
1.745 raeburn 10153: last;
1.563 banghart 10154: } elsif (!defined($what)) {
10155: push(@readonly_files, $file_name);
1.745 raeburn 10156: last;
1.561 banghart 10157: }
10158: }
1.745 raeburn 10159: }
1.561 banghart 10160: }
10161: return @readonly_files;
10162: }
1.577 banghart 10163: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10164:
1.577 banghart 10165: sub get_marked_as_readonly_hash {
1.745 raeburn 10166: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10167: my %readonly_files;
1.745 raeburn 10168: while (my ($file_name,$value) = each(%{$current_permissions})) {
10169: if (defined($group)) {
10170: if ($file_name !~ m-^\Q$group\E/-) {
10171: next;
10172: }
10173: }
1.577 banghart 10174: if (ref($value) eq "ARRAY"){
10175: foreach my $stored_what (@{$value}) {
1.745 raeburn 10176: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10177: foreach my $lock_descriptor(@{$stored_what}) {
10178: if ($lock_descriptor eq 'graded') {
10179: $readonly_files{$file_name} = 'graded';
10180: } elsif ($lock_descriptor eq 'handback') {
10181: $readonly_files{$file_name} = 'handback';
10182: } else {
10183: if (!exists($readonly_files{$file_name})) {
10184: $readonly_files{$file_name} = 'locked';
10185: }
10186: }
1.745 raeburn 10187: }
1.750 banghart 10188: }
1.577 banghart 10189: }
10190: }
10191: }
10192: return %readonly_files;
10193: }
1.559 banghart 10194: # ------------------------------------------------------------ Unmark as Read Only
10195:
10196: sub unmark_as_readonly {
1.629 banghart 10197: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10198: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10199: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10200: $file_name = &declutter_portfile($file_name);
1.634 albertel 10201: my $symb_crs = $what;
10202: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10203: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10204: my ($tmp)=keys(%current_permissions);
10205: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10206: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10207: foreach my $file (@readonly_files) {
1.759 albertel 10208: my $clean_file = &declutter_portfile($file);
10209: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10210: my $current_locks = $current_permissions{$file};
1.563 banghart 10211: my @new_locks;
10212: my @del_keys;
10213: if (ref($current_locks) eq "ARRAY"){
10214: foreach my $locker (@{$current_locks}) {
1.632 albertel 10215: my $compare=$locker;
1.749 raeburn 10216: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10217: $compare=join('',@{$locker});
1.746 raeburn 10218: if ($compare ne $symb_crs) {
10219: push(@new_locks, $locker);
10220: }
1.563 banghart 10221: }
10222: }
1.650 albertel 10223: if (scalar(@new_locks) > 0) {
1.563 banghart 10224: $current_permissions{$file} = \@new_locks;
10225: } else {
10226: push(@del_keys, $file);
1.613 albertel 10227: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10228: delete($current_permissions{$file});
1.563 banghart 10229: }
10230: }
1.561 banghart 10231: }
1.613 albertel 10232: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10233: return;
10234: }
1.512 banghart 10235:
1.17 www 10236: # ------------------------------------------------------------ Directory lister
10237:
10238: sub dirlist {
1.955 raeburn 10239: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10240: $uri=~s/^\///;
10241: $uri=~s/\/$//;
1.253 stredwic 10242: my ($udom, $uname);
1.955 raeburn 10243: if ($getuserdir) {
1.253 stredwic 10244: $udom = $userdomain;
10245: $uname = $username;
1.955 raeburn 10246: } else {
10247: (undef,$udom,$uname)=split(/\//,$uri);
10248: if(defined($userdomain)) {
10249: $udom = $userdomain;
10250: }
10251: if(defined($username)) {
10252: $uname = $username;
10253: }
1.253 stredwic 10254: }
1.955 raeburn 10255: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10256:
1.955 raeburn 10257: $dirRoot = $perlvar{'lonDocRoot'};
10258: if (defined($getpropath)) {
10259: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10260: $dirRoot =~ s/\/$//;
1.955 raeburn 10261: } elsif (defined($getuserdir)) {
10262: my $subdir=$uname.'__';
10263: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10264: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10265: ."/$udom/$subdir/$uname";
10266: } elsif (defined($alternateRoot)) {
10267: $dirRoot = $alternateRoot;
1.751 banghart 10268: }
1.253 stredwic 10269:
10270: if($udom) {
10271: if($uname) {
1.1135 raeburn 10272: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10273: if ($uhome eq 'no_host') {
10274: return ([],'no_host');
10275: }
1.955 raeburn 10276: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10277: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10278: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10279: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10280: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10281: } else {
10282: @listing_results = map { &unescape($_); } split(/:/,$listing);
10283: }
1.605 matthew 10284: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10285: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10286: @listing_results = split(/:/,$listing);
10287: } else {
10288: @listing_results = map { &unescape($_); } split(/:/,$listing);
10289: }
1.1135 raeburn 10290: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10291: ($listing eq 'rejected') || ($listing eq 'refused') ||
10292: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10293: return ([],$listing);
10294: } else {
10295: return (\@listing_results);
1.1135 raeburn 10296: }
1.955 raeburn 10297: } elsif(!$alternateRoot) {
1.1136 raeburn 10298: my (%allusers,%listerror);
1.841 albertel 10299: my %servers = &get_servers($udom,'library');
1.955 raeburn 10300: foreach my $tryserver (keys(%servers)) {
10301: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10302: &escape($udom),$tryserver);
10303: if ($listing eq 'unknown_cmd') {
10304: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10305: $udom, $tryserver);
10306: } else {
10307: @listing_results = map { &unescape($_); } split(/:/,$listing);
10308: }
1.841 albertel 10309: if ($listing eq 'unknown_cmd') {
10310: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10311: $udom, $tryserver);
10312: @listing_results = split(/:/,$listing);
10313: } else {
10314: @listing_results =
10315: map { &unescape($_); } split(/:/,$listing);
10316: }
1.1136 raeburn 10317: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10318: ($listing eq 'rejected') || ($listing eq 'refused') ||
10319: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10320: $listerror{$tryserver} = $listing;
10321: } else {
1.841 albertel 10322: foreach my $line (@listing_results) {
10323: my ($entry) = split(/&/,$line,2);
10324: $allusers{$entry} = 1;
10325: }
10326: }
1.253 stredwic 10327: }
1.1136 raeburn 10328: my @alluserslist=();
1.800 albertel 10329: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10330: push(@alluserslist,$user.'&user');
1.253 stredwic 10331: }
1.1172.2.80 raeburn 10332: if (!%listerror) {
10333: # no errors
10334: return (\@alluserslist);
10335: } elsif (scalar(keys(%servers)) == 1) {
10336: # one library server, one error
10337: my ($key) = keys(%listerror);
10338: return (\@alluserslist, $listerror{$key});
10339: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10340: # con_lost indicates that we might miss data from at least one
10341: # library server
10342: return (\@alluserslist, 'con_lost');
10343: } else {
10344: # multiple library servers and no con_lost -> data should be
10345: # complete.
10346: return (\@alluserslist);
10347: }
10348:
1.253 stredwic 10349: } else {
1.1136 raeburn 10350: return ([],'missing username');
1.253 stredwic 10351: }
1.955 raeburn 10352: } elsif(!defined($getpropath)) {
1.1136 raeburn 10353: my $path = $perlvar{'lonDocRoot'}.'/res/';
10354: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10355: return (\@all_domains);
1.955 raeburn 10356: } else {
1.1136 raeburn 10357: return ([],'missing domain');
1.275 stredwic 10358: }
10359: }
10360:
10361: # --------------------------------------------- GetFileTimestamp
10362: # This function utilizes dirlist and returns the date stamp for
10363: # when it was last modified. It will also return an error of -1
10364: # if an error occurs
10365:
10366: sub GetFileTimestamp {
1.955 raeburn 10367: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10368: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10369: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10370: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10371: undef,$getuserdir);
10372: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10373: return -1;
10374: }
10375: if (ref($fileref) eq 'ARRAY') {
10376: my @stats = split('&',$fileref->[0]);
1.375 matthew 10377: # @stats contains first the filename, then the stat output
10378: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10379: } else {
10380: return -1;
1.253 stredwic 10381: }
1.26 www 10382: }
10383:
1.712 albertel 10384: sub stat_file {
10385: my ($uri) = @_;
1.787 albertel 10386: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10387:
1.955 raeburn 10388: my ($udom,$uname,$file);
1.712 albertel 10389: if ($uri =~ m-^/(uploaded|editupload)/-) {
10390: ($udom,$uname,$file) =
1.811 albertel 10391: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10392: $file = 'userfiles/'.$file;
10393: }
10394: if ($uri =~ m-^/res/-) {
10395: ($udom,$uname) =
1.807 albertel 10396: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10397: $file = $uri;
10398: }
10399:
10400: if (!$udom || !$uname || !$file) {
10401: # unable to handle the uri
10402: return ();
10403: }
1.956 raeburn 10404: my $getpropath;
10405: if ($file =~ /^userfiles\//) {
10406: $getpropath = 1;
10407: }
1.1136 raeburn 10408: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10409: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10410: return ();
10411: } else {
10412: if (ref($listref) eq 'ARRAY') {
10413: my @stats = split('&',$listref->[0]);
10414: shift(@stats); #filename is first
10415: return @stats;
10416: }
1.712 albertel 10417: }
10418: return ();
10419: }
10420:
1.26 www 10421: # -------------------------------------------------------- Value of a Condition
10422:
1.713 albertel 10423: # gets the value of a specific preevaluated condition
10424: # stored in the string $env{user.state.<cid>}
10425: # or looks up a condition reference in the bighash and if if hasn't
10426: # already been evaluated recurses into docondval to get the value of
10427: # the condition, then memoizing it to
10428: # $env{user.state.<cid>.<condition>}
1.40 www 10429: sub directcondval {
10430: my $number=shift;
1.620 albertel 10431: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10432: &Apache::lonuserstate::evalstate();
10433: }
1.713 albertel 10434: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10435: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10436: } elsif ($number =~ /^_/) {
10437: my $sub_condition;
10438: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10439: &GDBM_READER(),0640)) {
10440: $sub_condition=$bighash{'conditions'.$number};
10441: untie(%bighash);
10442: }
10443: my $value = &docondval($sub_condition);
1.949 raeburn 10444: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10445: return $value;
10446: }
1.620 albertel 10447: if ($env{'user.state.'.$env{'request.course.id'}}) {
10448: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10449: } else {
10450: return 2;
10451: }
10452: }
10453:
1.713 albertel 10454: # get the collection of conditions for this resource
1.26 www 10455: sub condval {
10456: my $condidx=shift;
1.54 www 10457: my $allpathcond='';
1.713 albertel 10458: foreach my $cond (split(/\|/,$condidx)) {
10459: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10460: $allpathcond.=
10461: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10462: }
1.191 harris41 10463: }
1.54 www 10464: $allpathcond=~s/\|$//;
1.713 albertel 10465: return &docondval($allpathcond);
10466: }
10467:
10468: #evaluates an expression of conditions
10469: sub docondval {
10470: my ($allpathcond) = @_;
10471: my $result=0;
10472: if ($env{'request.course.id'}
10473: && defined($allpathcond)) {
10474: my $operand='|';
10475: my @stack;
10476: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10477: if ($chunk eq '(') {
10478: push @stack,($operand,$result);
10479: } elsif ($chunk eq ')') {
10480: my $before=pop @stack;
10481: if (pop @stack eq '&') {
10482: $result=$result>$before?$before:$result;
10483: } else {
10484: $result=$result>$before?$result:$before;
10485: }
10486: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10487: $operand=$chunk;
10488: } else {
10489: my $new=directcondval($chunk);
10490: if ($operand eq '&') {
10491: $result=$result>$new?$new:$result;
10492: } else {
10493: $result=$result>$new?$result:$new;
10494: }
10495: }
10496: }
1.26 www 10497: }
10498: return $result;
1.421 albertel 10499: }
10500:
10501: # ---------------------------------------------------- Devalidate courseresdata
10502:
10503: sub devalidatecourseresdata {
10504: my ($coursenum,$coursedomain)=@_;
10505: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10506: &devalidate_cache_new('courseres',$hashid);
1.28 www 10507: }
10508:
1.763 www 10509:
1.200 www 10510: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10511: #
10512: # Parameters:
10513: # $coursenum - Number of the course.
10514: # $coursedomain - Domain at which the course was created.
10515: # Returns:
10516: # A hash of the course parameters along (I think) with timestamps
10517: # and version info.
1.877 foxr 10518:
1.624 albertel 10519: sub get_courseresdata {
10520: my ($coursenum,$coursedomain)=@_;
1.200 www 10521: my $coursehom=&homeserver($coursenum,$coursedomain);
10522: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10523: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10524: my %dumpreply;
1.417 albertel 10525: unless (defined($cached)) {
1.624 albertel 10526: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10527: $result=\%dumpreply;
1.251 albertel 10528: my ($tmp) = keys(%dumpreply);
10529: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10530: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10531: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10532: return $tmp;
1.416 albertel 10533: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10534: $result=undef;
1.599 albertel 10535: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10536: }
10537: }
1.624 albertel 10538: return $result;
10539: }
10540:
1.633 albertel 10541: sub devalidateuserresdata {
10542: my ($uname,$udom)=@_;
10543: my $hashid="$udom:$uname";
10544: &devalidate_cache_new('userres',$hashid);
10545: }
10546:
1.624 albertel 10547: sub get_userresdata {
10548: my ($uname,$udom)=@_;
10549: #most student don\'t have any data set, check if there is some data
10550: if (&EXT_cache_status($udom,$uname)) { return undef; }
10551:
10552: my $hashid="$udom:$uname";
10553: my ($result,$cached)=&is_cached_new('userres',$hashid);
10554: if (!defined($cached)) {
10555: my %resourcedata=&dump('resourcedata',$udom,$uname);
10556: $result=\%resourcedata;
10557: &do_cache_new('userres',$hashid,$result,600);
10558: }
10559: my ($tmp)=keys(%$result);
10560: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10561: return $result;
10562: }
10563: #error 2 occurs when the .db doesn't exist
10564: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10565: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10566: &logthis("<font color=\"blue\">WARNING:".
10567: " Trying to get resource data for ".
10568: $uname." at ".$udom.": ".
10569: $tmp."</font>");
10570: }
1.624 albertel 10571: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10572: #&EXT_cache_set($udom,$uname);
10573: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10574: undef($tmp); # not really an error so don't send it back
1.624 albertel 10575: }
10576: return $tmp;
10577: }
1.879 foxr 10578: #----------------------------------------------- resdata - return resource data
10579: # Purpose:
10580: # Return resource data for either users or for a course.
10581: # Parameters:
10582: # $name - Course/user name.
10583: # $domain - Name of the domain the user/course is registered on.
1.1172.2.93.4 1(raebur 10584:7): # $type - Type of thing $name is (must be 'course' or 'user')
1.879 foxr 10585: # @which - Array of names of resources desired.
10586: # Returns:
10587: # The value of the first reasource in @which that is found in the
10588: # resource hash.
10589: # Exceptional Conditions:
10590: # If the $type passed in is not valid (not the string 'course' or
10591: # 'user', an undefined reference is returned.
10592: # If none of the resources are found, an undef is returned
1.624 albertel 10593: sub resdata {
10594: my ($name,$domain,$type,@which)=@_;
10595: my $result;
10596: if ($type eq 'course') {
10597: $result=&get_courseresdata($name,$domain);
10598: } elsif ($type eq 'user') {
10599: $result=&get_userresdata($name,$domain);
10600: }
10601: if (!ref($result)) { return $result; }
1.251 albertel 10602: foreach my $item (@which) {
1.1172.2.93.4 1(raebur 10603:7): if (ref($item) eq 'ARRAY') {
10604:7): if (defined($result->{$item->[0]})) {
10605:7): return [$result->{$item->[0]},$item->[1]];
10606:7): }
10607:7): }
1.250 albertel 10608: }
1.291 albertel 10609: return undef;
1.200 www 10610: }
10611:
1.1172.2.93.4 2(raebur 10612:7): sub get_domain_ltitools {
10613:7): my ($cdom) = @_;
10614:7): my %ltitools;
10615:7): my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10616:7): if (defined($cached)) {
10617:7): if (ref($result) eq 'HASH') {
10618:7): %ltitools = %{$result};
10619:7): }
10620:7): } else {
10621:7): my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10622:7): if (ref($domconfig{'ltitools'}) eq 'HASH') {
10623:7): %ltitools = %{$domconfig{'ltitools'}};
10624:7): my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
10625:7): if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
10626:7): foreach my $id (keys(%ltitools)) {
10627:7): if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
10628:7): foreach my $item ('key','secret') {
10629:7): $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
10630:7): }
10631:7): }
10632:7): }
10633:7): }
10634:7): }
10635:7): my $cachetime = 24*60*60;
10636:7): &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10637:7): }
10638:7): return %ltitools;
10639:7): }
10640:7):
1.1172.2.31 raeburn 10641: sub get_numsuppfiles {
10642: my ($cnum,$cdom,$ignorecache)=@_;
10643: my $hashid=$cnum.':'.$cdom;
10644: my ($suppcount,$cached);
10645: unless ($ignorecache) {
10646: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10647: }
10648: unless (defined($cached)) {
10649: my $chome=&homeserver($cnum,$cdom);
10650: unless ($chome eq 'no_host') {
10651: ($suppcount,my $errors) = (0,0);
10652: my $suppmap = 'supplemental.sequence';
10653: ($suppcount,$errors) =
10654: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10655: }
10656: &do_cache_new('suppcount',$hashid,$suppcount,600);
10657: }
10658: return $suppcount;
10659: }
10660:
1.379 matthew 10661: #
10662: # EXT resource caching routines
10663: #
10664:
10665: sub clear_EXT_cache_status {
1.383 albertel 10666: &delenv('cache.EXT.');
1.379 matthew 10667: }
10668:
10669: sub EXT_cache_status {
10670: my ($target_domain,$target_user) = @_;
1.383 albertel 10671: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10672: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10673: # We know already the user has no data
10674: return 1;
10675: } else {
10676: return 0;
10677: }
10678: }
10679:
10680: sub EXT_cache_set {
10681: my ($target_domain,$target_user) = @_;
1.383 albertel 10682: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10683: #&appenv({$cachename => time});
1.379 matthew 10684: }
10685:
1.28 www 10686: # --------------------------------------------------------- Value of a Variable
1.58 www 10687: sub EXT {
1.715 albertel 10688:
1.1172.2.28 raeburn 10689: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10690: unless ($varname) { return ''; }
1.218 albertel 10691: #get real user name/domain, courseid and symb
10692: my $courseid;
1.359 albertel 10693: my $publicuser;
1.427 www 10694: if ($symbparm) {
10695: $symbparm=&get_symb_from_alias($symbparm);
10696: }
1.218 albertel 10697: if (!($uname && $udom)) {
1.790 albertel 10698: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10699: if (!$symbparm) { $symbparm=$cursymb; }
10700: } else {
1.620 albertel 10701: $courseid=$env{'request.course.id'};
1.218 albertel 10702: }
1.48 www 10703: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10704: my $rest;
1.320 albertel 10705: if (defined($therest[0])) {
1.48 www 10706: $rest=join('.',@therest);
10707: } else {
10708: $rest='';
10709: }
1.320 albertel 10710:
1.57 www 10711: my $qualifierrest=$qualifier;
10712: if ($rest) { $qualifierrest.='.'.$rest; }
10713: my $spacequalifierrest=$space;
10714: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10715: if ($realm eq 'user') {
1.48 www 10716: # --------------------------------------------------------------- user.resource
10717: if ($space eq 'resource') {
1.651 albertel 10718: if ( (defined($Apache::lonhomework::parsing_a_problem)
10719: || defined($Apache::lonhomework::parsing_a_task))
10720: &&
1.744 albertel 10721: ($symbparm eq &symbread()) ) {
10722: # if we are in the middle of processing the resource the
10723: # get the value we are planning on committing
10724: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10725: return $Apache::lonhomework::results{$qualifierrest};
10726: } else {
10727: return $Apache::lonhomework::history{$qualifierrest};
10728: }
1.335 albertel 10729: } else {
1.359 albertel 10730: my %restored;
1.620 albertel 10731: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10732: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10733: } else {
10734: %restored=&restore($symbparm,$courseid,$udom,$uname);
10735: }
1.335 albertel 10736: return $restored{$qualifierrest};
10737: }
1.48 www 10738: # ----------------------------------------------------------------- user.access
10739: } elsif ($space eq 'access') {
1.218 albertel 10740: # FIXME - not supporting calls for a specific user
1.48 www 10741: return &allowed($qualifier,$rest);
10742: # ------------------------------------------ user.preferences, user.environment
10743: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10744: if (($uname eq $env{'user.name'}) &&
10745: ($udom eq $env{'user.domain'})) {
10746: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10747: } else {
1.359 albertel 10748: my %returnhash;
10749: if (!$publicuser) {
10750: %returnhash=&userenvironment($udom,$uname,
10751: $qualifierrest);
10752: }
1.218 albertel 10753: return $returnhash{$qualifierrest};
10754: }
1.48 www 10755: # ----------------------------------------------------------------- user.course
10756: } elsif ($space eq 'course') {
1.218 albertel 10757: # FIXME - not supporting calls for a specific user
1.620 albertel 10758: return $env{join('.',('request.course',$qualifier))};
1.48 www 10759: # ------------------------------------------------------------------- user.role
10760: } elsif ($space eq 'role') {
1.218 albertel 10761: # FIXME - not supporting calls for a specific user
1.620 albertel 10762: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10763: if ($qualifier eq 'value') {
10764: return $role;
10765: } elsif ($qualifier eq 'extent') {
10766: return $where;
10767: }
10768: # ----------------------------------------------------------------- user.domain
10769: } elsif ($space eq 'domain') {
1.218 albertel 10770: return $udom;
1.48 www 10771: # ------------------------------------------------------------------- user.name
10772: } elsif ($space eq 'name') {
1.218 albertel 10773: return $uname;
1.48 www 10774: # ---------------------------------------------------- Any other user namespace
1.29 www 10775: } else {
1.359 albertel 10776: my %reply;
10777: if (!$publicuser) {
10778: %reply=&get($space,[$qualifierrest],$udom,$uname);
10779: }
10780: return $reply{$qualifierrest};
1.48 www 10781: }
1.236 www 10782: } elsif ($realm eq 'query') {
10783: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10784: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10785: [$spacequalifierrest]);
1.620 albertel 10786: return $env{'form.'.$spacequalifierrest};
1.236 www 10787: } elsif ($realm eq 'request') {
1.48 www 10788: # ------------------------------------------------------------- request.browser
10789: if ($space eq 'browser') {
1.1145 bisitz 10790: return $env{'browser.'.$qualifier};
1.57 www 10791: # ------------------------------------------------------------ request.filename
10792: } else {
1.620 albertel 10793: return $env{'request.'.$spacequalifierrest};
1.29 www 10794: }
1.28 www 10795: } elsif ($realm eq 'course') {
1.48 www 10796: # ---------------------------------------------------------- course.description
1.620 albertel 10797: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10798: } elsif ($realm eq 'resource') {
1.165 www 10799:
1.620 albertel 10800: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10801: if (!$symbparm) { $symbparm=&symbread(); }
10802: }
1.693 albertel 10803:
1.1172.2.30 raeburn 10804: if ($qualifier eq '') {
10805: if ($space eq 'title') {
10806: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10807: return &gettitle($symbparm);
10808: }
1.693 albertel 10809:
1.1172.2.30 raeburn 10810: if ($space eq 'map') {
10811: my ($map) = &decode_symb($symbparm);
10812: return &symbread($map);
10813: }
10814: if ($space eq 'maptitle') {
10815: my ($map) = &decode_symb($symbparm);
10816: return &gettitle($map);
10817: }
10818: if ($space eq 'filename') {
10819: if ($symbparm) {
10820: return &clutter((&decode_symb($symbparm))[2]);
10821: }
10822: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10823: }
1.1172.2.30 raeburn 10824:
10825: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10826: if ($space eq 'visibleparts') {
10827: my $navmap = Apache::lonnavmaps::navmap->new();
10828: my $item;
10829: if (ref($navmap)) {
10830: my $res = $navmap->getBySymb($symbparm);
10831: my $parts = $res->parts();
10832: if (ref($parts) eq 'ARRAY') {
10833: $item = join(',',@{$parts});
10834: }
10835: undef($navmap);
10836: }
10837: return $item;
10838: }
10839: }
10840: }
1.693 albertel 10841:
10842: my ($section, $group, @groups);
1.593 albertel 10843: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10844: if (($courseid eq '') && ($cid)) {
10845: $courseid = $cid;
10846: }
10847: if (($symbparm && $courseid) &&
10848: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10849:
1.218 albertel 10850: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10851:
1.60 www 10852: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10853: my $symbp=$symbparm;
1.735 albertel 10854: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10855:
10856: my $symbparm=$symbp.'.'.$spacequalifierrest;
10857: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10858:
1.620 albertel 10859: if (($env{'user.name'} eq $uname) &&
10860: ($env{'user.domain'} eq $udom)) {
10861: $section=$env{'request.course.sec'};
1.733 raeburn 10862: @groups = split(/:/,$env{'request.course.groups'});
10863: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10864: } else {
1.539 albertel 10865: if (! defined($usection)) {
1.551 albertel 10866: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10867: } else {
10868: $section = $usection;
10869: }
1.733 raeburn 10870: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10871: }
10872:
10873: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10874: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10875: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10876:
1.593 albertel 10877: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10878: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10879: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10880:
1.60 www 10881: # ----------------------------------------------------------- first, check user
1.624 albertel 10882:
10883: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10884: ([$courselevelr,'resource'],
10885: [$courselevelm,'map' ],
10886: [$courselevel, 'course' ]));
1.931 albertel 10887: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10888:
1.594 albertel 10889: # ------------------------------------------------ second, check some of course
1.684 raeburn 10890: my $coursereply;
1.691 raeburn 10891: if (@groups > 0) {
10892: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10893: $mapparm,$spacequalifierrest);
1.927 albertel 10894: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10895: }
1.96 www 10896:
1.684 raeburn 10897: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10898: $env{'course.'.$courseid.'.domain'},
10899: 'course',
10900: ([$seclevelr, 'resource'],
10901: [$seclevelm, 'map' ],
10902: [$seclevel, 'course' ],
10903: [$courselevelr,'resource']));
10904: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10905:
1.60 www 10906: # ------------------------------------------------------ third, check map parms
1.218 albertel 10907: my %parmhash=();
10908: my $thisparm='';
10909: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10910: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10911: &GDBM_READER(),0640)) {
1.218 albertel 10912: $thisparm=$parmhash{$symbparm};
10913: untie(%parmhash);
10914: }
1.927 albertel 10915: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10916: }
1.594 albertel 10917: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10918:
1.218 albertel 10919: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10920: my $filename;
10921: if (!$symbparm) { $symbparm=&symbread(); }
10922: if ($symbparm) {
1.409 www 10923: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10924: } else {
1.620 albertel 10925: $filename=$env{'request.filename'};
1.282 albertel 10926: }
10927: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10928: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10929: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10930: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10931:
1.927 albertel 10932: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10933: if ($symbparm && defined($courseid) &&
1.620 albertel 10934: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10935: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10936: $env{'course.'.$courseid.'.domain'},
10937: 'course',
1.927 albertel 10938: ([$courselevelm,'map' ],
10939: [$courselevel, 'course']));
10940: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10941: }
1.145 www 10942: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10943: unless ($space eq '0') {
1.336 albertel 10944: my @parts=split(/_/,$space);
10945: my $id=pop(@parts);
10946: my $part=join('_',@parts);
10947: if ($part eq '') { $part='0'; }
1.927 albertel 10948: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10949: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10950: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10951: }
1.395 albertel 10952: if ($recurse) { return undef; }
10953: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10954: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10955: # ---------------------------------------------------- Any other user namespace
10956: } elsif ($realm eq 'environment') {
10957: # ----------------------------------------------------------------- environment
1.620 albertel 10958: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10959: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10960: } else {
1.770 albertel 10961: if ($uname eq 'anonymous' && $udom eq '') {
10962: return '';
10963: }
1.219 albertel 10964: my %returnhash=&userenvironment($udom,$uname,
10965: $spacequalifierrest);
10966: return $returnhash{$spacequalifierrest};
10967: }
1.28 www 10968: } elsif ($realm eq 'system') {
1.48 www 10969: # ----------------------------------------------------------------- system.time
10970: if ($space eq 'time') {
10971: return time;
10972: }
1.696 albertel 10973: } elsif ($realm eq 'server') {
10974: # ----------------------------------------------------------------- system.time
10975: if ($space eq 'name') {
10976: return $ENV{'SERVER_NAME'};
10977: }
1.28 www 10978: }
1.48 www 10979: return '';
1.61 www 10980: }
10981:
1.927 albertel 10982: sub get_reply {
10983: my ($reply_value) = @_;
1.940 raeburn 10984: if (ref($reply_value) eq 'ARRAY') {
10985: if (wantarray) {
10986: return @$reply_value;
10987: }
10988: return $reply_value->[0];
10989: } else {
10990: return $reply_value;
1.927 albertel 10991: }
10992: }
10993:
1.691 raeburn 10994: sub check_group_parms {
10995: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10996: my @groupitems = ();
10997: my $resultitem;
1.927 albertel 10998: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10999: foreach my $group (@{$groups}) {
11000: foreach my $level (@levels) {
1.927 albertel 11001: my $item = $courseid.'.['.$group.'].'.$level->[0];
11002: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11003: }
11004: }
11005: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11006: $env{'course.'.$courseid.'.domain'},
11007: 'course',@groupitems);
11008: return $coursereply;
11009: }
11010:
11011: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11012: my ($courseid,@groups) = @_;
11013: @groups = sort(@groups);
1.691 raeburn 11014: return @groups;
11015: }
11016:
1.395 albertel 11017: sub packages_tab_default {
11018: my ($uri,$varname)=@_;
11019: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11020:
11021: my (@extension,@specifics,$do_default);
11022: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11023: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11024: if ($pack_type eq 'default') {
11025: $do_default=1;
11026: } elsif ($pack_type eq 'extension') {
11027: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11028: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11029: # only look at packages defaults for packages that this id is
1.738 albertel 11030: push(@specifics,[$package,$pack_type,$pack_part]);
11031: }
11032: }
11033: # first look for a package that matches the requested part id
11034: foreach my $package (@specifics) {
11035: my (undef,$pack_type,$pack_part)=@{$package};
11036: next if ($pack_part ne $part);
11037: if (defined($packagetab{"$pack_type&$name&default"})) {
11038: return $packagetab{"$pack_type&$name&default"};
11039: }
11040: }
11041: # look for any possible matching non extension_ package
11042: foreach my $package (@specifics) {
11043: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11044: if (defined($packagetab{"$pack_type&$name&default"})) {
11045: return $packagetab{"$pack_type&$name&default"};
11046: }
1.585 albertel 11047: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11048: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11049: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11050: }
11051: }
1.738 albertel 11052: # look for any posible extension_ match
11053: foreach my $package (@extension) {
11054: my ($package,$pack_type)=@{$package};
11055: if (defined($packagetab{"$pack_type&$name&default"})) {
11056: return $packagetab{"$pack_type&$name&default"};
11057: }
11058: if (defined($packagetab{$package."&$name&default"})) {
11059: return $packagetab{$package."&$name&default"};
11060: }
11061: }
11062: # look for a global default setting
11063: if ($do_default && defined($packagetab{"default&$name&default"})) {
11064: return $packagetab{"default&$name&default"};
11065: }
1.395 albertel 11066: return undef;
11067: }
11068:
1.334 albertel 11069: sub add_prefix_and_part {
11070: my ($prefix,$part)=@_;
11071: my $keyroot;
11072: if (defined($prefix) && $prefix !~ /^__/) {
11073: # prefix that has a part already
11074: $keyroot=$prefix;
11075: } elsif (defined($prefix)) {
11076: # prefix that is missing a part
11077: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11078: } else {
11079: # no prefix at all
11080: if (defined($part)) { $keyroot='_'.$part; }
11081: }
11082: return $keyroot;
11083: }
11084:
1.71 www 11085: # ---------------------------------------------------------------- Get metadata
11086:
1.599 albertel 11087: my %metaentry;
1.1070 www 11088: my %importedpartids;
1.1172.2.93.4 8(raebur 11089:8): my %importedrespids;
1.71 www 11090: sub metadata {
1.176 www 11091: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11092: $uri=&declutter($uri);
1.288 albertel 11093: # if it is a non metadata possible uri return quickly
1.529 albertel 11094: if (($uri eq '') ||
11095: (($uri =~ m|^/*adm/|) &&
1.1172.2.93.4 2(raebur 11096:7): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11097: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11098: return undef;
11099: }
1.1172.2.49 raeburn 11100: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11101: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11102: return undef;
1.288 albertel 11103: }
1.73 www 11104: my $filename=$uri;
11105: $uri=~s/\.meta$//;
1.172 www 11106: #
11107: # Is the metadata already cached?
1.177 www 11108: # Look at timestamp of caching
1.172 www 11109: # Everything is cached by the main uri, libraries are never directly cached
11110: #
1.428 albertel 11111: if (!defined($liburi)) {
1.599 albertel 11112: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11113: if (defined($cached)) { return $result->{':'.$what}; }
11114: }
11115: {
1.1069 www 11116: # Imported parts would go here
1.1172.2.93.4 8(raebur 11117:8): my @origfiletagids=();
1.1069 www 11118: my $importedparts=0;
1.1172.2.93.4 8(raebur 11119:8):
11120:8): # Imported responseids would go here
11121:8): my $importedresponses=0;
1.172 www 11122: #
11123: # Is this a recursive call for a library?
11124: #
1.599 albertel 11125: # if (! exists($metacache{$uri})) {
11126: # $metacache{$uri}={};
11127: # }
1.924 albertel 11128: my $cachetime = 60*60;
1.171 www 11129: if ($liburi) {
11130: $liburi=&declutter($liburi);
11131: $filename=$liburi;
1.401 bowersj2 11132: } else {
1.599 albertel 11133: &devalidate_cache_new('meta',$uri);
11134: undef(%metaentry);
1.401 bowersj2 11135: }
1.140 www 11136: my %metathesekeys=();
1.73 www 11137: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11138: my $metastring;
1.1140 www 11139: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11140: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11141: $metastring =
1.929 albertel 11142: &Apache::lonnet::ssi_body($which,
1.924 albertel 11143: ('grade_target' => 'meta'));
11144: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11145: } elsif (($uri !~ m -^(editupload)/-) &&
11146: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11147: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11148: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11149: $metastring=&getfile($file);
1.489 albertel 11150: }
1.208 albertel 11151: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11152: my $token;
1.140 www 11153: undef %metathesekeys;
1.71 www 11154: while ($token=$parser->get_token) {
1.339 albertel 11155: if ($token->[0] eq 'S') {
11156: if (defined($token->[2]->{'package'})) {
1.172 www 11157: #
11158: # This is a package - get package info
11159: #
1.339 albertel 11160: my $package=$token->[2]->{'package'};
11161: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11162: if (defined($token->[2]->{'id'})) {
11163: $keyroot.='_'.$token->[2]->{'id'};
11164: }
1.599 albertel 11165: if ($metaentry{':packages'}) {
11166: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11167: } else {
1.599 albertel 11168: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11169: }
1.736 albertel 11170: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11171: my $part=$keyroot;
11172: $part=~s/^\_//;
1.736 albertel 11173: if ($pack_entry=~/^\Q$package\E\&/ ||
11174: $pack_entry=~/^\Q$package\E_0\&/) {
11175: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11176: # ignore package.tab specified default values
11177: # here &package_tab_default() will fetch those
11178: if ($subp eq 'default') { next; }
1.736 albertel 11179: my $value=$packagetab{$pack_entry};
1.432 albertel 11180: my $unikey;
11181: if ($pack =~ /_0$/) {
11182: $unikey='parameter_0_'.$name;
11183: $part=0;
11184: } else {
11185: $unikey='parameter'.$keyroot.'_'.$name;
11186: }
1.339 albertel 11187: if ($subp eq 'display') {
11188: $value.=' [Part: '.$part.']';
11189: }
1.599 albertel 11190: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11191: $metathesekeys{$unikey}=1;
1.599 albertel 11192: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11193: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11194: }
1.599 albertel 11195: if (defined($metaentry{':'.$unikey.'.default'})) {
11196: $metaentry{':'.$unikey}=
11197: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11198: }
1.339 albertel 11199: }
11200: }
11201: } else {
1.172 www 11202: #
11203: # This is not a package - some other kind of start tag
1.339 albertel 11204: #
11205: my $entry=$token->[1];
1.1068 www 11206: my $unikey='';
1.175 www 11207:
1.339 albertel 11208: if ($entry eq 'import') {
1.175 www 11209: #
11210: # Importing a library here
1.339 albertel 11211: #
1.1067 www 11212: my $location=$parser->get_text('/import');
11213: my $dir=$filename;
11214: $dir=~s|[^/]*$||;
11215: $location=&filelocation($dir,$location);
1.1172.2.93.4 8(raebur 11216:8):
11217:8): my $importid=$token->[2]->{'id'};
1.1068 www 11218: my $importmode=$token->[2]->{'importmode'};
1.1172.2.93.4 8(raebur 11219:8): #
11220:8): # Check metadata for imported file to
11221:8): # see if it contained response items
11222:8): #
9(raebur 11223:8): my %currmetaentry = %metaentry;
8(raebur 11224:8): my $libresponseorder = &metadata($location,'responseorder');
11225:8): my $origfile;
11226:8): if ($libresponseorder ne '') {
11227:8): if ($#origfiletagids<0) {
11228:8): undef(%importedrespids);
11229:8): undef(%importedpartids);
11230:8): }
11231:8): @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11232:8): if (@{$importedrespids{$importid}} > 0) {
11233:8): $importedresponses = 1;
11234:8): # We need to get the original file and the imported file to get the response order correct
11235:8): # Load and inspect original file
11236:8): if ($#origfiletagids<0) {
11237:8): my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11238:8): $origfile=&getfile($origfilelocation);
11239:8): @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11240:8): }
11241:8): }
11242:8): }
9(raebur 11243:8): # Do not overwrite contents of %metaentry hash for resource itself with
11244:8): # hash populated for imported library file
11245:8): %metaentry = %currmetaentry;
11246:8): undef(%currmetaentry);
1.1068 www 11247: if ($importmode eq 'problem') {
1.1069 www 11248: # Import as problem/response
1.1068 www 11249: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11250: } elsif ($importmode eq 'part') {
11251: # Import as part(s)
1.1069 www 11252: $importedparts=1;
11253: # We need to get the original file and the imported file to get the part order correct
11254: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.93.4 8(raebur 11255:8): # Load and inspect original file if we didn't do that already
9(raebur 11256:8): if ($#origfiletagids<0) {
8(raebur 11257:8): undef(%importedrespids);
11258:8): undef(%importedpartids);
11259:8): if ($origfile eq '') {
11260:8): my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11261:8): $origfile=&getfile($origfilelocation);
11262:8): @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11263:8): }
1.1070 www 11264: }
11265:
1.1069 www 11266: # Load and inspect imported file
11267: my $impfile=&getfile($location);
11268: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11269: if ($#impfilepartids>=0) {
11270: # This problem had parts
1.1070 www 11271: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11272: } else {
11273: # Importing by turning a single problem into a problem part
11274: # It gets the import-tags ID as part-ID
11275: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11276: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11277: }
1.1068 www 11278: } else {
11279: # Normal import
11280: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11281: if (defined($token->[2]->{'id'})) {
11282: $unikey.='_'.$token->[2]->{'id'};
11283: }
1.1067 www 11284: }
11285:
1.339 albertel 11286: if ($depthcount<20) {
1.736 albertel 11287: my $metadata =
11288: &metadata($uri,'keys', $location,$unikey,
11289: $depthcount+1);
11290: foreach my $meta (split(',',$metadata)) {
11291: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11292: $metathesekeys{$meta}=1;
1.339 albertel 11293: }
1.1068 www 11294:
11295: }
1.1067 www 11296: } else {
11297: #
11298: # Not importing, some other kind of non-package, non-library start tag
11299: #
11300: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11301: if (defined($token->[2]->{'id'})) {
11302: $unikey.='_'.$token->[2]->{'id'};
11303: }
1.339 albertel 11304: if (defined($token->[2]->{'name'})) {
11305: $unikey.='_'.$token->[2]->{'name'};
11306: }
11307: $metathesekeys{$unikey}=1;
1.736 albertel 11308: foreach my $param (@{$token->[3]}) {
11309: $metaentry{':'.$unikey.'.'.$param} =
11310: $token->[2]->{$param};
1.339 albertel 11311: }
11312: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11313: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11314: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11315: # only ws inside the tag, and not in default, so use default
11316: # as value
1.599 albertel 11317: $metaentry{':'.$unikey}=$default;
1.908 albertel 11318: } elsif ( $internaltext =~ /\S/ ) {
11319: # something interesting inside the tag
11320: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11321: } else {
1.908 albertel 11322: # no interesting values, don't set a default
1.339 albertel 11323: }
1.172 www 11324: # end of not-a-package not-a-library import
1.339 albertel 11325: }
1.172 www 11326: # end of not-a-package start tag
1.339 albertel 11327: }
1.172 www 11328: # the next is the end of "start tag"
1.339 albertel 11329: }
11330: }
1.483 albertel 11331: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11332: $extension = lc($extension);
11333: if ($extension eq 'htm') { $extension='html'; }
11334:
1.737 albertel 11335: foreach my $key (keys(%packagetab)) {
1.483 albertel 11336: #no specific packages #how's our extension
11337: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11338: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11339: \%metathesekeys);
11340: }
1.883 albertel 11341:
11342: if (!exists($metaentry{':packages'})
11343: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11344: foreach my $key (keys(%packagetab)) {
1.483 albertel 11345: #no specific packages well let's get default then
11346: if ($key!~/^default&/) { next; }
1.488 albertel 11347: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11348: \%metathesekeys);
11349: }
11350: }
1.338 www 11351: # are there custom rights to evaluate
1.599 albertel 11352: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11353:
1.338 www 11354: #
11355: # Importing a rights file here
1.339 albertel 11356: #
11357: unless ($depthcount) {
1.599 albertel 11358: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11359: my $dir=$filename;
11360: $dir=~s|[^/]*$||;
11361: $location=&filelocation($dir,$location);
1.736 albertel 11362: my $rights_metadata =
11363: &metadata($uri,'keys',$location,'_rights',
11364: $depthcount+1);
11365: foreach my $rights (split(',',$rights_metadata)) {
11366: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11367: $metathesekeys{$rights}=1;
1.339 albertel 11368: }
11369: }
11370: }
1.737 albertel 11371: # uniqifiy package listing
11372: my %seen;
11373: my @uniq_packages =
11374: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11375: $metaentry{':packages'} = join(',',@uniq_packages);
11376:
1.1172.2.93.4 8(raebur 11377:8): if (($importedresponses) || ($importedparts)) {
11378:8): if ($importedparts) {
1.1070 www 11379: # We had imported parts and need to rebuild partorder
1.1172.2.93.4 8(raebur 11380:8): $metaentry{':partorder'}='';
11381:8): $metathesekeys{'partorder'}=1;
11382:8): }
11383:8): if ($importedresponses) {
11384:8): # We had imported responses and need to rebuild responseorder
11385:8): $metaentry{':responseorder'}='';
11386:8): $metathesekeys{'responseorder'}=1;
11387:8): }
11388:8): for (my $index=0;$index<$#origfiletagids;$index+=2) {
11389:8): my $origid = $origfiletagids[$index+1];
11390:8): if ($origfiletagids[$index] eq 'part') {
11391:8): # Original part, part of the problem
11392:8): if ($importedparts) {
11393:8): $metaentry{':partorder'}.=','.$origid;
11394:8): }
11395:8): } elsif ($origfiletagids[$index] eq 'import') {
11396:8): if ($importedparts) {
11397:8): # We have imported parts at this position
11398:8): $metaentry{':partorder'}.=','.$importedpartids{$origid};
11399:8): }
11400:8): if ($importedresponses) {
11401:8): # We have imported responses at this position
11402:8): if (ref($importedrespids{$origid}) eq 'ARRAY') {
11403:8): $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
11404:8): }
11405:8): }
11406:8): } else {
11407:8): # Original response item, part of the problem
11408:8): if ($importedresponses) {
11409:8): $metaentry{':responseorder'}.=','.$origid;
11410:8): }
11411:8): }
11412:8): }
11413:8): if ($importedparts) {
11414:8): $metaentry{':partorder'}=~s/^\,//;
11415:8): }
11416:8): if ($importedresponses) {
11417:8): $metaentry{':responseorder'}=~s/^\,//;
11418:8): }
1.1070 www 11419: }
11420:
1.737 albertel 11421: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11422: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11423: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11424: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11425: # this is the end of "was not already recently cached
1.71 www 11426: }
1.599 albertel 11427: return $metaentry{':'.$what};
1.261 albertel 11428: }
11429:
1.488 albertel 11430: sub metadata_create_package_def {
1.483 albertel 11431: my ($uri,$key,$package,$metathesekeys)=@_;
11432: my ($pack,$name,$subp)=split(/\&/,$key);
11433: if ($subp eq 'default') { next; }
11434:
1.599 albertel 11435: if (defined($metaentry{':packages'})) {
11436: $metaentry{':packages'}.=','.$package;
1.483 albertel 11437: } else {
1.599 albertel 11438: $metaentry{':packages'}=$package;
1.483 albertel 11439: }
11440: my $value=$packagetab{$key};
11441: my $unikey;
11442: $unikey='parameter_0_'.$name;
1.599 albertel 11443: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11444: $$metathesekeys{$unikey}=1;
1.599 albertel 11445: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11446: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11447: }
1.599 albertel 11448: if (defined($metaentry{':'.$unikey.'.default'})) {
11449: $metaentry{':'.$unikey}=
11450: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11451: }
11452: }
11453:
1.261 albertel 11454: sub metadata_generate_part0 {
11455: my ($metadata,$metacache,$uri) = @_;
11456: my %allnames;
1.737 albertel 11457: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11458: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11459: my $part=$$metacache{':'.$metakey.'.part'};
11460: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11461: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11462: $allnames{$name}=$part;
11463: }
11464: }
11465: }
11466: foreach my $name (keys(%allnames)) {
11467: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11468: my $key=":parameter_0_$name";
1.261 albertel 11469: $$metacache{"$key.part"}='0';
11470: $$metacache{"$key.name"}=$name;
1.428 albertel 11471: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11472: $allnames{$name}.'_'.$name.
11473: '.type'};
1.428 albertel 11474: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11475: '.display'};
1.644 www 11476: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11477: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11478: $$metacache{"$key.display"}=$olddis;
11479: }
1.71 www 11480: }
11481:
1.764 albertel 11482: # ------------------------------------------------------ Devalidate title cache
11483:
11484: sub devalidate_title_cache {
11485: my ($url)=@_;
11486: if (!$env{'request.course.id'}) { return; }
11487: my $symb=&symbread($url);
11488: if (!$symb) { return; }
11489: my $key=$env{'request.course.id'}."\0".$symb;
11490: &devalidate_cache_new('title',$key);
11491: }
11492:
1.1014 droeschl 11493: # ------------------------------------------------- Get the title of a course
11494:
11495: sub current_course_title {
11496: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11497: }
1.301 www 11498: # ------------------------------------------------- Get the title of a resource
11499:
11500: sub gettitle {
11501: my $urlsymb=shift;
11502: my $symb=&symbread($urlsymb);
1.534 albertel 11503: if ($symb) {
1.620 albertel 11504: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11505: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11506: if (defined($cached)) {
11507: return $result;
11508: }
1.534 albertel 11509: my ($map,$resid,$url)=&decode_symb($symb);
11510: my $title='';
1.907 albertel 11511: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11512: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11513: } else {
11514: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11515: &GDBM_READER(),0640)) {
11516: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11517: $title=$bighash{'title_'.$mapid.'.'.$resid};
11518: untie(%bighash);
11519: }
1.534 albertel 11520: }
11521: $title=~s/\&colon\;/\:/gs;
11522: if ($title) {
1.1159 www 11523: # Remember both $symb and $title for dynamic metadata
11524: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11525: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11526: # Cache this title and then return it
1.599 albertel 11527: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11528: }
11529: $urlsymb=$url;
11530: }
11531: my $title=&metadata($urlsymb,'title');
11532: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11533: return $title;
1.301 www 11534: }
1.613 albertel 11535:
1.614 albertel 11536: sub get_slot {
11537: my ($which,$cnum,$cdom)=@_;
11538: if (!$cnum || !$cdom) {
1.790 albertel 11539: (undef,my $courseid)=&whichuser();
1.620 albertel 11540: $cdom=$env{'course.'.$courseid.'.domain'};
11541: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11542: }
1.703 albertel 11543: my $key=join("\0",'slots',$cdom,$cnum,$which);
11544: my %slotinfo;
11545: if (exists($remembered{$key})) {
11546: $slotinfo{$which} = $remembered{$key};
11547: } else {
11548: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11549: &Apache::lonhomework::showhash(%slotinfo);
11550: my ($tmp)=keys(%slotinfo);
11551: if ($tmp=~/^error:/) { return (); }
11552: $remembered{$key} = $slotinfo{$which};
11553: }
1.616 albertel 11554: if (ref($slotinfo{$which}) eq 'HASH') {
11555: return %{$slotinfo{$which}};
11556: }
11557: return $slotinfo{$which};
1.614 albertel 11558: }
1.1150 raeburn 11559:
11560: sub get_reservable_slots {
11561: my ($cnum,$cdom,$uname,$udom) = @_;
11562: my $now = time;
11563: my $reservable_info;
11564: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11565: if (exists($remembered{$key})) {
11566: $reservable_info = $remembered{$key};
11567: } else {
11568: my %resv;
11569: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11570: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11571: $reservable_info = \%resv;
11572: $remembered{$key} = $reservable_info;
11573: }
11574: return $reservable_info;
11575: }
11576:
11577: sub get_course_slots {
11578: my ($cnum,$cdom) = @_;
11579: my $hashid=$cnum.':'.$cdom;
11580: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11581: if (defined($cached)) {
11582: if (ref($result) eq 'HASH') {
11583: return %{$result};
11584: }
11585: } else {
11586: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11587: my ($tmp) = keys(%slots);
11588: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11589: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11590: return %slots;
11591: }
11592: }
11593: return;
11594: }
11595:
11596: sub devalidate_slots_cache {
11597: my ($cnum,$cdom)=@_;
11598: my $hashid=$cnum.':'.$cdom;
11599: &devalidate_cache_new('allslots',$hashid);
11600: }
11601:
1.1172.2.8 raeburn 11602: sub get_coursechange {
11603: my ($cdom,$cnum) = @_;
11604: if ($cdom eq '' || $cnum eq '') {
11605: return unless ($env{'request.course.id'});
11606: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11607: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11608: }
11609: my $hashid=$cdom.'_'.$cnum;
11610: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11611: if ((defined($cached)) && ($change ne '')) {
11612: return $change;
11613: } else {
11614: my %crshash;
11615: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11616: if ($crshash{'internal.contentchange'} eq '') {
11617: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11618: if ($change eq '') {
11619: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11620: $change = $crshash{'internal.created'};
11621: }
11622: } else {
11623: $change = $crshash{'internal.contentchange'};
11624: }
11625: my $cachetime = 600;
11626: &do_cache_new('crschange',$hashid,$change,$cachetime);
11627: }
11628: return $change;
11629: }
11630:
11631: sub devalidate_coursechange_cache {
11632: my ($cnum,$cdom)=@_;
11633: my $hashid=$cnum.':'.$cdom;
11634: &devalidate_cache_new('crschange',$hashid);
11635: }
11636:
1.31 www 11637: # ------------------------------------------------- Update symbolic store links
11638:
11639: sub symblist {
11640: my ($mapname,%newhash)=@_;
1.438 www 11641: $mapname=&deversion(&declutter($mapname));
1.31 www 11642: my %hash;
1.620 albertel 11643: if (($env{'request.course.fn'}) && (%newhash)) {
11644: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11645: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11646: foreach my $url (keys(%newhash)) {
1.711 albertel 11647: next if ($url eq 'last_known'
11648: && $env{'form.no_update_last_known'});
11649: $hash{declutter($url)}=&encode_symb($mapname,
11650: $newhash{$url}->[1],
11651: $newhash{$url}->[0]);
1.191 harris41 11652: }
1.31 www 11653: if (untie(%hash)) {
11654: return 'ok';
11655: }
11656: }
11657: }
11658: return 'error';
1.212 www 11659: }
11660:
11661: # --------------------------------------------------------------- Verify a symb
11662:
11663: sub symbverify {
1.1172.2.11 raeburn 11664: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11665: my $thisfn=$thisurl;
1.439 www 11666: $thisfn=&declutter($thisfn);
1.215 www 11667: # direct jump to resource in page or to a sequence - will construct own symbs
11668: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11669: # check URL part
1.409 www 11670: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11671:
1.431 www 11672: unless ($url eq $thisfn) { return 0; }
1.213 www 11673:
1.216 www 11674: $symb=&symbclean($symb);
1.510 www 11675: $thisurl=&deversion($thisurl);
1.439 www 11676: $thisfn=&deversion($thisfn);
1.213 www 11677:
11678: my %bighash;
11679: my $okay=0;
1.431 www 11680:
1.620 albertel 11681: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11682: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11683: my $noclutter;
1.1032 raeburn 11684: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11685: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11686: if ($map =~ m{^uploaded/.+\.page$}) {
11687: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11688: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11689: $noclutter = 1;
11690: }
11691: }
11692: my $ids;
11693: if ($noclutter) {
11694: $ids=$bighash{'ids_'.$thisurl};
11695: } else {
11696: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11697: }
1.1102 raeburn 11698: unless ($ids) {
1.1172.2.13 raeburn 11699: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11700: $ids=$bighash{$idkey};
1.216 www 11701: }
11702: if ($ids) {
11703: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11704: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11705: $symb =~ s/\?.+$//;
11706: }
1.800 albertel 11707: foreach my $id (split(/\,/,$ids)) {
11708: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11709: if (
11710: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11711: eq $symb) {
1.1172.2.11 raeburn 11712: if (ref($encstate)) {
11713: $$encstate = $bighash{'encrypted_'.$id};
11714: }
1.1172.2.13 raeburn 11715: if (($env{'request.role.adv'}) ||
11716: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11717: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11718: $okay=1;
11719: last;
11720: }
11721: }
11722: }
1.216 www 11723: }
1.213 www 11724: untie(%bighash);
11725: }
11726: return $okay;
1.31 www 11727: }
11728:
1.210 www 11729: # --------------------------------------------------------------- Clean-up symb
11730:
11731: sub symbclean {
11732: my $symb=shift;
1.568 albertel 11733: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11734: # remove version from map
11735: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11736:
1.210 www 11737: # remove version from URL
11738: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11739:
1.507 www 11740: # remove wrapper
11741:
1.510 www 11742: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11743: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11744: return $symb;
1.409 www 11745: }
11746:
11747: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11748:
11749: sub encode_symb {
11750: my ($map,$resid,$url)=@_;
11751: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11752: }
1.409 www 11753:
11754: sub decode_symb {
1.568 albertel 11755: my $symb=shift;
11756: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11757: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11758: return (&fixversion($map),$resid,&fixversion($url));
11759: }
11760:
11761: sub fixversion {
11762: my $fn=shift;
1.609 banghart 11763: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11764: my %bighash;
11765: my $uri=&clutter($fn);
1.620 albertel 11766: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11767: # is this cached?
1.599 albertel 11768: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11769: if (defined($cached)) { return $result; }
11770: # unfortunately not cached, or expired
1.620 albertel 11771: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11772: &GDBM_READER(),0640)) {
11773: if ($bighash{'version_'.$uri}) {
11774: my $version=$bighash{'version_'.$uri};
1.444 www 11775: unless (($version eq 'mostrecent') ||
11776: ($version==&getversion($uri))) {
1.440 www 11777: $uri=~s/\.(\w+)$/\.$version\.$1/;
11778: }
11779: }
11780: untie %bighash;
1.413 www 11781: }
1.599 albertel 11782: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11783: }
11784:
11785: sub deversion {
11786: my $url=shift;
11787: $url=~s/\.\d+\.(\w+)$/\.$1/;
11788: return $url;
1.210 www 11789: }
11790:
1.31 www 11791: # ------------------------------------------------------ Return symb list entry
11792:
11793: sub symbread {
1.1172.2.66 raeburn 11794: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11795: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11796: if (defined($env{$cache_str})) {
11797: if ($ignorecachednull) {
11798: return $env{$cache_str} unless ($env{$cache_str} eq '');
11799: } else {
11800: return $env{$cache_str};
11801: }
11802: }
1.242 www 11803: # no filename provided? try from environment
1.1172.2.54 raeburn 11804: unless ($thisfn) {
1.620 albertel 11805: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11806: return $env{$cache_str}=&symbclean($env{'request.symb'});
11807: }
11808: $thisfn=$env{'request.filename'};
1.44 www 11809: }
1.569 albertel 11810: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11811: # is that filename actually a symb? Verify, clean, and return
11812: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11813: if (&symbverify($thisfn,$1)) {
1.620 albertel 11814: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11815: }
1.242 www 11816: }
1.44 www 11817: $thisfn=declutter($thisfn);
1.31 www 11818: my %hash;
1.37 www 11819: my %bighash;
11820: my $syval='';
1.620 albertel 11821: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11822: my $targetfn = $thisfn;
1.609 banghart 11823: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11824: $targetfn = 'adm/wrapper/'.$thisfn;
11825: }
1.687 albertel 11826: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11827: $targetfn=$1;
11828: }
1.620 albertel 11829: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11830: &GDBM_READER(),0640)) {
1.481 raeburn 11831: $syval=$hash{$targetfn};
1.37 www 11832: untie(%hash);
11833: }
11834: # ---------------------------------------------------------- There was an entry
11835: if ($syval) {
1.601 albertel 11836: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11837: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11838: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11839: #return $env{$cache_str}='';
1.601 albertel 11840: #}
11841: #$syval.=$1;
11842: #}
1.37 www 11843: } else {
11844: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11845: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11846: &GDBM_READER(),0640)) {
1.37 www 11847: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11848: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11849: unless ($ids) {
11850: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11851: }
11852: unless ($ids) {
11853: # alias?
11854: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11855: }
1.37 www 11856: if ($ids) {
11857: # ------------------------------------------------------------------- Has ID(s)
11858: my @possibilities=split(/\,/,$ids);
1.39 www 11859: if ($#possibilities==0) {
11860: # ----------------------------------------------- There is only one possibility
1.37 www 11861: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11862: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11863: $resid,$thisfn);
1.1172.2.66 raeburn 11864: if (ref($possibles) eq 'HASH') {
11865: $possibles->{$syval} = 1;
11866: }
11867: if ($checkforblock) {
11868: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11869: if (@blockers) {
11870: $syval = '';
11871: return;
11872: }
11873: }
11874: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11875: # ------------------------------------------ There is more than one possibility
11876: my $realpossible=0;
1.800 albertel 11877: foreach my $id (@possibilities) {
11878: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11879: my $canaccess;
11880: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11881: $canaccess = 1;
11882: } else {
11883: $canaccess = &allowed('bre',$file);
11884: }
11885: if ($canaccess) {
11886: my ($mapid,$resid)=split(/\./,$id);
11887: if ($bighash{'map_type_'.$mapid} ne 'page') {
11888: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11889: $resid,$thisfn);
11890: if (ref($possibles) eq 'HASH') {
11891: $possibles->{$syval} = 1;
11892: }
11893: if ($checkforblock) {
11894: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11895: unless (@blockers > 0) {
11896: $syval = $poss_syval;
11897: $realpossible++;
11898: }
11899: } else {
11900: $syval = $poss_syval;
11901: $realpossible++;
11902: }
11903: }
1.39 www 11904: }
1.191 harris41 11905: }
1.39 www 11906: if ($realpossible!=1) { $syval=''; }
1.249 www 11907: } else {
11908: $syval='';
1.37 www 11909: }
11910: }
1.1172.2.66 raeburn 11911: untie(%bighash);
1.481 raeburn 11912: }
1.31 www 11913: }
1.62 www 11914: if ($syval) {
1.620 albertel 11915: return $env{$cache_str}=$syval;
1.62 www 11916: }
1.31 www 11917: }
1.949 raeburn 11918: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11919: return $env{$cache_str}='';
1.31 www 11920: }
11921:
11922: # ---------------------------------------------------------- Return random seed
11923:
1.32 www 11924: sub numval {
11925: my $txt=shift;
11926: $txt=~tr/A-J/0-9/;
11927: $txt=~tr/a-j/0-9/;
11928: $txt=~tr/K-T/0-9/;
11929: $txt=~tr/k-t/0-9/;
11930: $txt=~tr/U-Z/0-5/;
11931: $txt=~tr/u-z/0-5/;
11932: $txt=~s/\D//g;
1.564 albertel 11933: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11934: return int($txt);
1.368 albertel 11935: }
11936:
1.484 albertel 11937: sub numval2 {
11938: my $txt=shift;
11939: $txt=~tr/A-J/0-9/;
11940: $txt=~tr/a-j/0-9/;
11941: $txt=~tr/K-T/0-9/;
11942: $txt=~tr/k-t/0-9/;
11943: $txt=~tr/U-Z/0-5/;
11944: $txt=~tr/u-z/0-5/;
11945: $txt=~s/\D//g;
11946: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11947: my $total;
11948: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11949: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11950: return int($total);
11951: }
11952:
1.575 albertel 11953: sub numval3 {
11954: use integer;
11955: my $txt=shift;
11956: $txt=~tr/A-J/0-9/;
11957: $txt=~tr/a-j/0-9/;
11958: $txt=~tr/K-T/0-9/;
11959: $txt=~tr/k-t/0-9/;
11960: $txt=~tr/U-Z/0-5/;
11961: $txt=~tr/u-z/0-5/;
11962: $txt=~s/\D//g;
11963: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11964: my $total;
11965: foreach my $val (@txts) { $total+=$val; }
11966: if ($_64bit) { $total=(($total<<32)>>32); }
11967: return $total;
11968: }
11969:
1.675 albertel 11970: sub digest {
11971: my ($data)=@_;
11972: my $digest=&Digest::MD5::md5($data);
11973: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11974: my ($e,$f);
11975: {
11976: use integer;
11977: $e=($a+$b);
11978: $f=($c+$d);
11979: if ($_64bit) {
11980: $e=(($e<<32)>>32);
11981: $f=(($f<<32)>>32);
11982: }
11983: }
11984: if (wantarray) {
11985: return ($e,$f);
11986: } else {
11987: my $g;
11988: {
11989: use integer;
11990: $g=($e+$f);
11991: if ($_64bit) {
11992: $g=(($g<<32)>>32);
11993: }
11994: }
11995: return $g;
11996: }
11997: }
11998:
1.368 albertel 11999: sub latest_rnd_algorithm_id {
1.675 albertel 12000: return '64bit5';
1.366 albertel 12001: }
1.32 www 12002:
1.503 albertel 12003: sub get_rand_alg {
12004: my ($courseid)=@_;
1.790 albertel 12005: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12006: if ($courseid) {
1.620 albertel 12007: return $env{"course.$courseid.rndseed"};
1.503 albertel 12008: }
12009: return &latest_rnd_algorithm_id();
12010: }
12011:
1.562 albertel 12012: sub validCODE {
12013: my ($CODE)=@_;
12014: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12015: return 0;
12016: }
12017:
1.491 albertel 12018: sub getCODE {
1.620 albertel 12019: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12020: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12021: defined($Apache::lonhomework::parsing_a_task) ) &&
12022: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12023: return $Apache::lonhomework::history{'resource.CODE'};
12024: }
12025: return undef;
12026: }
1.1133 foxr 12027: #
12028: # Determines the random seed for a specific context:
12029: #
12030: # parameters:
12031: # symb - in course context the symb for the seed.
12032: # course_id - The course id of the form domain_coursenum.
12033: # domain - Domain for the user.
12034: # course - Course for the user.
12035: # cenv - environment of the course.
12036: #
12037: # NOTE:
12038: # All parameters are picked out of the environment if missing
12039: # or not defined.
12040: # If a symb cannot be determined the current time is used instead.
12041: #
12042: # For a given well defined symb, courside, domain, username,
12043: # and course environment, the seed is reproducible.
12044: #
1.31 www 12045: sub rndseed {
1.1133 foxr 12046: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12047: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12048: if (!defined($symb)) {
1.366 albertel 12049: unless ($symb=$wsymb) { return time; }
12050: }
1.1146 foxr 12051: if (!defined $courseid) {
12052: $courseid=$wcourseid;
12053: }
12054: if (!defined $domain) { $domain=$wdomain; }
12055: if (!defined $username) { $username=$wusername }
1.1133 foxr 12056:
12057: my $which;
12058: if (defined($cenv->{'rndseed'})) {
12059: $which = $cenv->{'rndseed'};
12060: } else {
12061: $which =&get_rand_alg($courseid);
12062: }
1.491 albertel 12063: if (defined(&getCODE())) {
1.675 albertel 12064: if ($which eq '64bit5') {
12065: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12066: } elsif ($which eq '64bit4') {
1.575 albertel 12067: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12068: } else {
12069: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12070: }
1.675 albertel 12071: } elsif ($which eq '64bit5') {
12072: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12073: } elsif ($which eq '64bit4') {
12074: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12075: } elsif ($which eq '64bit3') {
12076: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12077: } elsif ($which eq '64bit2') {
12078: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12079: } elsif ($which eq '64bit') {
12080: return &rndseed_64bit($symb,$courseid,$domain,$username);
12081: }
12082: return &rndseed_32bit($symb,$courseid,$domain,$username);
12083: }
12084:
12085: sub rndseed_32bit {
12086: my ($symb,$courseid,$domain,$username)=@_;
12087: {
12088: use integer;
12089: my $symbchck=unpack("%32C*",$symb) << 27;
12090: my $symbseed=numval($symb) << 22;
12091: my $namechck=unpack("%32C*",$username) << 17;
12092: my $nameseed=numval($username) << 12;
12093: my $domainseed=unpack("%32C*",$domain) << 7;
12094: my $courseseed=unpack("%32C*",$courseid);
12095: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12096: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12097: #&logthis("rndseed :$num:$symb");
1.564 albertel 12098: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12099: return $num;
12100: }
12101: }
12102:
12103: sub rndseed_64bit {
12104: my ($symb,$courseid,$domain,$username)=@_;
12105: {
12106: use integer;
12107: my $symbchck=unpack("%32S*",$symb) << 21;
12108: my $symbseed=numval($symb) << 10;
12109: my $namechck=unpack("%32S*",$username);
12110:
12111: my $nameseed=numval($username) << 21;
12112: my $domainseed=unpack("%32S*",$domain) << 10;
12113: my $courseseed=unpack("%32S*",$courseid);
12114:
12115: my $num1=$symbchck+$symbseed+$namechck;
12116: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12117: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12118: #&logthis("rndseed :$num:$symb");
1.564 albertel 12119: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12120: return "$num1,$num2";
1.155 albertel 12121: }
1.366 albertel 12122: }
12123:
1.443 albertel 12124: sub rndseed_64bit2 {
12125: my ($symb,$courseid,$domain,$username)=@_;
12126: {
12127: use integer;
12128: # strings need to be an even # of cahracters long, it it is odd the
12129: # last characters gets thrown away
12130: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12131: my $symbseed=numval($symb) << 10;
12132: my $namechck=unpack("%32S*",$username.' ');
12133:
12134: my $nameseed=numval($username) << 21;
1.501 albertel 12135: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12136: my $courseseed=unpack("%32S*",$courseid.' ');
12137:
12138: my $num1=$symbchck+$symbseed+$namechck;
12139: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12140: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12141: #&logthis("rndseed :$num:$symb");
1.803 albertel 12142: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12143: return "$num1,$num2";
12144: }
12145: }
12146:
12147: sub rndseed_64bit3 {
12148: my ($symb,$courseid,$domain,$username)=@_;
12149: {
12150: use integer;
12151: # strings need to be an even # of cahracters long, it it is odd the
12152: # last characters gets thrown away
12153: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12154: my $symbseed=numval2($symb) << 10;
12155: my $namechck=unpack("%32S*",$username.' ');
12156:
12157: my $nameseed=numval2($username) << 21;
1.443 albertel 12158: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12159: my $courseseed=unpack("%32S*",$courseid.' ');
12160:
12161: my $num1=$symbchck+$symbseed+$namechck;
12162: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12163: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12164: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12165: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12166:
1.503 albertel 12167: return "$num1:$num2";
1.443 albertel 12168: }
12169: }
12170:
1.575 albertel 12171: sub rndseed_64bit4 {
12172: my ($symb,$courseid,$domain,$username)=@_;
12173: {
12174: use integer;
12175: # strings need to be an even # of cahracters long, it it is odd the
12176: # last characters gets thrown away
12177: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12178: my $symbseed=numval3($symb) << 10;
12179: my $namechck=unpack("%32S*",$username.' ');
12180:
12181: my $nameseed=numval3($username) << 21;
12182: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12183: my $courseseed=unpack("%32S*",$courseid.' ');
12184:
12185: my $num1=$symbchck+$symbseed+$namechck;
12186: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12187: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12188: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12189: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12190:
1.575 albertel 12191: return "$num1:$num2";
12192: }
12193: }
12194:
1.675 albertel 12195: sub rndseed_64bit5 {
12196: my ($symb,$courseid,$domain,$username)=@_;
12197: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12198: return "$num1:$num2";
12199: }
12200:
1.366 albertel 12201: sub rndseed_CODE_64bit {
12202: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12203: {
1.366 albertel 12204: use integer;
1.443 albertel 12205: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12206: my $symbseed=numval2($symb);
1.491 albertel 12207: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12208: my $CODEseed=numval(&getCODE());
1.443 albertel 12209: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12210: my $num1=$symbseed+$CODEchck;
12211: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12212: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12213: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12214: if ($_64bit) { $num1=(($num1<<32)>>32); }
12215: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12216: return "$num1:$num2";
1.366 albertel 12217: }
12218: }
12219:
1.575 albertel 12220: sub rndseed_CODE_64bit4 {
12221: my ($symb,$courseid,$domain,$username)=@_;
12222: {
12223: use integer;
12224: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12225: my $symbseed=numval3($symb);
12226: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12227: my $CODEseed=numval3(&getCODE());
12228: my $courseseed=unpack("%32S*",$courseid.' ');
12229: my $num1=$symbseed+$CODEchck;
12230: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12231: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12232: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12233: if ($_64bit) { $num1=(($num1<<32)>>32); }
12234: if ($_64bit) { $num2=(($num2<<32)>>32); }
12235: return "$num1:$num2";
12236: }
12237: }
12238:
1.675 albertel 12239: sub rndseed_CODE_64bit5 {
12240: my ($symb,$courseid,$domain,$username)=@_;
12241: my $code = &getCODE();
12242: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12243: return "$num1:$num2";
12244: }
12245:
1.366 albertel 12246: sub setup_random_from_rndseed {
12247: my ($rndseed)=@_;
1.503 albertel 12248: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12249: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12250: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12251: &Math::Random::random_set_seed_from_phrase($rndseed);
12252: } else {
12253: &Math::Random::random_set_seed($num1,$num2);
12254: }
1.366 albertel 12255: } else {
12256: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12257: }
1.36 albertel 12258: }
12259:
1.474 albertel 12260: sub latest_receipt_algorithm_id {
1.835 albertel 12261: return 'receipt3';
1.474 albertel 12262: }
12263:
1.480 www 12264: sub recunique {
12265: my $fucourseid=shift;
12266: my $unique;
1.835 albertel 12267: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12268: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12269: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12270: } else {
12271: $unique=$perlvar{'lonReceipt'};
12272: }
12273: return unpack("%32C*",$unique);
12274: }
12275:
12276: sub recprefix {
12277: my $fucourseid=shift;
12278: my $prefix;
1.835 albertel 12279: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12280: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12281: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12282: } else {
12283: $prefix=$perlvar{'lonHostID'};
12284: }
12285: return unpack("%32C*",$prefix);
12286: }
12287:
1.76 www 12288: sub ireceipt {
1.474 albertel 12289: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12290:
12291: my $return =&recprefix($fucourseid).'-';
12292:
12293: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12294: $env{'request.state'} eq 'construct') {
12295: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12296: return $return;
12297: }
12298:
1.76 www 12299: my $cuname=unpack("%32C*",$funame);
12300: my $cudom=unpack("%32C*",$fudom);
12301: my $cucourseid=unpack("%32C*",$fucourseid);
12302: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12303: my $cunique=&recunique($fucourseid);
1.474 albertel 12304: my $cpart=unpack("%32S*",$part);
1.835 albertel 12305: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12306:
1.790 albertel 12307: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12308:
12309: $return.= ($cunique%$cuname+
12310: $cunique%$cudom+
12311: $cusymb%$cuname+
12312: $cusymb%$cudom+
12313: $cucourseid%$cuname+
12314: $cucourseid%$cudom+
12315: $cpart%$cuname+
12316: $cpart%$cudom);
12317: } else {
12318: $return.= ($cunique%$cuname+
12319: $cunique%$cudom+
12320: $cusymb%$cuname+
12321: $cusymb%$cudom+
12322: $cucourseid%$cuname+
12323: $cucourseid%$cudom);
12324: }
12325: return $return;
1.76 www 12326: }
12327:
12328: sub receipt {
1.474 albertel 12329: my ($part)=@_;
1.790 albertel 12330: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12331: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12332: }
1.260 ng 12333:
1.790 albertel 12334: sub whichuser {
12335: my ($passedsymb)=@_;
12336: my ($symb,$courseid,$domain,$name,$publicuser);
12337: if (defined($env{'form.grade_symb'})) {
12338: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12339: my $allowed=&allowed('vgr',$tmp_courseid);
12340: if (!$allowed &&
12341: exists($env{'request.course.sec'}) &&
12342: $env{'request.course.sec'} !~ /^\s*$/) {
12343: $allowed=&allowed('vgr',$tmp_courseid.
12344: '/'.$env{'request.course.sec'});
12345: }
12346: if ($allowed) {
12347: ($symb)=&get_env_multiple('form.grade_symb');
12348: $courseid=$tmp_courseid;
12349: ($domain)=&get_env_multiple('form.grade_domain');
12350: ($name)=&get_env_multiple('form.grade_username');
12351: return ($symb,$courseid,$domain,$name,$publicuser);
12352: }
12353: }
12354: if (!$passedsymb) {
12355: $symb=&symbread();
12356: } else {
12357: $symb=$passedsymb;
12358: }
12359: $courseid=$env{'request.course.id'};
12360: $domain=$env{'user.domain'};
12361: $name=$env{'user.name'};
12362: if ($name eq 'public' && $domain eq 'public') {
12363: if (!defined($env{'form.username'})) {
12364: $env{'form.username'}.=time.rand(10000000);
12365: }
12366: $name.=$env{'form.username'};
12367: }
12368: return ($symb,$courseid,$domain,$name,$publicuser);
12369:
12370: }
12371:
1.36 albertel 12372: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12373: # returns either the contents of the file or
12374: # -1 if the file doesn't exist
1.481 raeburn 12375: #
12376: # if the target is a file that was uploaded via DOCS,
12377: # a check will be made to see if a current copy exists on the local server,
12378: # if it does this will be served, otherwise a copy will be retrieved from
12379: # the home server for the course and stored in /home/httpd/html/userfiles on
12380: # the local server.
1.472 albertel 12381:
1.36 albertel 12382: sub getfile {
1.538 albertel 12383: my ($file) = @_;
1.609 banghart 12384: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12385: &repcopy($file);
12386: return &readfile($file);
12387: }
12388:
12389: sub repcopy_userfile {
12390: my ($file)=@_;
1.1142 raeburn 12391: my $londocroot = $perlvar{'lonDocRoot'};
12392: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12393: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12394: my ($cdom,$cnum,$filename) =
1.811 albertel 12395: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12396: my $uri="/uploaded/$cdom/$cnum/$filename";
12397: if (-e "$file") {
1.828 www 12398: # we already have a local copy, check it out
1.538 albertel 12399: my @fileinfo = stat($file);
1.828 www 12400: my $rtncode;
12401: my $info;
1.538 albertel 12402: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12403: if ($lwpresp ne 'ok') {
1.828 www 12404: # there is no such file anymore, even though we had a local copy
1.482 albertel 12405: if ($rtncode eq '404') {
1.538 albertel 12406: unlink($file);
1.482 albertel 12407: }
12408: return -1;
12409: }
12410: if ($info < $fileinfo[9]) {
1.828 www 12411: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12412: return 'ok';
1.828 www 12413: } else {
12414: # the file is outdated, get rid of it
12415: unlink($file);
1.482 albertel 12416: }
1.828 www 12417: }
12418: # one way or the other, at this point, we don't have the file
12419: # construct the correct path for the file
12420: my @parts = ($cdom,$cnum);
12421: if ($filename =~ m|^(.+)/[^/]+$|) {
12422: push @parts, split(/\//,$1);
12423: }
12424: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12425: foreach my $part (@parts) {
12426: $path .= '/'.$part;
12427: if (!-e $path) {
12428: mkdir($path,0770);
1.482 albertel 12429: }
12430: }
1.828 www 12431: # now the path exists for sure
12432: # get a user agent
12433: my $ua=new LWP::UserAgent;
12434: my $transferfile=$file.'.in.transfer';
12435: # FIXME: this should flock
12436: if (-e $transferfile) { return 'ok'; }
12437: my $request;
12438: $uri=~s/^\///;
1.980 raeburn 12439: my $homeserver = &homeserver($cnum,$cdom);
12440: my $protocol = $protocol{$homeserver};
12441: $protocol = 'http' if ($protocol ne 'https');
12442: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12443: my $response=$ua->request($request,$transferfile);
12444: # did it work?
12445: if ($response->is_error()) {
12446: unlink($transferfile);
12447: &logthis("Userfile repcopy failed for $uri");
12448: return -1;
12449: }
12450: # worked, rename the transfer file
12451: rename($transferfile,$file);
1.607 raeburn 12452: return 'ok';
1.481 raeburn 12453: }
12454:
1.517 albertel 12455: sub tokenwrapper {
12456: my $uri=shift;
1.980 raeburn 12457: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12458: $uri=~s|^/||;
1.620 albertel 12459: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12460: my $token=$1;
1.552 albertel 12461: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12462: if ($udom && $uname && $file) {
12463: $file=~s|(\?\.*)*$||;
1.949 raeburn 12464: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12465: my $homeserver = &homeserver($uname,$udom);
12466: my $protocol = $protocol{$homeserver};
12467: $protocol = 'http' if ($protocol ne 'https');
12468: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12469: (($uri=~/\?/)?'&':'?').'token='.$token.
12470: '&tokenissued='.$perlvar{'lonHostID'};
12471: } else {
12472: return '/adm/notfound.html';
12473: }
12474: }
12475:
1.828 www 12476: # call with reqtype HEAD: get last modification time
12477: # call with reqtype GET: get the file contents
12478: # Do not call this with reqtype GET for large files! It loads everything into memory
12479: #
1.481 raeburn 12480: sub getuploaded {
12481: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12482: $uri=~s/^\///;
1.980 raeburn 12483: my $homeserver = &homeserver($cnum,$cdom);
12484: my $protocol = $protocol{$homeserver};
12485: $protocol = 'http' if ($protocol ne 'https');
12486: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12487: my $ua=new LWP::UserAgent;
12488: my $request=new HTTP::Request($reqtype,$uri);
12489: my $response=$ua->request($request);
12490: $$rtncode = $response->code;
1.482 albertel 12491: if (! $response->is_success()) {
12492: return 'failed';
12493: }
12494: if ($reqtype eq 'HEAD') {
1.486 www 12495: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12496: } elsif ($reqtype eq 'GET') {
12497: $$info = $response->content;
1.472 albertel 12498: }
1.482 albertel 12499: return 'ok';
1.36 albertel 12500: }
12501:
1.481 raeburn 12502: sub readfile {
12503: my $file = shift;
12504: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12505: my $fh;
1.1172.2.93.4 7(raebur 12506:7): open($fh,"<",$file);
1.481 raeburn 12507: my $a='';
1.800 albertel 12508: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12509: return $a;
12510: }
12511:
1.36 albertel 12512: sub filelocation {
1.590 banghart 12513: my ($dir,$file) = @_;
12514: my $location;
12515: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12516:
12517: if ($file =~ m-^/adm/-) {
12518: $file=~s-^/adm/wrapper/-/-;
12519: $file=~s-^/adm/coursedocs/showdoc/-/-;
12520: }
1.882 albertel 12521:
1.1139 www 12522: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12523: $location = $file;
1.609 banghart 12524: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12525: my ($udom,$uname,$filename)=
1.811 albertel 12526: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12527: my $home=&homeserver($uname,$udom);
12528: my $is_me=0;
12529: my @ids=¤t_machine_ids();
12530: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12531: if ($is_me) {
1.1117 foxr 12532: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12533: } else {
12534: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12535: $udom.'/'.$uname.'/'.$filename;
12536: }
1.882 albertel 12537: } elsif ($file =~ m-^/adm/-) {
12538: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12539: } else {
12540: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12541: $file=~s:^/(res|priv)/:/:;
12542: my $space=$1;
1.590 banghart 12543: if ( !( $file =~ m:^/:) ) {
12544: $location = $dir. '/'.$file;
12545: } else {
1.1142 raeburn 12546: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12547: }
1.59 albertel 12548: }
1.590 banghart 12549: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12550: while ($location=~m{/\.\./}) {
12551: if ($location =~ m{/[^/]+/\.\./}) {
12552: $location=~ s{/[^/]+/\.\./}{/}g;
12553: } else {
12554: $location=~ s{/\.\./}{/}g;
12555: }
12556: } #remove dir/..
1.590 banghart 12557: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12558: return $location;
1.46 www 12559: }
1.36 albertel 12560:
1.46 www 12561: sub hreflocation {
12562: my ($dir,$file)=@_;
1.980 raeburn 12563: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12564: $file=filelocation($dir,$file);
1.700 albertel 12565: } elsif ($file=~m-^/adm/-) {
12566: $file=~s-^/adm/wrapper/-/-;
12567: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12568: }
12569: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12570: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12571: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12572: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12573: {/uploaded/$1/$2/}x;
1.46 www 12574: }
1.913 albertel 12575: if ($file=~ m{^/userfiles/}) {
12576: $file =~ s{^/userfiles/}{/uploaded/};
12577: }
1.462 albertel 12578: return $file;
1.465 albertel 12579: }
12580:
1.1139 www 12581:
12582:
12583:
12584:
1.465 albertel 12585: sub current_machine_domains {
1.853 albertel 12586: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12587: }
12588:
12589: sub machine_domains {
12590: my ($hostname) = @_;
1.465 albertel 12591: my @domains;
1.838 albertel 12592: my %hostname = &all_hostnames();
1.465 albertel 12593: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12594: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12595: if ($hostname eq $name) {
1.844 albertel 12596: push(@domains,&host_domain($id));
1.465 albertel 12597: }
12598: }
12599: return @domains;
12600: }
12601:
12602: sub current_machine_ids {
1.853 albertel 12603: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12604: }
12605:
12606: sub machine_ids {
12607: my ($hostname) = @_;
12608: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12609: my @ids;
1.888 albertel 12610: my %name_to_host = &all_names();
1.889 albertel 12611: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12612: return @{ $name_to_host{$hostname} };
12613: }
12614: return;
1.31 www 12615: }
12616:
1.824 raeburn 12617: sub additional_machine_domains {
12618: my @domains;
1.1172.2.93.4 7(raebur 12619:7): open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 12620: while( my $line = <$fh>) {
12621: $line =~ s/\s//g;
12622: push(@domains,$line);
12623: }
12624: return @domains;
12625: }
12626:
12627: sub default_login_domain {
12628: my $domain = $perlvar{'lonDefDomain'};
12629: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12630: foreach my $posdom (¤t_machine_domains(),
12631: &additional_machine_domains()) {
12632: if (lc($posdom) eq lc($testdomain)) {
12633: $domain=$posdom;
12634: last;
12635: }
12636: }
12637: return $domain;
12638: }
12639:
1.31 www 12640: # ------------------------------------------------------------- Declutters URLs
12641:
12642: sub declutter {
12643: my $thisfn=shift;
1.569 albertel 12644: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12645: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12646: $thisfn=~s{^/home/httpd/html}{};
12647: }
1.31 www 12648: $thisfn=~s/^\///;
1.697 albertel 12649: $thisfn=~s|^adm/wrapper/||;
12650: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12651: $thisfn=~s/^res\///;
1.1172 bisitz 12652: $thisfn=~s/^priv\///;
1.1032 raeburn 12653: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12654: $thisfn=~s/\?.+$//;
12655: }
1.268 www 12656: return $thisfn;
12657: }
12658:
12659: # ------------------------------------------------------------- Clutter up URLs
12660:
12661: sub clutter {
12662: my $thisfn='/'.&declutter(shift);
1.887 albertel 12663: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12664: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12665: $thisfn='/res'.$thisfn;
12666: }
1.1031 raeburn 12667: if ($thisfn !~m|^/adm|) {
12668: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12669: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12670: } else {
12671: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12672: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12673: if ($embstyle eq 'ssi'
12674: || ($embstyle eq 'hdn')
12675: || ($embstyle eq 'rat')
12676: || ($embstyle eq 'prv')
12677: || ($embstyle eq 'ign')) {
12678: #do nothing with these
12679: } elsif (($embstyle eq 'img')
1.695 albertel 12680: || ($embstyle eq 'emb')
12681: || ($embstyle eq 'wrp')) {
12682: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12683: } elsif ($embstyle eq 'unk'
12684: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12685: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12686: } else {
1.718 www 12687: # &logthis("Got a blank emb style");
1.695 albertel 12688: }
1.694 albertel 12689: }
1.1172.2.93.4 2(raebur 12690:7): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
12691:7): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12692: }
1.31 www 12693: return $thisfn;
1.12 www 12694: }
12695:
1.787 albertel 12696: sub clutter_with_no_wrapper {
12697: my $uri = &clutter(shift);
12698: if ($uri =~ m-^/adm/-) {
12699: $uri =~ s-^/adm/wrapper/-/-;
12700: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12701: }
12702: return $uri;
12703: }
12704:
1.557 albertel 12705: sub freeze_escape {
12706: my ($value)=@_;
12707: if (ref($value)) {
12708: $value=&nfreeze($value);
12709: return '__FROZEN__'.&escape($value);
12710: }
12711: return &escape($value);
12712: }
12713:
1.11 www 12714:
1.557 albertel 12715: sub thaw_unescape {
12716: my ($value)=@_;
12717: if ($value =~ /^__FROZEN__/) {
12718: substr($value,0,10,undef);
12719: $value=&unescape($value);
12720: return &thaw($value);
12721: }
12722: return &unescape($value);
12723: }
12724:
1.436 albertel 12725: sub correct_line_ends {
12726: my ($result)=@_;
12727: $$result =~s/\r\n/\n/mg;
12728: $$result =~s/\r/\n/mg;
1.415 albertel 12729: }
1.1 albertel 12730: # ================================================================ Main Program
12731:
1.184 www 12732: sub goodbye {
1.204 albertel 12733: &logthis("Starting Shut down");
1.443 albertel 12734: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12735: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12736: #converted
1.599 albertel 12737: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12738: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12739: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12740: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12741: #1.1 only
1.870 albertel 12742: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12743: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12744: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12745: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12746: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12747: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12748: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12749: &flushcourselogs();
12750: &logthis("Shutting down");
12751: }
12752:
1.852 albertel 12753: sub get_dns {
1.1172.2.17 raeburn 12754: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12755: if (!$ignore_cache) {
12756: my ($content,$cached)=
12757: &Apache::lonnet::is_cached_new('dns',$url);
12758: if ($cached) {
1.1172.2.17 raeburn 12759: &$func($content,$hashref);
1.869 albertel 12760: return;
12761: }
12762: }
12763:
12764: my %alldns;
1.1172.2.93.4 7(raebur 12765:7): open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 12766: foreach my $dns (<$config>) {
12767: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12768: my $line = $1;
12769: my ($host,$protocol) = split(/:/,$line);
12770: if ($protocol ne 'https') {
12771: $protocol = 'http';
12772: }
12773: $alldns{$host} = $protocol;
1.869 albertel 12774: }
12775: while (%alldns) {
1.1172.2.52 raeburn 12776: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12777: my $ua=new LWP::UserAgent;
1.1134 raeburn 12778: $ua->timeout(30);
1.979 raeburn 12779: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12780: my $response=$ua->request($request);
1.979 raeburn 12781: delete($alldns{$dns});
1.852 albertel 12782: next if ($response->is_error());
12783: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12784: unless ($nocache) {
1.1172.2.23 raeburn 12785: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12786: }
12787: &$func(\@content,$hashref);
1.869 albertel 12788: return;
1.852 albertel 12789: }
12790: close($config);
1.871 albertel 12791: my $which = (split('/',$url))[3];
12792: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.93.4 7(raebur 12793:7): open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12794: my @content = <$config>;
1.1172.2.17 raeburn 12795: &$func(\@content,$hashref);
12796: return;
12797: }
12798:
12799: # ------------------------------------------------------Get DNS checksums file
12800: sub parse_dns_checksums_tab {
12801: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12802: my $lonhost = $perlvar{'lonHostID'};
12803: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12804: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12805: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12806: my $webconfdir = '/etc/httpd/conf';
12807: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12808: $webconfdir = '/etc/apache2';
12809: } elsif ($distro =~ /^sles(\d+)$/) {
12810: if ($1 >= 10) {
12811: $webconfdir = '/etc/apache2';
12812: }
12813: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12814: if ($1 >= 10.0) {
12815: $webconfdir = '/etc/apache2';
12816: }
12817: }
1.1172.2.17 raeburn 12818: my ($release,$timestamp) = split(/\-/,$loncaparev);
12819: my (%chksum,%revnum);
12820: if (ref($lines) eq 'ARRAY') {
12821: chomp(@{$lines});
1.1172.2.34 raeburn 12822: my $version = shift(@{$lines});
12823: if ($version eq $release) {
1.1172.2.17 raeburn 12824: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12825: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12826: if ($file =~ m{^/etc/httpd/conf}) {
12827: if ($webconfdir eq '/etc/apache2') {
12828: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12829: }
12830: }
1.1172.2.34 raeburn 12831: $chksum{$file} = $shasum;
12832: $revnum{$file} = $version;
1.1172.2.17 raeburn 12833: }
12834: if (ref($hashref) eq 'HASH') {
12835: %{$hashref} = (
12836: sums => \%chksum,
12837: versions => \%revnum,
12838: );
12839: }
12840: }
12841: }
1.869 albertel 12842: return;
1.852 albertel 12843: }
1.1172.2.17 raeburn 12844:
12845: sub fetch_dns_checksums {
12846: my %checksums;
1.1172.2.34 raeburn 12847: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12848: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12849: my ($release,$timestamp) = split(/\-/,$loncaparev);
12850: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12851: \%checksums);
12852: return \%checksums;
12853: }
12854:
1.327 albertel 12855: # ------------------------------------------------------------ Read domain file
12856: {
1.852 albertel 12857: my $loaded;
1.846 albertel 12858: my %domain;
12859:
1.852 albertel 12860: sub parse_domain_tab {
12861: my ($lines) = @_;
12862: foreach my $line (@$lines) {
12863: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12864:
1.846 albertel 12865: chomp($line);
1.852 albertel 12866: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12867: my %this_domain;
12868: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12869: 'lang_def', 'city', 'longi', 'lati',
12870: 'primary') {
12871: $this_domain{$field} = shift(@elements);
12872: }
12873: $domain{$name} = \%this_domain;
1.852 albertel 12874: }
12875: }
1.864 albertel 12876:
12877: sub reset_domain_info {
12878: undef($loaded);
12879: undef(%domain);
12880: }
12881:
1.852 albertel 12882: sub load_domain_tab {
1.1172.2.70 raeburn 12883: my ($ignore_cache,$nocache) = @_;
12884: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12885: my $fh;
1.1172.2.93.4 7(raebur 12886:7): if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 12887: my @lines = <$fh>;
12888: &parse_domain_tab(\@lines);
1.448 albertel 12889: }
1.852 albertel 12890: close($fh);
12891: $loaded = 1;
1.327 albertel 12892: }
1.846 albertel 12893:
12894: sub domain {
1.852 albertel 12895: &load_domain_tab() if (!$loaded);
12896:
1.846 albertel 12897: my ($name,$what) = @_;
12898: return if ( !exists($domain{$name}) );
12899:
12900: if (!$what) {
12901: return $domain{$name}{'description'};
12902: }
12903: return $domain{$name}{$what};
12904: }
1.974 raeburn 12905:
12906: sub domain_info {
12907: &load_domain_tab() if (!$loaded);
12908: return %domain;
12909: }
12910:
1.327 albertel 12911: }
12912:
12913:
1.1 albertel 12914: # ------------------------------------------------------------- Read hosts file
12915: {
1.838 albertel 12916: my %hostname;
1.844 albertel 12917: my %hostdom;
1.845 albertel 12918: my %libserv;
1.852 albertel 12919: my $loaded;
1.888 albertel 12920: my %name_to_host;
1.1074 raeburn 12921: my %internetdom;
1.1107 raeburn 12922: my %LC_dns_serv;
1.852 albertel 12923:
12924: sub parse_hosts_tab {
12925: my ($file) = @_;
12926: foreach my $configline (@$file) {
12927: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12928: chomp($configline);
12929: if ($configline =~ /^\^/) {
12930: if ($configline =~ /^\^([\w.\-]+)/) {
12931: $LC_dns_serv{$1} = 1;
12932: }
12933: next;
12934: }
1.1074 raeburn 12935: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12936: $name=~s/\s//g;
12937: if ($id && $domain && $role && $name) {
1.1172.2.93.4 3(raebur 12938:7): if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
12939:7): my $curr = $hostname{$id};
12940:7): my $skip;
12941:7): if (ref($name_to_host{$curr}) eq 'ARRAY') {
12942:7): if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
12943:7): $skip = 1;
12944:7): } else {
12945:7): @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
12946:7): }
12947:7): }
12948:7): unless ($skip) {
12949:7): push(@{$name_to_host{$name}},$id);
12950:7): }
12951:7): } else {
12952:7): push(@{$name_to_host{$name}},$id);
12953:7): }
1.852 albertel 12954: $hostname{$id}=$name;
12955: $hostdom{$id}=$domain;
12956: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12957: if (defined($protocol)) {
12958: if ($protocol eq 'https') {
12959: $protocol{$id} = $protocol;
12960: } else {
12961: $protocol{$id} = 'http';
12962: }
1.968 raeburn 12963: } else {
1.969 raeburn 12964: $protocol{$id} = 'http';
1.968 raeburn 12965: }
1.1074 raeburn 12966: if (defined($intdom)) {
12967: $internetdom{$id} = $intdom;
12968: }
1.852 albertel 12969: }
12970: }
12971: }
1.864 albertel 12972:
12973: sub reset_hosts_info {
1.897 albertel 12974: &purge_remembered();
1.864 albertel 12975: &reset_domain_info();
12976: &reset_hosts_ip_info();
1.892 albertel 12977: undef(%name_to_host);
1.864 albertel 12978: undef(%hostname);
12979: undef(%hostdom);
12980: undef(%libserv);
12981: undef($loaded);
12982: }
1.1 albertel 12983:
1.852 albertel 12984: sub load_hosts_tab {
1.1172.2.70 raeburn 12985: my ($ignore_cache,$nocache) = @_;
12986: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.93.4 7(raebur 12987:7): open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 12988: my @config = <$config>;
12989: &parse_hosts_tab(\@config);
12990: close($config);
12991: $loaded=1;
1.1 albertel 12992: }
1.852 albertel 12993:
1.838 albertel 12994: sub hostname {
1.852 albertel 12995: &load_hosts_tab() if (!$loaded);
12996:
1.838 albertel 12997: my ($lonid) = @_;
12998: return $hostname{$lonid};
12999: }
1.845 albertel 13000:
1.838 albertel 13001: sub all_hostnames {
1.852 albertel 13002: &load_hosts_tab() if (!$loaded);
13003:
1.838 albertel 13004: return %hostname;
13005: }
1.845 albertel 13006:
1.888 albertel 13007: sub all_names {
1.1172.2.70 raeburn 13008: my ($ignore_cache,$nocache) = @_;
13009: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13010:
13011: return %name_to_host;
13012: }
13013:
1.974 raeburn 13014: sub all_host_domain {
13015: &load_hosts_tab() if (!$loaded);
13016: return %hostdom;
13017: }
13018:
1.845 albertel 13019: sub is_library {
1.852 albertel 13020: &load_hosts_tab() if (!$loaded);
13021:
1.845 albertel 13022: return exists($libserv{$_[0]});
13023: }
13024:
13025: sub all_library {
1.852 albertel 13026: &load_hosts_tab() if (!$loaded);
13027:
1.845 albertel 13028: return %libserv;
13029: }
13030:
1.1062 droeschl 13031: sub unique_library {
13032: #2x reverse removes all hostnames that appear more than once
13033: my %unique = reverse &all_library();
13034: return reverse %unique;
13035: }
13036:
1.841 albertel 13037: sub get_servers {
1.852 albertel 13038: &load_hosts_tab() if (!$loaded);
13039:
1.841 albertel 13040: my ($domain,$type) = @_;
13041: my %possible_hosts = ($type eq 'library') ? %libserv
13042: : %hostname;
13043: my %result;
1.842 albertel 13044: if (ref($domain) eq 'ARRAY') {
13045: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13046: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13047: $result{$host} = $hostname;
13048: }
13049: }
13050: } else {
13051: while ( my ($host,$hostname) = each(%possible_hosts)) {
13052: if ($hostdom{$host} eq $domain) {
13053: $result{$host} = $hostname;
13054: }
1.841 albertel 13055: }
13056: }
13057: return %result;
13058: }
1.845 albertel 13059:
1.1062 droeschl 13060: sub get_unique_servers {
13061: my %unique = reverse &get_servers(@_);
13062: return reverse %unique;
13063: }
13064:
1.844 albertel 13065: sub host_domain {
1.852 albertel 13066: &load_hosts_tab() if (!$loaded);
13067:
1.844 albertel 13068: my ($lonid) = @_;
13069: return $hostdom{$lonid};
13070: }
13071:
1.841 albertel 13072: sub all_domains {
1.852 albertel 13073: &load_hosts_tab() if (!$loaded);
13074:
1.841 albertel 13075: my %seen;
13076: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13077: return @uniq;
13078: }
1.1074 raeburn 13079:
13080: sub internet_dom {
13081: &load_hosts_tab() if (!$loaded);
13082:
13083: my ($lonid) = @_;
13084: return $internetdom{$lonid};
13085: }
1.1107 raeburn 13086:
13087: sub is_LC_dns {
13088: &load_hosts_tab() if (!$loaded);
13089:
13090: my ($hostname) = @_;
13091: return exists($LC_dns_serv{$hostname});
13092: }
13093:
1.1 albertel 13094: }
13095:
1.847 albertel 13096: {
13097: my %iphost;
1.856 albertel 13098: my %name_to_ip;
13099: my %lonid_to_ip;
1.869 albertel 13100:
1.847 albertel 13101: sub get_hosts_from_ip {
13102: my ($ip) = @_;
13103: my %iphosts = &get_iphost();
13104: if (ref($iphosts{$ip})) {
13105: return @{$iphosts{$ip}};
13106: }
13107: return;
1.839 albertel 13108: }
1.864 albertel 13109:
13110: sub reset_hosts_ip_info {
13111: undef(%iphost);
13112: undef(%name_to_ip);
13113: undef(%lonid_to_ip);
13114: }
1.856 albertel 13115:
13116: sub get_host_ip {
13117: my ($lonid) = @_;
13118: if (exists($lonid_to_ip{$lonid})) {
13119: return $lonid_to_ip{$lonid};
13120: }
13121: my $name=&hostname($lonid);
13122: my $ip = gethostbyname($name);
13123: return if (!$ip || length($ip) ne 4);
13124: $ip=inet_ntoa($ip);
13125: $name_to_ip{$name} = $ip;
13126: $lonid_to_ip{$lonid} = $ip;
13127: return $ip;
13128: }
1.847 albertel 13129:
13130: sub get_iphost {
1.1172.2.70 raeburn 13131: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13132:
1.869 albertel 13133: if (!$ignore_cache) {
13134: if (%iphost) {
13135: return %iphost;
13136: }
13137: my ($ip_info,$cached)=
13138: &Apache::lonnet::is_cached_new('iphost','iphost');
13139: if ($cached) {
13140: %iphost = %{$ip_info->[0]};
13141: %name_to_ip = %{$ip_info->[1]};
13142: %lonid_to_ip = %{$ip_info->[2]};
13143: return %iphost;
13144: }
13145: }
1.894 albertel 13146:
13147: # get yesterday's info for fallback
13148: my %old_name_to_ip;
13149: my ($ip_info,$cached)=
13150: &Apache::lonnet::is_cached_new('iphost','iphost');
13151: if ($cached) {
13152: %old_name_to_ip = %{$ip_info->[1]};
13153: }
13154:
1.1172.2.70 raeburn 13155: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13156: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13157: my $ip;
13158: if (!exists($name_to_ip{$name})) {
13159: $ip = gethostbyname($name);
13160: if (!$ip || length($ip) ne 4) {
1.894 albertel 13161: if (defined($old_name_to_ip{$name})) {
13162: $ip = $old_name_to_ip{$name};
13163: &logthis("Can't find $name defaulting to old $ip");
13164: } else {
13165: &logthis("Name $name no IP found");
13166: next;
13167: }
13168: } else {
13169: $ip=inet_ntoa($ip);
1.847 albertel 13170: }
13171: $name_to_ip{$name} = $ip;
13172: } else {
13173: $ip = $name_to_ip{$name};
1.653 albertel 13174: }
1.888 albertel 13175: foreach my $id (@{ $name_to_host{$name} }) {
13176: $lonid_to_ip{$id} = $ip;
13177: }
13178: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13179: }
1.1172.2.70 raeburn 13180: unless ($nocache) {
13181: &do_cache_new('iphost','iphost',
13182: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13183: 48*60*60);
13184: }
1.869 albertel 13185:
1.847 albertel 13186: return %iphost;
1.598 albertel 13187: }
13188:
1.992 raeburn 13189: #
13190: # Given a DNS returns the loncapa host name for that DNS
13191: #
13192: sub host_from_dns {
13193: my ($dns) = @_;
13194: my @hosts;
13195: my $ip;
13196:
1.993 raeburn 13197: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13198: $ip = $name_to_ip{$dns};
13199: }
13200: if (!$ip) {
13201: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13202: if (length($ip) == 4) {
13203: $ip = &IO::Socket::inet_ntoa($ip);
13204: }
13205: }
13206: if ($ip) {
13207: @hosts = get_hosts_from_ip($ip);
13208: return $hosts[0];
13209: }
13210: return undef;
1.986 foxr 13211: }
1.992 raeburn 13212:
1.1074 raeburn 13213: sub get_internet_names {
13214: my ($lonid) = @_;
13215: return if ($lonid eq '');
13216: my ($idnref,$cached)=
13217: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13218: if ($cached) {
13219: return $idnref;
13220: }
13221: my $ip = &get_host_ip($lonid);
13222: my @hosts = &get_hosts_from_ip($ip);
13223: my %iphost = &get_iphost();
13224: my (@idns,%seen);
13225: foreach my $id (@hosts) {
13226: my $dom = &host_domain($id);
13227: my $prim_id = &domain($dom,'primary');
13228: my $prim_ip = &get_host_ip($prim_id);
13229: next if ($seen{$prim_ip});
13230: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13231: foreach my $id (@{$iphost{$prim_ip}}) {
13232: my $intdom = &internet_dom($id);
13233: unless (grep(/^\Q$intdom\E$/,@idns)) {
13234: push(@idns,$intdom);
13235: }
13236: }
13237: }
13238: $seen{$prim_ip} = 1;
13239: }
1.1172.2.23 raeburn 13240: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13241: }
13242:
1.986 foxr 13243: }
13244:
1.1079 raeburn 13245: sub all_loncaparevs {
1.1172.2.39 raeburn 13246: 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 2.11);
1.1079 raeburn 13247: }
13248:
1.1172.2.27 raeburn 13249: # ------------------------------------------------------- Read loncaparev table
13250: {
13251: sub load_loncaparevs {
13252: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.93.4 7(raebur 13253:7): if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13254: while (my $configline=<$config>) {
13255: chomp($configline);
13256: my ($hostid,$loncaparev)=split(/:/,$configline);
13257: $loncaparevs{$hostid}=$loncaparev;
13258: }
13259: close($config);
13260: }
13261: }
13262: }
13263: }
13264:
13265: # ----------------------------------------------------- Read serverhostID table
13266: {
13267: sub load_serverhomeIDs {
13268: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.93.4 7(raebur 13269:7): if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 13270: while (my $configline=<$config>) {
13271: chomp($configline);
13272: my ($name,$id)=split(/:/,$configline);
13273: $serverhomeIDs{$name}=$id;
13274: }
13275: close($config);
13276: }
13277: }
13278: }
13279: }
13280:
13281:
1.862 albertel 13282: BEGIN {
13283:
13284: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13285: unless ($readit) {
13286: {
13287: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13288: %perlvar = (%perlvar,%{$configvars});
13289: }
13290:
13291:
1.1 albertel 13292: # ------------------------------------------------------ Read spare server file
13293: {
1.1172.2.93.4 7(raebur 13294:7): open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13295:
13296: while (my $configline=<$config>) {
13297: chomp($configline);
1.284 matthew 13298: if ($configline) {
1.784 albertel 13299: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13300: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13301: push(@{ $spareid{$type} }, $host);
1.1 albertel 13302: }
13303: }
1.448 albertel 13304: close($config);
1.1 albertel 13305: }
1.11 www 13306: # ------------------------------------------------------------ Read permissions
13307: {
1.1172.2.93.4 7(raebur 13308:7): open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13309:
13310: while (my $configline=<$config>) {
1.448 albertel 13311: chomp($configline);
13312: if ($configline) {
13313: my ($role,$perm)=split(/ /,$configline);
13314: if ($perm ne '') { $pr{$role}=$perm; }
13315: }
1.11 www 13316: }
1.448 albertel 13317: close($config);
1.11 www 13318: }
13319:
13320: # -------------------------------------------- Read plain texts for permissions
13321: {
1.1172.2.93.4 7(raebur 13322:7): open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13323:
13324: while (my $configline=<$config>) {
1.448 albertel 13325: chomp($configline);
13326: if ($configline) {
1.742 raeburn 13327: my ($short,@plain)=split(/:/,$configline);
13328: %{$prp{$short}} = ();
13329: if (@plain > 0) {
13330: $prp{$short}{'std'} = $plain[0];
13331: for (my $i=1; $i<@plain; $i++) {
13332: $prp{$short}{'alt'.$i} = $plain[$i];
13333: }
13334: }
1.448 albertel 13335: }
1.135 www 13336: }
1.448 albertel 13337: close($config);
1.135 www 13338: }
13339:
13340: # ---------------------------------------------------------- Read package table
13341: {
1.1172.2.93.4 7(raebur 13342:7): open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13343:
13344: while (my $configline=<$config>) {
1.483 albertel 13345: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13346: chomp($configline);
13347: my ($short,$plain)=split(/:/,$configline);
13348: my ($pack,$name)=split(/\&/,$short);
13349: if ($plain ne '') {
13350: $packagetab{$pack.'&'.$name.'&name'}=$name;
13351: $packagetab{$short}=$plain;
13352: }
1.11 www 13353: }
1.448 albertel 13354: close($config);
1.329 matthew 13355: }
13356:
1.1172.2.27 raeburn 13357: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13358:
1.1172.2.27 raeburn 13359: &load_loncaparevs();
13360:
13361: # ------------------------------------------------------- Read serverhostID table
13362:
13363: &load_serverhomeIDs();
1.1074 raeburn 13364:
1.1172.2.27 raeburn 13365: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13366: {
13367: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13368: if (-e $file) {
13369: my $parser = HTML::LCParser->new($file);
13370: while (my $token = $parser->get_token()) {
13371: if ($token->[0] eq 'S') {
13372: my $item = $token->[1];
13373: my $name = $token->[2]{'name'};
13374: my $value = $token->[2]{'value'};
13375: if ($item ne '' && $name ne '' && $value ne '') {
13376: my $release = $parser->get_text();
13377: $release =~ s/(^\s*|\s*$ )//gx;
13378: $needsrelease{$item.':'.$name.':'.$value} = $release;
13379: }
13380: }
13381: }
13382: }
1.1073 raeburn 13383: }
13384:
1.1138 raeburn 13385: # ---------------------------------------------------------- Read managers table
13386: {
13387: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.93.4 7(raebur 13388:7): if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 13389: while (my $configline=<$config>) {
13390: chomp($configline);
13391: next if ($configline =~ /^\#/);
13392: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13393: $managerstab{$configline} = 1;
13394: }
13395: }
13396: close($config);
13397: }
13398: }
13399: }
13400:
1.329 matthew 13401: # ------------- set up temporary directory
13402: {
1.1117 foxr 13403: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13404:
1.11 www 13405: }
13406:
1.794 albertel 13407: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13408: 'compress_threshold'=> 20_000,
13409: });
1.185 www 13410:
1.281 www 13411: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13412: $dumpcount=0;
1.958 www 13413: $locknum=0;
1.22 www 13414:
1.163 harris41 13415: &logtouch();
1.672 albertel 13416: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13417: $readit=1;
1.564 albertel 13418: {
13419: use integer;
13420: my $test=(2**32)+1;
1.568 albertel 13421: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13422: &logthis(" Detected 64bit platform ($_64bit)");
13423: }
1.195 www 13424: }
1.1 albertel 13425: }
1.179 www 13426:
1.1 albertel 13427: 1;
1.191 harris41 13428: __END__
13429:
1.243 albertel 13430: =pod
13431:
1.191 harris41 13432: =head1 NAME
13433:
1.243 albertel 13434: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13435:
13436: =head1 SYNOPSIS
13437:
1.243 albertel 13438: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13439:
13440: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13441:
1.243 albertel 13442: Common parameters:
13443:
13444: =over 4
13445:
13446: =item *
13447:
13448: $uname : an internal username (if $cname expecting a course Id specifically)
13449:
13450: =item *
13451:
13452: $udom : a domain (if $cdom expecting a course's domain specifically)
13453:
13454: =item *
13455:
13456: $symb : a resource instance identifier
13457:
13458: =item *
13459:
13460: $namespace : the name of a .db file that contains the data needed or
13461: being set.
13462:
13463: =back
13464:
1.394 bowersj2 13465: =head1 OVERVIEW
1.191 harris41 13466:
1.394 bowersj2 13467: lonnet provides subroutines which interact with the
13468: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13469: about classes, users, and resources.
1.243 albertel 13470:
13471: For many of these objects you can also use this to store data about
13472: them or modify them in various ways.
1.191 harris41 13473:
1.394 bowersj2 13474: =head2 Symbs
1.191 harris41 13475:
1.394 bowersj2 13476: To identify a specific instance of a resource, LON-CAPA uses symbols
13477: or "symbs"X<symb>. These identifiers are built from the URL of the
13478: map, the resource number of the resource in the map, and the URL of
13479: the resource itself. The latter is somewhat redundant, but might help
13480: if maps change.
13481:
13482: An example is
13483:
13484: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13485:
13486: The respective map entry is
13487:
13488: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13489: title="Problem 2">
13490: </resource>
13491:
13492: Symbs are used by the random number generator, as well as to store and
13493: restore data specific to a certain instance of for example a problem.
13494:
13495: =head2 Storing And Retrieving Data
13496:
13497: X<store()>X<cstore()>X<restore()>Three of the most important functions
13498: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13499: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13500: is is the non-critical message twin of cstore. These functions are for
13501: handlers to store a perl hash to a user's permanent data space in an
13502: easy manner, and to retrieve it again on another call. It is expected
13503: that a handler would use this once at the beginning to retrieve data,
13504: and then again once at the end to send only the new data back.
13505:
13506: The data is stored in the user's data directory on the user's
13507: homeserver under the ID of the course.
13508:
13509: The hash that is returned by restore will have all of the previous
13510: value for all of the elements of the hash.
13511:
13512: Example:
13513:
13514: #creating a hash
13515: my %hash;
13516: $hash{'foo'}='bar';
13517:
13518: #storing it
13519: &Apache::lonnet::cstore(\%hash);
13520:
13521: #changing a value
13522: $hash{'foo'}='notbar';
13523:
13524: #adding a new value
13525: $hash{'bar'}='foo';
13526: &Apache::lonnet::cstore(\%hash);
13527:
13528: #retrieving the hash
13529: my %history=&Apache::lonnet::restore();
13530:
13531: #print the hash
13532: foreach my $key (sort(keys(%history))) {
13533: print("\%history{$key} = $history{$key}");
13534: }
13535:
13536: Will print out:
1.191 harris41 13537:
1.394 bowersj2 13538: %history{1:foo} = bar
13539: %history{1:keys} = foo:timestamp
13540: %history{1:timestamp} = 990455579
13541: %history{2:bar} = foo
13542: %history{2:foo} = notbar
13543: %history{2:keys} = foo:bar:timestamp
13544: %history{2:timestamp} = 990455580
13545: %history{bar} = foo
13546: %history{foo} = notbar
13547: %history{timestamp} = 990455580
13548: %history{version} = 2
13549:
13550: Note that the special hash entries C<keys>, C<version> and
13551: C<timestamp> were added to the hash. C<version> will be equal to the
13552: total number of versions of the data that have been stored. The
13553: C<timestamp> attribute will be the UNIX time the hash was
13554: stored. C<keys> is available in every historical section to list which
13555: keys were added or changed at a specific historical revision of a
13556: hash.
13557:
13558: B<Warning>: do not store the hash that restore returns directly. This
13559: will cause a mess since it will restore the historical keys as if the
13560: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13561:
1.394 bowersj2 13562: Calling convention:
1.191 harris41 13563:
1.1172.2.27 raeburn 13564: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13565: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13566:
1.394 bowersj2 13567: For more detailed information, see lonnet specific documentation.
1.191 harris41 13568:
1.394 bowersj2 13569: =head1 RETURN MESSAGES
1.191 harris41 13570:
1.394 bowersj2 13571: =over 4
1.191 harris41 13572:
1.394 bowersj2 13573: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13574:
1.394 bowersj2 13575: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13576: when the connection is brought back up
1.191 harris41 13577:
1.394 bowersj2 13578: =item * B<con_failed>: unable to contact remote host and unable to save message
13579: for later delivery
1.191 harris41 13580:
1.967 bisitz 13581: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13582:
1.394 bowersj2 13583: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13584: that was requested
1.191 harris41 13585:
1.243 albertel 13586: =back
1.191 harris41 13587:
1.243 albertel 13588: =head1 PUBLIC SUBROUTINES
1.191 harris41 13589:
1.243 albertel 13590: =head2 Session Environment Functions
1.191 harris41 13591:
1.243 albertel 13592: =over 4
1.191 harris41 13593:
1.394 bowersj2 13594: =item *
13595: X<appenv()>
1.949 raeburn 13596: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13597: the user envirnoment file, and will be restored for each access this
1.620 albertel 13598: user makes during this session, also modifies the %env for the current
1.949 raeburn 13599: process. Optional rolesarrayref - if defined contains a reference to an array
13600: of roles which are exempt from the restriction on modifying user.role entries
13601: in the user's environment.db and in %env.
1.191 harris41 13602:
13603: =item *
1.394 bowersj2 13604: X<delenv()>
1.987 raeburn 13605: B<delenv($delthis,$regexp)>: removes all items from the session
13606: environment file that begin with $delthis. If the
13607: optional second arg - $regexp - is true, $delthis is treated as a
13608: regular expression, otherwise \Q$delthis\E is used.
13609: The values are also deleted from the current processes %env.
1.191 harris41 13610:
1.795 albertel 13611: =item * get_env_multiple($name)
13612:
13613: gets $name from the %env hash, it seemlessly handles the cases where multiple
13614: values may be defined and end up as an array ref.
13615:
13616: returns an array of values
13617:
1.243 albertel 13618: =back
13619:
13620: =head2 User Information
1.191 harris41 13621:
1.243 albertel 13622: =over 4
1.191 harris41 13623:
13624: =item *
1.394 bowersj2 13625: X<queryauthenticate()>
13626: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13627: authentication scheme
13628:
13629: =item *
1.394 bowersj2 13630: X<authenticate()>
1.1073 raeburn 13631: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13632: authenticate user from domain's lib servers (first use the current
13633: one). C<$upass> should be the users password.
1.1073 raeburn 13634: $checkdefauth is optional (value is 1 if a check should be made to
13635: authenticate user using default authentication method, and allow
13636: account creation if username does not have account in the domain).
13637: $clientcancheckhost is optional (value is 1 if checking whether the
13638: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13639:
13640: =item *
1.394 bowersj2 13641: X<homeserver()>
13642: B<homeserver($uname,$udom)>: find the server which has
13643: the user's directory and files (there must be only one), this caches
13644: the answer, and also caches if there is a borken connection.
1.191 harris41 13645:
13646: =item *
1.394 bowersj2 13647: X<idget()>
13648: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13649: (IDs are a unique resource in a domain, there must be only 1 ID per
13650: username, and only 1 username per ID in a specific domain) (returns
13651: hash: id=>name,id=>name)
1.191 harris41 13652:
13653: =item *
1.394 bowersj2 13654: X<idrget()>
13655: B<idrget($udom,@unames)>: find the IDs behind a list of
13656: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13657:
13658: =item *
1.394 bowersj2 13659: X<idput()>
13660: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13661:
13662: =item *
1.394 bowersj2 13663: X<rolesinit()>
1.1169 droeschl 13664: B<rolesinit($udom,$username)>: get user privileges.
13665: returns user role, first access and timer interval hashes
1.243 albertel 13666:
13667: =item *
1.1171 droeschl 13668: X<privileged()>
13669: B<privileged($username,$domain)>: returns a true if user has a
13670: privileged and active role (i.e. su or dc), false otherwise.
13671:
13672: =item *
1.551 albertel 13673: X<getsection()>
13674: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13675: course $cname, return section name/number or '' for "not in course"
13676: and '-1' for "no section"
13677:
13678: =item *
1.394 bowersj2 13679: X<userenvironment()>
13680: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13681: passed in @what from the requested user's environment, returns a hash
13682:
1.858 raeburn 13683: =item *
13684: X<userlog_query()>
1.859 albertel 13685: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13686: activity.log file. %filters defines filters applied when parsing the
13687: log file. These can be start or end timestamps, or the type of action
13688: - log to look for Login or Logout events, check for Checkin or
13689: Checkout, role for role selection. The response is in the form
13690: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13691: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13692:
1.243 albertel 13693: =back
13694:
13695: =head2 User Roles
13696:
13697: =over 4
13698:
13699: =item *
13700:
1.1172.2.65 raeburn 13701: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13702: returns codes for allowed actions.
13703:
13704: The first argument is required, all others are optional.
13705:
13706: $priv is the privilege being checked.
13707: $uri contains additional information about what is being checked for access (e.g.,
13708: URL, course ID etc.).
13709: $symb is the unique resource instance identifier in a course; if needed,
13710: but not provided, it will be retrieved via a call to &symbread().
13711: $role is the role for which a priv is being checked (only used if priv is evb).
13712: $clientip is the user's IP address (only used when checking for access to portfolio
13713: files).
13714: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13715: prevents recursive calls to &allowed.
13716:
1.243 albertel 13717: F: full access
13718: U,I,K: authentication modes (cxx only)
13719: '': forbidden
13720: 1: user needs to choose course
13721: 2: browse allowed
1.766 albertel 13722: A: passphrase authentication needed
1.1172.2.65 raeburn 13723: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13724:
13725: =item *
13726:
1.1172.2.13 raeburn 13727: constructaccess($url,$setpriv) : check for access to construction space URL
13728:
13729: See if the owner domain and name in the URL match those in the
13730: expected environment. If so, return three element list
13731: ($ownername,$ownerdomain,$ownerhome).
13732:
13733: Otherwise return the null string.
13734:
13735: If second argument 'setpriv' is true, it assigns the privileges,
13736: and returns the same three element list, unless the owner has
13737: blocked "ad hoc" Domain Coordinator access to the Author Space,
13738: in which case the null string is returned.
13739:
13740: =item *
13741:
1.1172.2.84 raeburn 13742: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13743: define a custom role rolename set privileges in format of lonTabs/roles.tab
13744: for system, domain, and course level. $uname and $udom are optional (current
13745: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13746:
13747: =item *
13748:
1.988 raeburn 13749: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13750: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13751: $type is Course (default) or Community.
1.988 raeburn 13752: If $forcedefault evaluates to true, text returned will be default
13753: text for $type. Otherwise, if this is a course, the text returned
13754: will be a custom name for the role (if defined in the course's
13755: environment). If no custom name is defined the default is returned.
13756:
1.832 raeburn 13757: =item *
13758:
1.1172.2.23 raeburn 13759: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13760: All arguments are optional. Returns a hash of a roles, either for
13761: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13762: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13763: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13764: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13765: For each key, value is set to colon-separated start and end times for
13766: the role. If no username and domain are specified, will default to
1.934 raeburn 13767: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13768: of role statuses (active, future or previous), roles
13769: (e.g., cc,in, st etc.) and domains of the roles which can be used
13770: to restrict the list of roles reported. If no array ref is
13771: provided for types, will default to return only active roles.
1.834 albertel 13772:
1.1172.2.13 raeburn 13773: =item *
13774:
13775: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13776: user: $uname:$udom has a role in the course: $cdom_$cnum.
13777:
13778: Additional optional arguments are: $type (if role checking is to be restricted
13779: to certain user status types -- previous (expired roles), active (currently
13780: available roles) or future (roles available in the future), and
13781: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13782: have active Domain Coordinator role in course's domain or in additional
13783: domains (specified in 'Domains to check for privileged users' in course
13784: environment -- set via: Course Settings -> Classlists and staff listing).
13785:
13786: =item *
13787:
13788: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13789: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13790: $possdomains and $possroles are optional array refs -- to domains to check and
13791: roles to check. If $possdomains is not specified, a dump will be done of the
13792: users' roles.db to check for a dc or su role in any domain. This can be
13793: time consuming if &privileged is called repeatedly (e.g., when displaying a
13794: classlist), so in such cases, supplying a $possdomains array is preferred, as
13795: this then allows &privileged_by_domain() to be used, which caches the identity
13796: of privileged users, eliminating the need for repeated calls to &dump().
13797:
13798: =item *
13799:
13800: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13801: where the outer hash keys are domains specified in the $possdomains array ref,
13802: next inner hash keys are privileged roles specified in the $roles array ref,
13803: and the innermost hash contains key = value pairs for username:domain = end:start
13804: for active or future "privileged" users with that role in that domain. To avoid
13805: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13806: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13807:
1.243 albertel 13808: =back
13809:
13810: =head2 User Modification
13811:
13812: =over 4
13813:
13814: =item *
13815:
1.957 raeburn 13816: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13817: user for the level given by URL. Optional start and end dates (leave empty
13818: string or zero for "no date")
1.191 harris41 13819:
13820: =item *
13821:
1.243 albertel 13822: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13823: change a users, password, possible return values are: ok,
13824: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13825: refused
1.191 harris41 13826:
13827: =item *
13828:
1.243 albertel 13829: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13830:
13831: =item *
13832:
1.1058 raeburn 13833: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13834: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13835:
13836: will update user information (firstname,middlename,lastname,generation,
13837: permanentemail), and if forceid is true, student/employee ID also.
13838: A user's institutional affiliation(s) can also be updated.
13839: User information fields will not be overwritten with empty entries
13840: unless the field is included in the $candelete array reference.
13841: This array is included when a single user is modified via "Manage Users",
13842: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13843:
13844: =item *
13845:
1.286 matthew 13846: modifystudent
13847:
1.957 raeburn 13848: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13849: The course id is resolved based on the current user's environment.
13850: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13851: associated with a course.
13852:
1.297 matthew 13853: This call is essentially a wrapper for lonnet::modifyuser and
13854: lonnet::modify_student_enrollment
1.286 matthew 13855:
13856: Inputs:
13857:
13858: =over 4
13859:
1.957 raeburn 13860: =item B<$udom> Student's loncapa domain
1.286 matthew 13861:
1.957 raeburn 13862: =item B<$uname> Student's loncapa login name
1.286 matthew 13863:
1.964 bisitz 13864: =item B<$uid> Student/Employee ID
1.286 matthew 13865:
1.957 raeburn 13866: =item B<$umode> Student's authentication mode
1.286 matthew 13867:
1.957 raeburn 13868: =item B<$upass> Student's password
1.286 matthew 13869:
1.957 raeburn 13870: =item B<$first> Student's first name
1.286 matthew 13871:
1.957 raeburn 13872: =item B<$middle> Student's middle name
1.286 matthew 13873:
1.957 raeburn 13874: =item B<$last> Student's last name
1.286 matthew 13875:
1.957 raeburn 13876: =item B<$gene> Student's generation
1.286 matthew 13877:
1.957 raeburn 13878: =item B<$usec> Student's section in course
1.286 matthew 13879:
13880: =item B<$end> Unix time of the roles expiration
13881:
13882: =item B<$start> Unix time of the roles start date
13883:
13884: =item B<$forceid> If defined, allow $uid to be changed
13885:
13886: =item B<$desiredhome> server to use as home server for student
13887:
1.957 raeburn 13888: =item B<$email> Student's permanent e-mail address
13889:
13890: =item B<$type> Type of enrollment (auto or manual)
13891:
1.963 raeburn 13892: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13893:
13894: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13895:
1.963 raeburn 13896: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13897:
1.963 raeburn 13898: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13899:
1.1172.2.19 raeburn 13900: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13901:
13902: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957 raeburn 13903:
1.286 matthew 13904: =back
1.297 matthew 13905:
13906: =item *
13907:
13908: modify_student_enrollment
13909:
1.1172.2.31 raeburn 13910: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13911: 'role.request.course' must be defined for this function to proceed.
13912:
13913: Inputs:
13914:
13915: =over 4
13916:
1.1172.2.31 raeburn 13917: =item $udom, student's domain
1.297 matthew 13918:
1.1172.2.31 raeburn 13919: =item $uname, student's name
1.297 matthew 13920:
1.1172.2.31 raeburn 13921: =item $uid, student's user id
1.297 matthew 13922:
1.1172.2.31 raeburn 13923: =item $first, student's first name
1.297 matthew 13924:
13925: =item $middle
13926:
13927: =item $last
13928:
13929: =item $gene
13930:
13931: =item $usec
13932:
13933: =item $end
13934:
13935: =item $start
13936:
1.957 raeburn 13937: =item $type
13938:
13939: =item $locktype
13940:
13941: =item $cid
13942:
13943: =item $selfenroll
13944:
13945: =item $context
13946:
1.1172.2.19 raeburn 13947: =item $credits, number of credits student will earn from this class
13948:
1.1172.2.76 raeburn 13949: =item $instsec, institutional course section code for student
13950:
1.297 matthew 13951: =back
13952:
1.191 harris41 13953:
13954: =item *
13955:
1.243 albertel 13956: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13957: custom role; give a custom role to a user for the level given by URL. Specify
13958: name and domain of role author, and role name
1.191 harris41 13959:
13960: =item *
13961:
1.243 albertel 13962: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13963:
13964: =item *
13965:
1.243 albertel 13966: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13967:
13968: =back
13969:
13970: =head2 Course Infomation
13971:
13972: =over 4
1.191 harris41 13973:
13974: =item *
13975:
1.1118 foxr 13976: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13977: specified course id, including all environment settings for the
13978: course, the description of the course will be in the hash under the
13979: key 'description'
1.191 harris41 13980:
1.1118 foxr 13981: $options is an optional parameter that if supplied is a hash reference that controls
13982: what how this function works. It has the following key/values:
13983:
13984: =over 4
13985:
13986: =item freshen_cache
13987:
13988: If defined, and the environment cache for the course is valid, it is
13989: returned in the returned hash.
13990:
13991: =item one_time
13992:
13993: If defined, the last cache time is set to _now_
13994:
13995: =item user
13996:
13997: If defined, the supplied username is used instead of the current user.
13998:
13999:
14000: =back
14001:
1.191 harris41 14002: =item *
14003:
1.624 albertel 14004: resdata($name,$domain,$type,@which) : request for current parameter
14005: setting for a specific $type, where $type is either 'course' or 'user',
14006: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14007: answers for 10 minutes.
1.243 albertel 14008:
1.877 foxr 14009: =item *
14010:
14011: get_courseresdata($courseid, $domain) : dump the entire course resource
14012: data base, returning a hash that is keyed by the resource name and has
14013: values that are the resource value. I believe that the timestamps and
14014: versions are also returned.
14015:
1.1172.2.31 raeburn 14016: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14017: supplemental content area. This routine caches the number of files for
14018: 10 minutes.
14019:
1.243 albertel 14020: =back
14021:
14022: =head2 Course Modification
14023:
14024: =over 4
1.191 harris41 14025:
14026: =item *
14027:
1.243 albertel 14028: writecoursepref($courseid,%prefs) : write preferences (environment
14029: database) for a course
1.191 harris41 14030:
14031: =item *
14032:
1.1011 raeburn 14033: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14034:
14035: =item *
14036:
1.1038 raeburn 14037: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14038:
1.1167 droeschl 14039: =item *
14040:
14041: is_course($courseid), is_course($cdom, $cnum)
14042:
14043: Accepts either a combined $courseid (in the form of domain_courseid) or the
14044: two component version $cdom, $cnum. It checks if the specified course exists.
14045:
14046: Returns:
14047: undef if the course doesn't exist, otherwise
14048: in scalar context the combined courseid.
14049: in list context the two components of the course identifier, domain and
14050: courseid.
14051:
1.243 albertel 14052: =back
14053:
14054: =head2 Resource Subroutines
14055:
14056: =over 4
1.191 harris41 14057:
14058: =item *
14059:
1.243 albertel 14060: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14061:
14062: =item *
14063:
1.243 albertel 14064: repcopy($filename) : subscribes to the requested file, and attempts to
14065: replicate from the owning library server, Might return
1.607 raeburn 14066: 'unavailable', 'not_found', 'forbidden', 'ok', or
14067: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14068: resource. Expects the local filesystem pathname
14069: (/home/httpd/html/res/....)
14070:
14071: =back
14072:
14073: =head2 Resource Information
14074:
14075: =over 4
1.191 harris41 14076:
14077: =item *
14078:
1.1172.2.28 raeburn 14079: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14080: and returns the value of a variety of different possible values,
14081: $varname should be a request string, and the other parameters can be
14082: used to specify who and what one is asking about. Ordinarily, $cid
14083: does not need to be specified, as it is retrived from
14084: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14085: within lonuserstate::loadmap() when initializing a course, before
14086: $env{'request.course.id'} has been set, so it needs to be provided
14087: in that one case.
1.243 albertel 14088:
14089: Possible values for $varname are environment.lastname (or other item
14090: from the envirnment hash), user.name (or someother aspect about the
14091: user), resource.0.maxtries (or some other part and parameter of a
14092: resource)
1.204 albertel 14093:
14094: =item *
14095:
1.243 albertel 14096: directcondval($number) : get current value of a condition; reads from a state
14097: string
1.204 albertel 14098:
14099: =item *
14100:
1.243 albertel 14101: condval($condidx) : value of condition index based on state
1.204 albertel 14102:
14103: =item *
14104:
1.243 albertel 14105: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14106: resource's metadata, $what should be either a specific key, or either
14107: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14108: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14109:
14110: this function automatically caches all requests
1.191 harris41 14111:
14112: =item *
14113:
1.243 albertel 14114: metadata_query($query,$custom,$customshow) : make a metadata query against the
14115: network of library servers; returns file handle of where SQL and regex results
14116: will be stored for query
1.191 harris41 14117:
14118: =item *
14119:
1.1172.2.66 raeburn 14120: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14121: return symbolic list entry (all arguments optional).
14122:
14123: Args: filename is the filename (including path) for the file for which a symb
14124: is required; donotrecurse, if true will prevent calls to allowed() being made
14125: to check access status if more than one resource was found in the bighash
14126: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14127: a randompick); ignorecachednull, if true will prevent a symb of '' being
14128: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14129: cause possible symbs to be checked to determine if they are subject to content
14130: blocking, if so they will not be included as possible symbs; possibles is a
14131: ref to a hash, which, as a side effect, will be populated with all possible
14132: symbs (content blocking not tested).
14133:
1.243 albertel 14134: returns the data handle
1.191 harris41 14135:
14136: =item *
14137:
1.1172.2.17 raeburn 14138: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14139: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14140: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14141: on failure, user must be in a course, as it assumes the existence of
14142: the course initial hash, and uses $env('request.course.id'}. The third
14143: arg is an optional reference to a scalar. If this arg is passed in the
14144: call to symbverify, it will be set to 1 if the symb has been set to be
14145: encrypted; otherwise it will be null.
1.243 albertel 14146:
1.191 harris41 14147: =item *
14148:
1.243 albertel 14149: symbclean($symb) : removes versions numbers from a symb, returns the
14150: cleaned symb
1.191 harris41 14151:
14152: =item *
14153:
1.243 albertel 14154: is_on_map($uri) : checks if the $uri is somewhere on the current
14155: course map, user must be in a course for it to work.
1.191 harris41 14156:
14157: =item *
14158:
1.243 albertel 14159: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14160:
14161: =item *
14162:
1.243 albertel 14163: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14164: a random seed, all arguments are optional, if they aren't sent it uses the
14165: environment to derive them. Note: if symb isn't sent and it can't get one
14166: from &symbread it will use the current time as its return value
1.191 harris41 14167:
14168: =item *
14169:
1.243 albertel 14170: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14171: unfakeable, receipt
1.191 harris41 14172:
14173: =item *
14174:
1.620 albertel 14175: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14176:
14177: =item *
14178:
1.243 albertel 14179: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14180:
14181: =item *
14182:
1.243 albertel 14183: 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 14184:
14185: =item *
14186:
1.243 albertel 14187: 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 14188:
14189: =item *
14190:
1.243 albertel 14191: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14192:
14193: =item *
14194:
1.243 albertel 14195: devalidate($symb) : devalidate temporary spreadsheet calculations,
14196: forcing spreadsheet to reevaluate the resource scores next time.
14197:
1.1172.2.13 raeburn 14198: =item *
14199:
14200: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14201: when viewing in course context.
14202:
14203: input: six args -- filename (decluttered), course number, course domain,
14204: url, symb (if registered) and group (if this is a
14205: group item -- e.g., bulletin board, group page etc.).
14206:
14207: output: array of five scalars --
14208: $cfile -- url for file editing if editable on current server
14209: $home -- homeserver of resource (i.e., for author if published,
14210: or course if uploaded.).
14211: $switchserver -- 1 if server switch will be needed.
14212: $forceedit -- 1 if icon/link should be to go to edit mode
14213: $forceview -- 1 if icon/link should be to go to view mode
14214:
14215: =item *
14216:
14217: is_course_upload($file,$cnum,$cdom)
14218:
14219: Used in course context to determine if current file was uploaded to
14220: the course (i.e., would be found in /userfiles/docs on the course's
14221: homeserver.
14222:
14223: input: 3 args -- filename (decluttered), course number and course domain.
14224: output: boolean -- 1 if file was uploaded.
14225:
1.243 albertel 14226: =back
14227:
14228: =head2 Storing/Retreiving Data
14229:
14230: =over 4
1.191 harris41 14231:
14232: =item *
14233:
1.1172.2.64 raeburn 14234: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14235: permanently for this url; hashref needs to be given and should be a \%hashname;
14236: the remaining args aren't required and if they aren't passed or are '' they will
14237: be derived from the env (with the exception of $laststore, which is an
14238: optional arg used when a user's submission is stored in grading).
14239: $laststore is $version=$timestamp, where $version is the most recent version
14240: number retrieved for the corresponding $symb in the $namespace db file, and
14241: $timestamp is the timestamp for that transaction (UNIX time).
14242: $laststore is currently only passed when cstore() is called by
14243: structuretags::finalize_storage().
1.191 harris41 14244:
14245: =item *
14246:
1.1172.2.64 raeburn 14247: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14248: but uses critical subroutine
1.191 harris41 14249:
14250: =item *
14251:
1.243 albertel 14252: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14253: all args are optional
1.191 harris41 14254:
14255: =item *
14256:
1.717 albertel 14257: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14258: dumps the complete (or key matching regexp) namespace into a hash
14259: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14260: normally &store()ed into
14261:
14262: $range should be either an integer '100' (give me the first 100
14263: matching records)
14264: or be two integers sperated by a - with no spaces
14265: '30-50' (give me the 30th through the 50th matching
14266: records)
14267:
14268:
14269: =item *
14270:
1.1172.2.59 raeburn 14271: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14272: replaces a &store() version of data with a replacement set of data
14273: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14274: reference. If $tolog is true, the transaction is logged in the courselog
14275: with an action=PUTSTORE.
1.717 albertel 14276:
14277: =item *
14278:
1.243 albertel 14279: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14280: works very similar to store/cstore, but all data is stored in a
14281: temporary location and can be reset using tmpreset, $storehash should
14282: be a hash reference, returns nothing on success
1.191 harris41 14283:
14284: =item *
14285:
1.243 albertel 14286: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14287: similar to restore, but all data is stored in a temporary location and
14288: can be reset using tmpreset. Returns a hash of values on success,
14289: error string otherwise.
1.191 harris41 14290:
14291: =item *
14292:
1.243 albertel 14293: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14294: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14295:
14296: =item *
14297:
1.243 albertel 14298: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14299: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14300:
14301: =item *
14302:
1.243 albertel 14303: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14304: namesp ($udom and $uname are optional)
1.191 harris41 14305:
14306: =item *
14307:
1.702 albertel 14308: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14309: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14310: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14311:
1.702 albertel 14312: $range should be either an integer '100' (give me the first 100
14313: matching records)
14314: or be two integers sperated by a - with no spaces
14315: '30-50' (give me the 30th through the 50th matching
14316: records)
1.449 matthew 14317: =item *
14318:
14319: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14320: $store can be a scalar, an array reference, or if the amount to be
14321: incremented is > 1, a hash reference.
14322:
14323: ($udom and $uname are optional)
1.191 harris41 14324:
14325: =item *
14326:
1.243 albertel 14327: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14328: ($udom and $uname are optional)
1.191 harris41 14329:
14330: =item *
14331:
1.243 albertel 14332: cput($namespace,$storehash,$udom,$uname) : critical put
14333: ($udom and $uname are optional)
1.191 harris41 14334:
14335: =item *
14336:
1.748 albertel 14337: newput($namespace,$storehash,$udom,$uname) :
14338:
14339: Attempts to store the items in the $storehash, but only if they don't
14340: currently exist, if this succeeds you can be certain that you have
14341: successfully created a new key value pair in the $namespace db.
14342:
14343:
14344: Args:
14345: $namespace: name of database to store values to
14346: $storehash: hashref to store to the db
14347: $udom: (optional) domain of user containing the db
14348: $uname: (optional) name of user caontaining the db
14349:
14350: Returns:
14351: 'ok' -> succeeded in storing all keys of $storehash
14352: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14353: least <key> already existed in the db (other
14354: requested keys may also already exist)
1.967 bisitz 14355: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14356: 'con_lost' -> unable to contact request server
14357: 'refused' -> action was not allowed by remote machine
14358:
14359:
14360: =item *
14361:
1.243 albertel 14362: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14363: reference filled in from namesp (encrypts the return communication)
14364: ($udom and $uname are optional)
1.191 harris41 14365:
14366: =item *
14367:
1.243 albertel 14368: log($udom,$name,$home,$message) : write to permanent log for user; use
14369: critical subroutine
14370:
1.806 raeburn 14371: =item *
14372:
1.860 raeburn 14373: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14374: array reference filled in from namespace found in domain level on either
14375: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14376:
14377: =item *
14378:
1.860 raeburn 14379: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14380: domain level either on specified domain server ($uhome) or primary domain
14381: server ($udom and $uhome are optional)
1.806 raeburn 14382:
1.943 raeburn 14383: =item *
14384:
1.1172.2.35 raeburn 14385: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14386: for: authentication, language, quotas, timezone, date locale, and portal URL in
14387: the target domain.
14388:
14389: May also include additional key => value pairs for the following groups:
14390:
14391: =over
14392:
14393: =item
14394: disk quotas (MB allocated by default to portfolios and authoring spaces).
14395:
14396: =over
14397:
14398: =item defaultquota, authorquota
14399:
14400: =back
14401:
14402: =item
14403: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14404: portfolio for users).
14405:
14406: =over
14407:
14408: =item
14409: aboutme, blog, webdav, portfolio
14410:
14411: =back
14412:
14413: =item
14414: requestcourses: ability to request courses, and how requests are processed.
14415:
14416: =over
14417:
14418: =item
1.1172.2.37 raeburn 14419: official, unofficial, community, textbook
1.1172.2.35 raeburn 14420:
14421: =back
14422:
14423: =item
14424: inststatus: types of institutional affiliation, and order in which they are displayed.
14425:
14426: =over
14427:
14428: =item
1.1172.2.44 raeburn 14429: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14430:
14431: =back
14432:
14433: =item
14434: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14435: for course's uploaded content.
14436:
14437: =over
14438:
14439: =item
1.1172.2.68 raeburn 14440: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14441: communityquota, textbookquota
1.1172.2.35 raeburn 14442:
14443: =back
14444:
14445: =item
14446: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14447: on your servers.
14448:
14449: =over
14450:
14451: =item
14452: remotesessions, hostedsessions
14453:
14454: =back
14455:
14456: =back
14457:
14458: In cases where a domain coordinator has never used the "Set Domain Configuration"
14459: utility to create a configuration.db file on a domain's primary library server
14460: only the following domain defaults: auth_def, auth_arg_def, lang_def
14461: -- corresponding values are authentication type (internal, krb4, krb5,
14462: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14463: will be available. Values are retrieved from cache (if current), unless the
14464: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14465: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14466:
14467: Typical usage:
1.943 raeburn 14468:
1.1172.2.35 raeburn 14469: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14470:
1.243 albertel 14471: =back
14472:
14473: =head2 Network Status Functions
14474:
14475: =over 4
1.191 harris41 14476:
14477: =item *
14478:
1.1137 raeburn 14479: dirlist() : return directory list based on URI (first arg).
14480:
14481: Inputs: 1 required, 5 optional.
14482:
14483: =over
14484:
14485: =item
14486: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14487:
14488: =item
14489: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14490:
14491: =item
14492: $username - username of user/course to be listed. Extracted from $uri if absent.
14493:
14494: =item
14495: $getpropath - boolean: 1 if prepend path using &propath().
14496:
14497: =item
14498: $getuserdir - boolean: 1 if prepend path for "userfiles".
14499:
14500: =item
14501: $alternateRoot - path to prepend in place of path from $uri.
14502:
14503: =back
14504:
14505: Returns: Array of up to two items.
14506:
14507: =over
14508:
14509: a reference to an array of files/subdirectories
14510:
14511: =over
14512:
14513: Each element in the array of files/subdirectories is a & separated list of
14514: item name and the result of running stat on the item. If dirlist was requested
14515: for a file instead of a directory, the item name will be ''. For a directory
14516: listing, if the item is a metadata file, the element will end &N&M
14517: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14518: default copyright set (1).
14519:
14520: =back
14521:
14522: a scalar containing error condition (if encountered).
14523:
14524: =over
14525:
14526: =item
14527: no_host (no homeserver identified for $username:$domain).
14528:
14529: =item
14530: no_such_host (server contacted for listing not identified as valid host).
14531:
14532: =item
14533: con_lost (connection to remote server failed).
14534:
14535: =item
14536: refused (invalid $username:$domain received on lond side).
14537:
14538: =item
14539: no_such_dir (directory at specified path on lond side does not exist).
14540:
14541: =item
14542: empty (directory at specified path on lond side is empty).
14543:
14544: =over
14545:
14546: This is currently not encountered because the &ls3, &ls2,
14547: &ls (_handler) routines on the lond side do not filter out
14548: . and .. from a directory listing.
14549:
14550: =back
14551:
14552: =back
14553:
14554: =back
1.191 harris41 14555:
14556: =item *
14557:
1.243 albertel 14558: spareserver() : find server with least workload from spare.tab
14559:
1.986 foxr 14560:
14561: =item *
14562:
14563: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14564: if there is no corresponding loncapa host.
14565:
1.243 albertel 14566: =back
14567:
1.986 foxr 14568:
1.243 albertel 14569: =head2 Apache Request
14570:
14571: =over 4
1.191 harris41 14572:
14573: =item *
14574:
1.243 albertel 14575: ssi($url,%hash) : server side include, does a complete request cycle on url to
14576: localhost, posts hash
14577:
14578: =back
14579:
14580: =head2 Data to String to Data
14581:
14582: =over 4
1.191 harris41 14583:
14584: =item *
14585:
1.243 albertel 14586: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14587: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14588:
14589: =item *
14590:
1.243 albertel 14591: hashref2str($hashref) : convert a hashref into a string complete with
14592: escaping and '=' and '&' separators, supports elements that are
14593: arrayrefs and hashrefs
1.191 harris41 14594:
14595: =item *
14596:
1.243 albertel 14597: arrayref2str($arrayref) : convert an arrayref into a string complete
14598: with escaping and '&' separators, supports elements that are arrayrefs
14599: and hashrefs
1.191 harris41 14600:
14601: =item *
14602:
1.243 albertel 14603: str2hash($string) : convert string to hash using unescaping and
14604: splitting on '=' and '&', supports elements that are arrayrefs and
14605: hashrefs
1.191 harris41 14606:
14607: =item *
14608:
1.243 albertel 14609: str2array($string) : convert string to hash using unescaping and
14610: splitting on '&', supports elements that are arrayrefs and hashrefs
14611:
14612: =back
14613:
14614: =head2 Logging Routines
14615:
14616:
14617: These routines allow one to make log messages in the lonnet.log and
14618: lonnet.perm logfiles.
1.191 harris41 14619:
1.1119 foxr 14620: =over 4
14621:
1.191 harris41 14622: =item *
14623:
1.243 albertel 14624: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14625:
14626: =item *
14627:
1.243 albertel 14628: logthis() : append message to the normal lonnet.log file, it gets
14629: preiodically rolled over and deleted.
1.191 harris41 14630:
14631: =item *
14632:
1.243 albertel 14633: logperm() : append a permanent message to lonnet.perm.log, this log
14634: file never gets deleted by any automated portion of the system, only
14635: messages of critical importance should go in here.
14636:
1.1119 foxr 14637:
1.243 albertel 14638: =back
14639:
14640: =head2 General File Helper Routines
14641:
14642: =over 4
1.191 harris41 14643:
14644: =item *
14645:
1.481 raeburn 14646: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14647: (a) files in /uploaded
14648: (i) If a local copy of the file exists -
14649: compares modification date of local copy with last-modified date for
14650: definitive version stored on home server for course. If local copy is
14651: stale, requests a new version from the home server and stores it.
14652: If the original has been removed from the home server, then local copy
14653: is unlinked.
14654: (ii) If local copy does not exist -
14655: requests the file from the home server and stores it.
14656:
14657: If $caller is 'uploadrep':
14658: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14659: for request for files originally uploaded via DOCS.
14660: - returns 'ok' if fresh local copy now available, -1 otherwise.
14661:
14662: Otherwise:
14663: This indicates a call from the content generation phase of the request.
14664: - returns the entire contents of the file or -1.
14665:
14666: (b) files in /res
14667: - returns the entire contents of a file or -1;
14668: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14669:
1.712 albertel 14670:
14671: =item *
14672:
14673: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14674: reference
14675:
14676: returns either a stat() list of data about the file or an empty list
14677: if the file doesn't exist or couldn't find out about it (connection
14678: problems or user unknown)
14679:
1.191 harris41 14680: =item *
14681:
1.243 albertel 14682: filelocation($dir,$file) : returns file system location of a file
14683: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14684: directory that relative $file lookups are to looked in ($dir of /a/dir
14685: and a file of ../bob will become /a/bob)
1.191 harris41 14686:
14687: =item *
14688:
14689: hreflocation($dir,$file) : returns file system location or a URL; same as
14690: filelocation except for hrefs
14691:
14692: =item *
14693:
1.1172.2.49 raeburn 14694: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14695: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14696:
1.243 albertel 14697: =back
14698:
1.608 albertel 14699: =head2 Usererfile file routines (/uploaded*)
14700:
14701: =over 4
14702:
14703: =item *
14704:
14705: userfileupload(): main rotine for putting a file in a user or course's
14706: filespace, arguments are,
14707:
1.620 albertel 14708: formname - required - this is the name of the element in $env where the
1.608 albertel 14709: filename, and the contents of the file to create/modifed exist
1.620 albertel 14710: the filename is in $env{'form.'.$formname.'.filename'} and the
14711: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14712: context - if coursedoc, store the file in the course of the active role
14713: of the current user;
14714: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14715: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14716: subdir - required - subdirectory to put the file in under ../userfiles/
14717: if undefined, it will be placed in "unknown"
14718:
14719: (This routine calls clean_filename() to remove any dangerous
14720: characters from the filename, and then calls finuserfileupload() to
14721: complete the transaction)
14722:
14723: returns either the url of the uploaded file (/uploaded/....) if successful
14724: and /adm/notfound.html if unsuccessful
14725:
14726: =item *
14727:
14728: clean_filename(): routine for cleaing a filename up for storage in
14729: userfile space, argument is:
14730:
14731: filename - proposed filename
14732:
14733: returns: the new clean filename
14734:
14735: =item *
14736:
1.1090 raeburn 14737: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14738: userspace, probably shouldn't be called directly
14739:
14740: docuname: username or courseid of destination for the file
14741: docudom: domain of user/course of destination for the file
14742: formname: same as for userfileupload()
1.1090 raeburn 14743: fname: filename (including subdirectories) for the file
14744: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14745: allfiles: reference to hash used to store objects found by parser
14746: codebase: reference to hash used for codebases of java objects found by parser
14747: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14748: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14749: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14750: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14751: context: if 'overwrite', will move the uploaded file from its temporary location to
14752: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14753: mimetype: reference to scalar to accommodate mime type determined
14754: from File::MMagic if $parser = parse.
1.608 albertel 14755:
14756: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14757: and /adm/notfound.html if unsuccessful (or an error message if context
14758: was 'overwrite').
14759:
1.608 albertel 14760:
14761: =item *
14762:
14763: renameuserfile(): renames an existing userfile to a new name
14764:
14765: Args:
14766: docuname: username or courseid of destination for the file
14767: docudom: domain of user/course of destination for the file
14768: old: current file name (including any subdirs under userfiles)
14769: new: desired file name (including any subdirs under userfiles)
14770:
14771: =item *
14772:
14773: mkdiruserfile(): creates a directory is a userfiles dir
14774:
14775: Args:
14776: docuname: username or courseid of destination for the file
14777: docudom: domain of user/course of destination for the file
14778: dir: dir to create (including any subdirs under userfiles)
14779:
14780: =item *
14781:
14782: removeuserfile(): removes a file that exists in userfiles
14783:
14784: Args:
14785: docuname: username or courseid of destination for the file
14786: docudom: domain of user/course of destination for the file
14787: fname: filname to delete (including any subdirs under userfiles)
14788:
14789: =item *
14790:
14791: removeuploadedurl(): convience function for removeuserfile()
14792:
14793: Args:
14794: url: a full /uploaded/... url to delete
14795:
1.747 albertel 14796: =item *
14797:
14798: get_portfile_permissions():
14799: Args:
14800: domain: domain of user or course contain the portfolio files
14801: user: name of user or num of course contain the portfolio files
14802: Returns:
14803: hashref of a dump of the proper file_permissions.db
14804:
14805:
14806: =item *
14807:
14808: get_access_controls():
14809:
14810: Args:
14811: current_permissions: the hash ref returned from get_portfile_permissions()
14812: group: (optional) the group you want the files associated with
14813: file: (optional) the file you want access info on
14814:
14815: Returns:
1.749 raeburn 14816: a hash (keys are file names) of hashes containing
14817: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14818: values are XML containing access control settings (see below)
1.747 albertel 14819:
14820: Internal notes:
14821:
1.749 raeburn 14822: access controls are stored in file_permissions.db as key=value pairs.
14823: key -> path to file/file_name\0uniqueID:scope_end_start
14824: where scope -> public,guest,course,group,domains or users.
14825: end -> UNIX time for end of access (0 -> no end date)
14826: start -> UNIX time for start of access
14827:
14828: value -> XML description of access control
14829: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14830: <start></start>
14831: <end></end>
14832:
14833: <password></password> for scope type = guest
14834:
14835: <domain></domain> for scope type = course or group
14836: <number></number>
14837: <roles id="">
14838: <role></role>
14839: <access></access>
14840: <section></section>
14841: <group></group>
14842: </roles>
14843:
14844: <dom></dom> for scope type = domains
14845:
14846: <users> for scope type = users
14847: <user>
14848: <uname></uname>
14849: <udom></udom>
14850: </user>
14851: </users>
14852: </scope>
14853:
14854: Access data is also aggregated for each file in an additional key=value pair:
14855: key -> path to file/file_name\0accesscontrol
14856: value -> reference to hash
14857: hash contains key = value pairs
14858: where key = uniqueID:scope_end_start
14859: value = UNIX time record was last updated
14860:
14861: Used to improve speed of look-ups of access controls for each file.
14862:
14863: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14864:
1.1172.2.13 raeburn 14865: =item *
14866:
1.749 raeburn 14867: modify_access_controls():
14868:
14869: Modifies access controls for a portfolio file
14870: Args
14871: 1. file name
14872: 2. reference to hash of required changes,
14873: 3. domain
14874: 4. username
14875: where domain,username are the domain of the portfolio owner
14876: (either a user or a course)
14877:
14878: Returns:
14879: 1. result of additions or updates ('ok' or 'error', with error message).
14880: 2. result of deletions ('ok' or 'error', with error message).
14881: 3. reference to hash of any new or updated access controls.
14882: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14883: key = integer (inbound ID)
1.1172.2.13 raeburn 14884: value = uniqueID
14885:
14886: =item *
14887:
14888: get_timebased_id():
14889:
14890: Attempts to get a unique timestamp-based suffix for use with items added to a
14891: course via the Course Editor (e.g., folders, composite pages,
14892: group bulletin boards).
14893:
14894: Args: (first three required; six others optional)
14895:
14896: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14897: docssequence, or name of group
14898:
14899: 2. keyid (alphanumeric): name of temporary locking key in hash,
14900: e.g., num, boardids
14901:
14902: 3. namespace: name of gdbm file used to store suffixes already assigned;
14903: file will be named nohist_namespace.db
14904:
14905: 4. cdom: domain of course; default is current course domain from %env
14906:
14907: 5. cnum: course number; default is current course number from %env
14908:
14909: 6. idtype: set to concat if an additional digit is to be appended to the
14910: unix timestamp to form the suffix, if the plain timestamp is already
14911: in use. Default is to not do this, but simply increment the unix
14912: timestamp by 1 until a unique key is obtained.
14913:
14914: 7. who: holder of locking key; defaults to user:domain for user.
14915:
14916: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14917: retrying); default is 3.
14918:
14919: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14920:
14921: Returns:
14922:
14923: 1. suffix obtained (numeric)
14924:
14925: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14926:
14927: 3. error: contains (localized) error message if an error occurred.
14928:
1.747 albertel 14929:
1.608 albertel 14930: =back
14931:
1.243 albertel 14932: =head2 HTTP Helper Routines
14933:
14934: =over 4
14935:
1.191 harris41 14936: =item *
14937:
14938: escape() : unpack non-word characters into CGI-compatible hex codes
14939:
14940: =item *
14941:
14942: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14943:
1.243 albertel 14944: =back
14945:
14946: =head1 PRIVATE SUBROUTINES
14947:
14948: =head2 Underlying communication routines (Shouldn't call)
14949:
14950: =over 4
14951:
14952: =item *
14953:
14954: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14955:
14956: =item *
14957:
14958: reply() : uses subreply to send a message to remote machine, logs all failures
14959:
14960: =item *
14961:
14962: critical() : passes a critical message to another server; if cannot
14963: get through then place message in connection buffer directory and
14964: returns con_delayed, if incapable of saving message, returns
14965: con_failed
14966:
14967: =item *
14968:
14969: reconlonc() : tries to reconnect lonc client processes.
14970:
14971: =back
14972:
14973: =head2 Resource Access Logging
14974:
14975: =over 4
14976:
14977: =item *
14978:
14979: flushcourselogs() : flush (save) buffer logs and access logs
14980:
14981: =item *
14982:
14983: courselog($what) : save message for course in hash
14984:
14985: =item *
14986:
14987: courseacclog($what) : save message for course using &courselog(). Perform
14988: special processing for specific resource types (problems, exams, quizzes, etc).
14989:
1.191 harris41 14990: =item *
14991:
14992: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14993: as a PerlChildExitHandler
1.243 albertel 14994:
14995: =back
14996:
14997: =head2 Other
14998:
14999: =over 4
15000:
15001: =item *
15002:
15003: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15004:
15005: =back
15006:
15007: =cut
1.877 foxr 15008:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>