Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.147.2.1
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.147. .1(raebu 4:22): # $Id: lonnet.pm,v 1.1172.2.147 2022/02/27 02:19:13 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;
1.1172.2.107 raeburn 77: use CGI::Cookie;
1.977 amueller 78:
1.1172.2.104 raeburn 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114 raeburn 81: %managerstab $passwdmin);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.1024 raeburn 97: use File::MMagic;
1.1172.2.142 raeburn 98: use Net::CIDR;
99: use Sys::Hostname::FQDN();
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 103: use LONCAPA::Lond;
1.1172.2.110 raeburn 104: use LONCAPA::transliterate;
1.1117 foxr 105:
1.1090 raeburn 106: use File::Copy;
1.676 albertel 107:
1.195 www 108: my $readit;
1.1172.2.79 raeburn 109: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 110:
1.619 albertel 111: require Exporter;
112:
113: our @ISA = qw (Exporter);
114: our @EXPORT = qw(%env);
115:
1.1172.2.9 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1172.2.9 raeburn 119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1172.2.13 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.134 raeburn 130: my $ip = &get_requestor_ip();
1.1172.2.9 raeburn 131: my $logentry = {
132: $id => {
133: 'exe_uname' => $env{'user.name'},
134: 'exe_udom' => $env{'user.domain'},
135: 'exe_time' => $now,
1.1172.2.134 raeburn 136: 'exe_ip' => $ip,
1.1172.2.9 raeburn 137: 'delflag' => $delflag,
138: 'logentry' => $storehash,
139: 'uname' => $uname,
140: 'udom' => $udom,
141: }
142: };
143: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 144: }
145: }
1.1 albertel 146:
1.163 harris41 147: sub logtouch {
148: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 149: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 150: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 151: close $fh;
152: }
153: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
154: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
155: }
156:
1.1 albertel 157: sub logthis {
158: my $message=shift;
159: my $execdir=$perlvar{'lonDaemons'};
160: my $now=time;
161: my $local=localtime($now);
1.1172.2.96 raeburn 162: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 163: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
164: print $fh $logstring;
1.448 albertel 165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
170: sub logperm {
171: my $message=shift;
172: my $execdir=$perlvar{'lonDaemons'};
173: my $now=time;
174: my $local=localtime($now);
1.1172.2.96 raeburn 175: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 176: print $fh "$now:$message:$local\n";
177: close($fh);
178: }
1.1 albertel 179: return 1;
180: }
181:
1.850 albertel 182: sub create_connection {
1.853 albertel 183: my ($hostname,$lonid) = @_;
1.851 albertel 184: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 185: Type => SOCK_STREAM,
186: Timeout => 10);
187: return 0 if (!$client);
1.890 albertel 188: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 189: my $result = <$client>;
190: chomp($result);
191: return 1 if ($result eq 'done');
192: return 0;
193: }
194:
1.983 raeburn 195: sub get_server_timezone {
196: my ($cnum,$cdom) = @_;
197: my $home=&homeserver($cnum,$cdom);
198: if ($home ne 'no_host') {
199: my $cachetime = 24*3600;
200: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
201: if (defined($cached)) {
202: return $timezone;
203: } else {
204: my $timezone = &reply('servertimezone',$home);
205: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
206: }
207: }
208: }
1.850 albertel 209:
1.1106 raeburn 210: sub get_server_distarch {
211: my ($lonhost,$ignore_cache) = @_;
212: if (defined($lonhost)) {
213: if (!defined(&hostname($lonhost))) {
214: return;
215: }
216: my $cachetime = 12*3600;
217: if (!$ignore_cache) {
218: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
219: if (defined($cached)) {
220: return $distarch;
221: }
222: }
223: my $rep = &reply('serverdistarch',$lonhost);
224: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
225: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
226: $rep eq '') {
227: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
228: }
229: }
230: return;
231: }
232:
1.993 raeburn 233: sub get_server_loncaparev {
1.1073 raeburn 234: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 235: if (defined($lonhost)) {
236: if (!defined(&hostname($lonhost))) {
237: undef($lonhost);
238: }
239: }
240: if (!defined($lonhost)) {
241: if (defined(&domain($dom,'primary'))) {
242: $lonhost=&domain($dom,'primary');
243: if ($lonhost eq 'no_host') {
244: undef($lonhost);
245: }
246: }
247: }
248: if (defined($lonhost)) {
1.1073 raeburn 249: my $cachetime = 12*3600;
250: if (!$ignore_cache) {
251: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
252: if (defined($cached)) {
253: return $loncaparev;
254: }
255: }
256: my ($answer,$loncaparev);
257: my @ids=¤t_machine_ids();
258: if (grep(/^\Q$lonhost\E$/,@ids)) {
259: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 260: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 261: $loncaparev = $1;
262: }
263: } else {
264: $answer = &reply('serverloncaparev',$lonhost);
265: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
266: if ($caller eq 'loncron') {
267: my $ua=new LWP::UserAgent;
1.1082 raeburn 268: $ua->timeout(4);
1.1172.2.120 raeburn 269: my $hostname = &hostname($lonhost);
1.1073 raeburn 270: my $protocol = $protocol{$lonhost};
271: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 272: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 273: my $request=new HTTP::Request('GET',$url);
274: my $response=$ua->request($request);
275: unless ($response->is_error()) {
276: my $content = $response->content;
1.1081 raeburn 277: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 278: $loncaparev = $1;
279: }
280: }
281: } else {
282: $loncaparev = $loncaparevs{$lonhost};
283: }
1.1081 raeburn 284: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 285: $loncaparev = $1;
286: }
1.993 raeburn 287: }
1.1073 raeburn 288: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 289: }
290: }
291:
1.1074 raeburn 292: sub get_server_homeID {
293: my ($hostname,$ignore_cache,$caller) = @_;
294: unless ($ignore_cache) {
295: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
296: if (defined($cached)) {
297: return $serverhomeID;
298: }
299: }
300: my $cachetime = 12*3600;
301: my $serverhomeID;
302: if ($caller eq 'loncron') {
303: my @machine_ids = &machine_ids($hostname);
304: foreach my $id (@machine_ids) {
305: my $response = &reply('serverhomeID',$id);
306: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
307: $serverhomeID = $response;
308: last;
309: }
310: }
311: if ($serverhomeID eq '') {
312: $serverhomeID = $machine_ids[-1];
313: }
314: } else {
315: $serverhomeID = $serverhomeIDs{$hostname};
316: }
317: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
318: }
319:
1.1121 raeburn 320: sub get_remote_globals {
321: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 322: my ($result,%returnhash,%whatneeded);
323: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 324: foreach my $what (sort(keys(%{$whathash}))) {
325: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 326: my ($response,$cached);
1.1121 raeburn 327: unless ($ignore_cache) {
1.1125 raeburn 328: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 329: }
330: if (defined($cached)) {
1.1125 raeburn 331: $returnhash{$what} = $response;
1.1121 raeburn 332: } else {
1.1125 raeburn 333: $whatneeded{$what} = 1;
1.1121 raeburn 334: }
335: }
1.1125 raeburn 336: if (keys(%whatneeded) == 0) {
337: $result = 'ok';
338: } else {
1.1121 raeburn 339: my $requested = &freeze_escape(\%whatneeded);
340: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 341: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
342: ($rep eq 'unknown_cmd')) {
343: $result = $rep;
344: } else {
345: $result = 'ok';
1.1121 raeburn 346: my @pairs=split(/\&/,$rep);
1.1125 raeburn 347: foreach my $item (@pairs) {
348: my ($key,$value)=split(/=/,$item,2);
349: my $what = &unescape($key);
350: my $hashid = $lonhost.'-'.$what;
351: $returnhash{$what}=&thaw_unescape($value);
352: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 353: }
354: }
355: }
356: }
1.1125 raeburn 357: return ($result,\%returnhash);
1.1121 raeburn 358: }
359:
1.1124 raeburn 360: sub remote_devalidate_cache {
1.1172.2.35 raeburn 361: my ($lonhost,$cachekeys) = @_;
362: my $items;
363: return unless (ref($cachekeys) eq 'ARRAY');
364: my $cachestr = join('&',@{$cachekeys});
365: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 366: }
367:
1.1 albertel 368: # -------------------------------------------------- Non-critical communication
369: sub subreply {
370: my ($cmd,$server)=@_;
1.838 albertel 371: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 372: #
373: # With loncnew process trimming, there's a timing hole between lonc server
374: # process exit and the master server picking up the listen on the AF_UNIX
375: # socket. In that time interval, a lock file will exist:
376:
377: my $lockfile=$peerfile.".lock";
378: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 379: sleep(0.1);
1.549 foxr 380: }
381: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 382: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 383: #
1.550 foxr 384: # We'll give the connection a few tries before abandoning it. If
385: # connection is not possible, we'll con_lost back to the client.
386: #
387: my $client;
388: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
389: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
390: Type => SOCK_STREAM,
391: Timeout => 10);
1.869 albertel 392: if ($client) {
1.550 foxr 393: last; # Connected!
1.850 albertel 394: } else {
1.853 albertel 395: &create_connection(&hostname($server),$server);
1.550 foxr 396: }
1.1172.2.79 raeburn 397: sleep(0.1); # Try again later if failed connection.
1.550 foxr 398: }
399: my $answer;
400: if ($client) {
1.704 albertel 401: print $client "sethost:$server:$cmd\n";
1.550 foxr 402: $answer=<$client>;
403: if (!$answer) { $answer="con_lost"; }
404: chomp($answer);
405: } else {
406: $answer = 'con_lost'; # Failed connection.
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: sub reply {
412: my ($cmd,$server)=@_;
1.838 albertel 413: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 414: my $answer=subreply($cmd,$server);
1.65 www 415: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 416: my $logged = $cmd;
417: if ($cmd =~ /^encrypt:([^:]+):/) {
418: my $subcmd = $1;
419: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
420: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
421: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
422: (undef,undef,my @rest) = split(/:/,$cmd);
423: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
424: splice(@rest,2,1,'Hidden');
425: } elsif ($subcmd eq 'passwd') {
426: splice(@rest,2,2,('Hidden','Hidden'));
427: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
428: ($subcmd eq 'autoexportgrades')) {
429: splice(@rest,3,1,'Hidden');
430: }
431: $logged = join(':',('encrypt:'.$subcmd,@rest));
432: }
433: }
434: &logthis("<font color=\"blue\">WARNING:".
435: " $logged to $server returned $answer</font>");
1.12 www 436: }
1.1 albertel 437: return $answer;
438: }
439:
440: # ----------------------------------------------------------- Send USR1 to lonc
441:
442: sub reconlonc {
1.891 albertel 443: my ($lonid) = @_;
444: if ($lonid) {
1.1172.2.72 raeburn 445: my $hostname = &hostname($lonid);
1.891 albertel 446: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
447: if ($hostname && -e $peerfile) {
448: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
449: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
450: Type => SOCK_STREAM,
451: Timeout => 10);
452: if ($client) {
453: print $client ("reset_retries\n");
454: my $answer=<$client>;
455: #reset just this one.
456: }
457: }
458: return;
459: }
460:
1.836 www 461: &logthis("Trying to reconnect lonc");
1.1 albertel 462: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 463: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 464: my $loncpid=<$fh>;
465: chomp($loncpid);
466: if (kill 0 => $loncpid) {
467: &logthis("lonc at pid $loncpid responding, sending USR1");
468: kill USR1 => $loncpid;
469: sleep 1;
1.836 www 470: } else {
1.12 www 471: &logthis(
1.672 albertel 472: "<font color=\"blue\">WARNING:".
1.12 www 473: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 474: }
475: } else {
1.836 www 476: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 477: }
478: }
479:
480: # ------------------------------------------------------ Critical communication
1.12 www 481:
1.1 albertel 482: sub critical {
483: my ($cmd,$server)=@_;
1.838 albertel 484: unless (&hostname($server)) {
1.672 albertel 485: &logthis("<font color=\"blue\">WARNING:".
1.89 www 486: " Critical message to unknown server ($server)</font>");
487: return 'no_such_host';
488: }
1.1 albertel 489: my $answer=reply($cmd,$server);
490: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 491: &reconlonc($server);
1.589 albertel 492: my $answer=reply($cmd,$server);
1.1 albertel 493: if ($answer eq 'con_lost') {
494: my $now=time;
495: my $middlename=$cmd;
1.5 www 496: $middlename=substr($middlename,0,16);
1.1 albertel 497: $middlename=~s/\W//g;
498: my $dfilename=
1.305 www 499: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
500: $dumpcount++;
1.1 albertel 501: {
1.448 albertel 502: my $dfh;
1.1172.2.96 raeburn 503: if (open($dfh,">",$dfilename)) {
1.448 albertel 504: print $dfh "$cmd\n";
505: close($dfh);
506: }
1.1 albertel 507: }
1.1172.2.79 raeburn 508: sleep 1;
1.1 albertel 509: my $wcmd='';
510: {
1.448 albertel 511: my $dfh;
1.1172.2.96 raeburn 512: if (open($dfh,"<",$dfilename)) {
1.448 albertel 513: $wcmd=<$dfh>;
514: close($dfh);
515: }
1.1 albertel 516: }
517: chomp($wcmd);
1.7 www 518: if ($wcmd eq $cmd) {
1.672 albertel 519: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 520: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 521: &logperm("D:$server:$cmd");
522: return 'con_delayed';
523: } else {
1.672 albertel 524: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 525: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 526: &logperm("F:$server:$cmd");
527: return 'con_failed';
528: }
529: }
530: }
531: return $answer;
1.405 albertel 532: }
533:
1.755 albertel 534: # ------------------------------------------- check if return value is an error
535:
536: sub error {
537: my ($result) = @_;
1.756 albertel 538: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 539: if ($2 == 2) { return undef; }
540: return $1;
541: }
542: return undef;
543: }
544:
1.783 albertel 545: sub convert_and_load_session_env {
546: my ($lonidsdir,$handle)=@_;
547: my @profile;
548: {
1.917 albertel 549: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
550: if (!$opened) {
1.915 albertel 551: return 0;
552: }
1.783 albertel 553: flock($idf,LOCK_SH);
554: @profile=<$idf>;
555: close($idf);
556: }
557: my %temp_env;
558: foreach my $line (@profile) {
1.786 albertel 559: if ($line !~ m/=/) {
560: return 0;
561: }
1.783 albertel 562: chomp($line);
563: my ($envname,$envvalue)=split(/=/,$line,2);
564: $temp_env{&unescape($envname)} = &unescape($envvalue);
565: }
566: unlink("$lonidsdir/$handle.id");
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
568: 0640)) {
569: %disk_env = %temp_env;
570: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
571: untie(%disk_env);
572: }
1.786 albertel 573: return 1;
1.783 albertel 574: }
575:
1.374 www 576: # ------------------------------------------- Transfer profile into environment
1.780 albertel 577: my $env_loaded;
578: sub transfer_profile_to_env {
1.788 albertel 579: my ($lonidsdir,$handle,$force_transfer) = @_;
580: if (!$force_transfer && $env_loaded) { return; }
1.374 www 581:
1.720 albertel 582: if (!defined($lonidsdir)) {
583: $lonidsdir = $perlvar{'lonIDsDir'};
584: }
585: if (!defined($handle)) {
586: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
587: }
588:
1.786 albertel 589: my $convert;
590: {
1.917 albertel 591: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
592: if (!$opened) {
1.915 albertel 593: return;
594: }
1.786 albertel 595: flock($idf,LOCK_SH);
596: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
597: &GDBM_READER(),0640)) {
598: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
599: untie(%disk_env);
600: } else {
601: $convert = 1;
602: }
603: }
604: if ($convert) {
605: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
606: &logthis("Failed to load session, or convert session.");
607: }
1.374 www 608: }
1.783 albertel 609:
1.786 albertel 610: my %remove;
1.783 albertel 611: while ( my $envname = each(%env) ) {
1.433 matthew 612: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
613: if ($time < time-300) {
1.783 albertel 614: $remove{$key}++;
1.433 matthew 615: }
616: }
617: }
1.783 albertel 618:
1.619 albertel 619: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 620: $env_loaded=1;
1.783 albertel 621: foreach my $expired_key (keys(%remove)) {
1.433 matthew 622: &delenv($expired_key);
1.374 www 623: }
1.1 albertel 624: }
625:
1.916 albertel 626: # ---------------------------------------------------- Check for valid session
627: sub check_for_valid_session {
1.1172.2.96 raeburn 628: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 629: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 630: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 631: if ($name eq 'lonDAV') {
632: $lonidsdir=$r->dir_config('lonDAVsessDir');
633: } else {
634: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 635: if ($name eq '') {
636: $name = 'lonID';
637: }
638: }
639: if ($name eq 'lonID') {
640: $secure = 'lonSID';
641: $linkname = 'lonLinkID';
642: $pubname = 'lonPubID';
643: if (exists($cookies{$secure})) {
644: $lonid=$cookies{$secure};
645: } elsif (exists($cookies{$name})) {
646: $lonid=$cookies{$name};
647: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
648: $lonid=$cookies{$linkname};
649: } elsif (exists($cookies{$pubname})) {
650: $lonid=$cookies{$pubname};
651: }
652: } else {
653: $lonid=$cookies{$name};
654: }
655: return undef if (!$lonid);
656:
657: my $handle=&LONCAPA::clean_handle($lonid->value);
658: if (-l "$lonidsdir/$handle.id") {
659: my $link = readlink("$lonidsdir/$handle.id");
660: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
661: $handle = $1;
662: }
1.1155 raeburn 663: }
1.1172.2.96 raeburn 664: if (!-e "$lonidsdir/$handle.id") {
665: if ((ref($domref)) && ($name eq 'lonID') &&
666: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
667: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
668: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
669: $$domref = $possudom;
670: }
671: }
672: return undef;
673: }
1.916 albertel 674:
1.917 albertel 675: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
676: return undef if (!$opened);
1.916 albertel 677:
678: flock($idf,LOCK_SH);
679: my %disk_env;
680: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
681: &GDBM_READER(),0640)) {
682: return undef;
683: }
684:
685: if (!defined($disk_env{'user.name'})
686: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 687: untie(%disk_env);
1.916 albertel 688: return undef;
689: }
1.1172.2.18 raeburn 690:
1.1172.2.36 raeburn 691: if (ref($userhashref) eq 'HASH') {
692: $userhashref->{'name'} = $disk_env{'user.name'};
693: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142 raeburn 694: if ($disk_env{'request.role'}) {
695: $userhashref->{'role'} = $disk_env{'request.role'};
696: }
1.1172.2.18 raeburn 697: }
1.1172.2.107 raeburn 698: untie(%disk_env);
1.1172.2.18 raeburn 699:
1.916 albertel 700: return $handle;
701: }
702:
1.830 albertel 703: sub timed_flock {
704: my ($file,$lock_type) = @_;
705: my $failed=0;
706: eval {
707: local $SIG{__DIE__}='DEFAULT';
708: local $SIG{ALRM}=sub {
709: $failed=1;
710: die("failed lock");
711: };
712: alarm(13);
713: flock($file,$lock_type);
714: alarm(0);
715: };
716: if ($failed) {
717: return undef;
718: } else {
719: return 1;
720: }
721: }
722:
1.1172.2.107 raeburn 723: sub get_sessionfile_vars {
724: my ($handle,$lonidsdir,$storearr) = @_;
725: my %returnhash;
726: unless (ref($storearr) eq 'ARRAY') {
727: return %returnhash;
728: }
729: if (-l "$lonidsdir/$handle.id") {
730: my $link = readlink("$lonidsdir/$handle.id");
731: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
732: $handle = $1;
733: }
734: }
735: if ((-e "$lonidsdir/$handle.id") &&
736: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
737: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
738: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
739: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
740: flock($idf,LOCK_SH);
741: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
742: &GDBM_READER(),0640)) {
743: foreach my $item (@{$storearr}) {
744: $returnhash{$item} = $disk_env{$item};
745: }
746: untie(%disk_env);
747: }
748: }
749: }
750: }
751: return %returnhash;
752: }
753:
1.5 www 754: # ---------------------------------------------------------- Append Environment
755:
756: sub appenv {
1.949 raeburn 757: my ($newenv,$roles) = @_;
758: if (ref($newenv) eq 'HASH') {
759: foreach my $key (keys(%{$newenv})) {
760: my $refused = 0;
761: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
762: $refused = 1;
763: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 764: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 765: if (grep(/^\Q$role\E$/,@{$roles})) {
766: $refused = 0;
767: }
768: }
769: }
770: if ($refused) {
771: &logthis("<font color=\"blue\">WARNING: ".
772: "Attempt to modify environment ".$key." to ".$newenv->{$key}
773: .'</font>');
774: delete($newenv->{$key});
775: } else {
776: $env{$key}=$newenv->{$key};
777: }
778: }
1.1172.2.96 raeburn 779: my $lonids = $perlvar{'lonIDsDir'};
780: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
781: my $opened = open(my $env_file,'+<',$env{'user.environment'});
782: if ($opened
783: && &timed_flock($env_file,LOCK_EX)
784: &&
785: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
786: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
787: while (my ($key,$value) = each(%{$newenv})) {
788: $disk_env{$key} = $value;
789: }
790: untie(%disk_env);
791: }
1.35 www 792: }
1.191 harris41 793: }
1.56 www 794: return 'ok';
795: }
796: # ----------------------------------------------------- Delete from Environment
797:
798: sub delenv {
1.1104 raeburn 799: my ($delthis,$regexp,$roles) = @_;
800: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
801: my $refused = 1;
802: if (ref($roles) eq 'ARRAY') {
803: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
804: if (grep(/^\Q$role\E$/,@{$roles})) {
805: $refused = 0;
806: }
807: }
808: if ($refused) {
809: &logthis("<font color=\"blue\">WARNING: ".
810: "Attempt to delete from environment ".$delthis);
811: return 'error';
812: }
1.56 www 813: }
1.917 albertel 814: my $opened = open(my $env_file,'+<',$env{'user.environment'});
815: if ($opened
1.915 albertel 816: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 817: &&
818: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
819: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 820: foreach my $key (keys(%disk_env)) {
1.987 raeburn 821: if ($regexp) {
822: if ($key=~/^$delthis/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: } else {
827: if ($key=~/^\Q$delthis\E/) {
828: delete($env{$key});
829: delete($disk_env{$key});
830: }
831: }
1.448 albertel 832: }
1.783 albertel 833: untie(%disk_env);
1.5 www 834: }
835: return 'ok';
1.369 albertel 836: }
837:
1.790 albertel 838: sub get_env_multiple {
839: my ($name) = @_;
840: my @values;
841: if (defined($env{$name})) {
842: # exists is it an array
843: if (ref($env{$name})) {
844: @values=@{ $env{$name} };
845: } else {
846: $values[0]=$env{$name};
847: }
848: }
849: return(@values);
850: }
851:
1.958 www 852: # ------------------------------------------------------------------- Locking
853:
854: sub set_lock {
855: my ($text)=@_;
856: $locknum++;
857: my $id=$$.'-'.$locknum;
858: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
859: 'session.lock.'.$id => $text});
860: return $id;
861: }
862:
863: sub get_locks {
864: my $num=0;
865: my %texts=();
866: foreach my $lock (split(/\,/,$env{'session.locks'})) {
867: if ($lock=~/\w/) {
868: $num++;
869: $texts{$lock}=$env{'session.lock.'.$lock};
870: }
871: }
872: return ($num,%texts);
873: }
874:
875: sub remove_lock {
876: my ($id)=@_;
877: my $newlocks='';
878: foreach my $lock (split(/\,/,$env{'session.locks'})) {
879: if (($lock=~/\w/) && ($lock ne $id)) {
880: $newlocks.=','.$lock;
881: }
882: }
883: &appenv({'session.locks' => $newlocks});
884: &delenv('session.lock.'.$id);
885: }
886:
887: sub remove_all_locks {
888: my $activelocks=$env{'session.locks'};
889: foreach my $lock (split(/\,/,$env{'session.locks'})) {
890: if ($lock=~/\w/) {
891: &remove_lock($lock);
892: }
893: }
894: }
895:
896:
1.369 albertel 897: # ------------------------------------------ Find out current server userload
898: sub userload {
899: my $numusers=0;
900: {
901: opendir(LONIDS,$perlvar{'lonIDsDir'});
902: my $filename;
903: my $curtime=time;
904: while ($filename=readdir(LONIDS)) {
1.925 albertel 905: next if ($filename eq '.' || $filename eq '..');
906: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 907: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 908: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 909: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 910: }
911: closedir(LONIDS);
912: }
913: my $userloadpercent=0;
914: my $maxuserload=$perlvar{'lonUserLoadLim'};
915: if ($maxuserload) {
1.371 albertel 916: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 917: }
1.372 albertel 918: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 919: return $userloadpercent;
1.283 www 920: }
921:
1.1 albertel 922: # ------------------------------ Find server with least workload from spare.tab
1.11 www 923:
1.1 albertel 924: sub spareserver {
1.1172.2.142 raeburn 925: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 926: my $spare_server;
1.370 albertel 927: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 928: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
929: : $userloadpercent;
1.1083 raeburn 930: my ($uint_dom,$remotesessions);
931: if (($udom ne '') && (&domain($udom) ne '')) {
932: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
933: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
934: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
935: $remotesessions = $udomdefaults{'remotesessions'};
936: }
1.1123 raeburn 937: my $spareshash = &this_host_spares($udom);
938: if (ref($spareshash) eq 'HASH') {
939: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
940: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 941: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
942: $try_server));
1.1123 raeburn 943: ($spare_server, $lowest_load) =
944: &compare_server_load($try_server, $spare_server, $lowest_load);
945: }
1.1083 raeburn 946: }
1.784 albertel 947:
1.1123 raeburn 948: my $found_server = ($spare_server ne '' && $lowest_load < 100);
949:
950: if (!$found_server) {
951: if (ref($spareshash->{'default'}) eq 'ARRAY') {
952: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 953: next unless (&spare_can_host($udom,$uint_dom,
954: $remotesessions,$try_server));
1.1123 raeburn 955: ($spare_server, $lowest_load) =
956: &compare_server_load($try_server, $spare_server, $lowest_load);
957: }
958: }
959: }
1.784 albertel 960: }
961:
962: if (!$want_server_name) {
1.1001 raeburn 963: if (defined($spare_server)) {
964: my $hostname = &hostname($spare_server);
1.1083 raeburn 965: if (defined($hostname)) {
1.1172.2.120 raeburn 966: my $protocol = 'http';
967: if ($protocol{$spare_server} eq 'https') {
968: $protocol = $protocol{$spare_server};
969: }
1.1172.2.142 raeburn 970: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
971: $hostname = $alias if ($alias ne '');
1.1001 raeburn 972: $spare_server = $protocol.'://'.$hostname;
973: }
974: }
1.784 albertel 975: }
976: return $spare_server;
977: }
978:
979: sub compare_server_load {
1.1172.2.41 raeburn 980: my ($try_server, $spare_server, $lowest_load, $required) = @_;
981:
982: if ($required) {
983: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
984: my $remoterev = &get_server_loncaparev(undef,$try_server);
985: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
986: if (($major eq '' && $minor eq '') ||
987: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
988: return ($spare_server,$lowest_load);
989: }
990: }
1.784 albertel 991:
992: my $loadans = &reply('load', $try_server);
993: my $userloadans = &reply('userload',$try_server);
994:
995: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 996: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 997: }
998:
999: my $load;
1000: if ($loadans =~ /\d/) {
1001: if ($userloadans =~ /\d/) {
1002: #both are numbers, pick the bigger one
1003: $load = ($loadans > $userloadans) ? $loadans
1004: : $userloadans;
1.411 albertel 1005: } else {
1.784 albertel 1006: $load = $loadans;
1.411 albertel 1007: }
1.784 albertel 1008: } else {
1009: $load = $userloadans;
1010: }
1011:
1012: if (($load =~ /\d/) && ($load < $lowest_load)) {
1013: $spare_server = $try_server;
1014: $lowest_load = $load;
1.370 albertel 1015: }
1.784 albertel 1016: return ($spare_server,$lowest_load);
1.202 matthew 1017: }
1.914 albertel 1018:
1019: # --------------------------- ask offload servers if user already has a session
1020: sub find_existing_session {
1021: my ($udom,$uname) = @_;
1.1123 raeburn 1022: my $spareshash = &this_host_spares($udom);
1023: if (ref($spareshash) eq 'HASH') {
1024: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1025: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1026: return $try_server if (&has_user_session($try_server, $udom, $uname));
1027: }
1028: }
1029: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1030: foreach my $try_server (@{ $spareshash->{'default'} }) {
1031: return $try_server if (&has_user_session($try_server, $udom, $uname));
1032: }
1033: }
1.914 albertel 1034: }
1035: return;
1036: }
1037:
1.1172.2.107 raeburn 1038: # check if user's browser sent load balancer cookie and server still has session
1039: # and is not overloaded.
1040: sub check_for_balancer_cookie {
1041: my ($r,$update_mtime) = @_;
1042: my ($otherserver,$cookie);
1043: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1044: if (exists($cookies{'balanceID'})) {
1045: my $balid = $cookies{'balanceID'};
1046: $cookie=&LONCAPA::clean_handle($balid->value);
1047: my $balancedir=$r->dir_config('lonBalanceDir');
1048: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1049: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1050: my ($possudom,$possuname) = ($1,$2);
1051: my $has_session = 0;
1052: if ((&domain($possudom) ne '') &&
1053: (&homeserver($possuname,$possudom) ne 'no_host')) {
1054: my $try_server;
1055: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1056: if ($opened) {
1057: flock($idf,LOCK_SH);
1058: while (my $line = <$idf>) {
1059: chomp($line);
1060: if (&hostname($line) ne '') {
1061: $try_server = $line;
1062: last;
1063: }
1064: }
1065: close($idf);
1066: if (($try_server) &&
1067: (&has_user_session($try_server,$possudom,$possuname))) {
1068: my $lowest_load = 30000;
1069: ($otherserver,$lowest_load) =
1070: &compare_server_load($try_server,undef,$lowest_load);
1071: if ($otherserver ne '' && $lowest_load < 100) {
1072: $has_session = 1;
1073: } else {
1074: undef($otherserver);
1075: }
1076: }
1077: }
1078: }
1079: if ($has_session) {
1080: if ($update_mtime) {
1081: my $atime = my $mtime = time;
1082: utime($atime,$mtime,"$balancedir/$cookie.id");
1083: }
1084: } else {
1085: unlink("$balancedir/$cookie.id");
1086: }
1087: }
1088: }
1089: }
1090: return ($otherserver,$cookie);
1091: }
1092:
1.1172.2.130 raeburn 1093: sub updatebalcookie {
1094: my ($cookie,$balancer,$lastentry)=@_;
1095: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1096: my ($udom,$uname) = ($1,$2);
1097: my $uprimary_id = &domain($udom,'primary');
1098: my $uintdom = &internet_dom($uprimary_id);
1099: my $intdom = &internet_dom($balancer);
1100: my $serverhomedom = &host_domain($balancer);
1101: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1102: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1103: }
1104: }
1105: return;
1106: }
1107:
1.1172.2.107 raeburn 1108: sub delbalcookie {
1109: my ($cookie,$balancer) =@_;
1110: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1111: my ($udom,$uname) = ($1,$2);
1112: my $uprimary_id = &domain($udom,'primary');
1113: my $uintdom = &internet_dom($uprimary_id);
1114: my $intdom = &internet_dom($balancer);
1115: my $serverhomedom = &host_domain($balancer);
1116: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130 raeburn 1117: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1118: }
1119: }
1120: }
1121:
1.914 albertel 1122: # -------------------------------- ask if server already has a session for user
1123: sub has_user_session {
1124: my ($lonid,$udom,$uname) = @_;
1125: my $result = &reply(join(':','userhassession',
1126: map {&escape($_)} ($udom,$uname)),$lonid);
1127: return 1 if ($result eq 'ok');
1128:
1129: return 0;
1130: }
1131:
1.1076 raeburn 1132: # --------- determine least loaded server in a user's domain which allows login
1133:
1134: sub choose_server {
1.1172.2.47 raeburn 1135: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1136: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1137: my %servers = &get_servers($udom);
1.1076 raeburn 1138: my $lowest_load = 30000;
1.1172.2.47 raeburn 1139: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1140: if ($skiploadbal) {
1141: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1142: unless (defined($cached)) {
1143: my $cachetime = 60*60*24;
1144: my %domconfig =
1145: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1146: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1147: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1148: $cachetime);
1149: }
1150: }
1151: }
1.1076 raeburn 1152: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1153: my $loginvia;
1.1172.2.47 raeburn 1154: if ($skiploadbal) {
1155: if (ref($balancers) eq 'HASH') {
1156: next if (exists($balancers->{$lonhost}));
1157: }
1158: }
1.1115 raeburn 1159: if ($checkloginvia) {
1160: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1161: if ($loginvia) {
1162: my ($server,$path) = split(/:/,$loginvia);
1163: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1164: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1165: if ($login_host eq $server) {
1166: $portal_path = $path;
1.1151 raeburn 1167: $isredirect = 1;
1.1116 raeburn 1168: }
1169: } else {
1170: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1171: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1172: if ($login_host eq $lonhost) {
1173: $portal_path = '';
1.1151 raeburn 1174: $isredirect = '';
1.1116 raeburn 1175: }
1176: }
1177: } else {
1.1076 raeburn 1178: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1179: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1180: }
1181: }
1182: if ($login_host ne '') {
1.1116 raeburn 1183: $hostname = &hostname($login_host);
1.1076 raeburn 1184: }
1.1172.2.88 raeburn 1185: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1186: }
1187:
1.1172.2.123 raeburn 1188: sub get_course_sessions {
1189: my ($cnum,$cdom,$lastactivity) = @_;
1190: my %servers = &internet_dom_servers($cdom);
1191: my %returnhash;
1192: foreach my $server (sort(keys(%servers))) {
1193: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1194: my @pairs=split(/\&/,$rep);
1195: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1196: foreach my $item (@pairs) {
1197: my ($key,$value)=split(/=/,$item,2);
1198: $key = &unescape($key);
1199: next if ($key =~ /^error: 2 /);
1200: if (exists($returnhash{$key})) {
1201: next if ($value < $returnhash{$key});
1202: }
1203: $returnhash{$key}=$value;
1204: }
1205: }
1206: }
1207: return %returnhash;
1208: }
1209:
1.202 matthew 1210: # --------------------------------------------- Try to change a user's password
1211:
1212: sub changepass {
1.799 raeburn 1213: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1214: $currentpass = &escape($currentpass);
1215: $newpass = &escape($newpass);
1.1030 raeburn 1216: my $lonhost = $perlvar{'lonHostID'};
1217: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1218: $server);
1219: if (! $answer) {
1220: &logthis("No reply on password change request to $server ".
1221: "by $uname in domain $udom.");
1222: } elsif ($answer =~ "^ok") {
1223: &logthis("$uname in $udom successfully changed their password ".
1224: "on $server.");
1225: } elsif ($answer =~ "^pwchange_failure") {
1226: &logthis("$uname in $udom was unable to change their password ".
1227: "on $server. The action was blocked by either lcpasswd ".
1228: "or pwchange");
1229: } elsif ($answer =~ "^non_authorized") {
1230: &logthis("$uname in $udom did not get their password correct when ".
1231: "attempting to change it on $server.");
1232: } elsif ($answer =~ "^auth_mode_error") {
1233: &logthis("$uname in $udom attempted to change their password despite ".
1234: "not being locally or internally authenticated on $server.");
1235: } elsif ($answer =~ "^unknown_user") {
1236: &logthis("$uname in $udom attempted to change their password ".
1237: "on $server but were unable to because $server is not ".
1238: "their home server.");
1239: } elsif ($answer =~ "^refused") {
1240: &logthis("$server refused to change $uname in $udom password because ".
1241: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1242: } elsif ($answer =~ "invalid_client") {
1243: &logthis("$server refused to change $uname in $udom password because ".
1244: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1245: } elsif ($answer =~ "^prioruse") {
1246: &logthis("$server refused to change $uname in $udom password because ".
1247: "the password had been used before");
1.202 matthew 1248: }
1249: return $answer;
1.1 albertel 1250: }
1251:
1.169 harris41 1252: # ----------------------- Try to determine user's current authentication scheme
1253:
1254: sub queryauthenticate {
1255: my ($uname,$udom)=@_;
1.456 albertel 1256: my $uhome=&homeserver($uname,$udom);
1.1172.2.147 raeburn 1257: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1258: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1259: return 'no_host';
1260: }
1261: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1262: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1263: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1264: }
1.456 albertel 1265: return $answer;
1.169 harris41 1266: }
1267:
1.1 albertel 1268: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1269:
1.1 albertel 1270: sub authenticate {
1.1073 raeburn 1271: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1272: $upass=&escape($upass);
1273: $uname= &LONCAPA::clean_username($uname);
1.836 www 1274: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1275: my $newhome;
1.836 www 1276: if ((!$uhome) || ($uhome eq 'no_host')) {
1277: # Maybe the machine was offline and only re-appeared again recently?
1278: &reconlonc();
1279: # One more
1.952 raeburn 1280: $uhome=&homeserver($uname,$udom,1);
1281: if (($uhome eq 'no_host') && $checkdefauth) {
1282: if (defined(&domain($udom,'primary'))) {
1283: $newhome=&domain($udom,'primary');
1284: }
1285: if ($newhome ne '') {
1286: $uhome = $newhome;
1287: }
1288: }
1.836 www 1289: if ((!$uhome) || ($uhome eq 'no_host')) {
1290: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1291: return 'no_host';
1292: }
1.1 albertel 1293: }
1.1073 raeburn 1294: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1295: if ($answer eq 'authorized') {
1.952 raeburn 1296: if ($newhome) {
1297: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1298: return 'no_account_on_host';
1299: } else {
1300: &logthis("User $uname at $udom authorized by $uhome");
1301: return $uhome;
1302: }
1.471 albertel 1303: }
1304: if ($answer eq 'non_authorized') {
1305: &logthis("User $uname at $udom rejected by $uhome");
1.1172.2.147 raeburn 1306: return 'no_host';
1.9 www 1307: }
1.471 albertel 1308: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1309: return 'no_host';
1310: }
1311:
1.1073 raeburn 1312: sub can_host_session {
1.1074 raeburn 1313: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1314: my $canhost = 1;
1.1074 raeburn 1315: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1316: if (ref($remotesessions) eq 'HASH') {
1317: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1318: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1319: $canhost = 0;
1320: } else {
1321: $canhost = 1;
1322: }
1323: }
1324: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1325: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1326: $canhost = 1;
1327: } else {
1328: $canhost = 0;
1329: }
1330: }
1331: if ($canhost) {
1332: if ($remotesessions->{'version'} ne '') {
1333: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1334: if ($reqmajor ne '' && $reqminor ne '') {
1335: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1336: my $major = $1;
1337: my $minor = $2;
1338: if (($major < $reqmajor ) ||
1339: (($major == $reqmajor) && ($minor < $reqminor))) {
1340: $canhost = 0;
1341: }
1342: } else {
1343: $canhost = 0;
1344: }
1345: }
1346: }
1347: }
1348: }
1349: if ($canhost) {
1350: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1351: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1352: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1353: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1354: if (($uint_dom ne '') &&
1355: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1356: $canhost = 0;
1357: } else {
1358: $canhost = 1;
1359: }
1360: }
1361: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1362: if (($uint_dom ne '') &&
1363: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1364: $canhost = 1;
1365: } else {
1366: $canhost = 0;
1367: }
1368: }
1369: }
1370: }
1371: return $canhost;
1372: }
1373:
1.1083 raeburn 1374: sub spare_can_host {
1375: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1376: my $canhost=1;
1.1172.2.62 raeburn 1377: my $try_server_hostname = &hostname($try_server);
1378: my $serverhomeID = &get_server_homeID($try_server_hostname);
1379: my $serverhomedom = &host_domain($serverhomeID);
1380: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1381: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1382: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1383: $canhost = 0;
1384: }
1385: }
1.1172.2.136 raeburn 1386: if ($canhost) {
1387: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1388: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1389: unless (&shared_institution($udom,$try_server)) {
1390: $canhost = 0;
1391: }
1392: }
1393: }
1394: }
1.1172.2.62 raeburn 1395: if (($canhost) && ($uint_dom)) {
1396: my @intdoms;
1397: my $internet_names = &get_internet_names($try_server);
1398: if (ref($internet_names) eq 'ARRAY') {
1399: @intdoms = @{$internet_names};
1400: }
1401: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1402: my $remoterev = &get_server_loncaparev(undef,$try_server);
1403: $canhost = &can_host_session($udom,$try_server,$remoterev,
1404: $remotesessions,
1405: $defdomdefaults{'hostedsessions'});
1406: }
1.1083 raeburn 1407: }
1408: return $canhost;
1409: }
1410:
1.1123 raeburn 1411: sub this_host_spares {
1412: my ($dom) = @_;
1.1126 raeburn 1413: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1414: my @hosts = ¤t_machine_ids();
1415: foreach my $lonhost (@hosts) {
1416: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1417: $dom_in_use = $dom;
1418: $lonhost_in_use = $lonhost;
1.1123 raeburn 1419: last;
1420: }
1421: }
1.1126 raeburn 1422: if ($dom_in_use ne '') {
1423: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1424: }
1425: if (ref($result) ne 'HASH') {
1426: $lonhost_in_use = $perlvar{'lonHostID'};
1427: $dom_in_use = &host_domain($lonhost_in_use);
1428: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1429: if (ref($result) ne 'HASH') {
1430: $result = \%spareid;
1431: }
1432: }
1433: return $result;
1434: }
1435:
1436: sub spares_for_offload {
1437: my ($dom_in_use,$lonhost_in_use) = @_;
1438: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1439: if (defined($cached)) {
1440: return $result;
1441: } else {
1.1126 raeburn 1442: my $cachetime = 60*60*24;
1443: my %domconfig =
1444: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1445: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1446: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1447: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1448: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1449: }
1450: }
1451: }
1452: }
1.1126 raeburn 1453: return;
1.1123 raeburn 1454: }
1455:
1.1129 raeburn 1456: sub get_lonbalancer_config {
1457: my ($servers) = @_;
1458: my ($currbalancer,$currtargets);
1459: if (ref($servers) eq 'HASH') {
1460: foreach my $server (keys(%{$servers})) {
1461: my %what = (
1462: spareid => 1,
1463: perlvar => 1,
1464: );
1465: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1466: if ($result eq 'ok') {
1467: if (ref($returnhash) eq 'HASH') {
1468: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1469: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1470: $currbalancer = $server;
1471: $currtargets = {};
1472: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1473: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1474: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1475: }
1476: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1477: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1478: }
1479: }
1480: last;
1481: }
1482: }
1483: }
1484: }
1485: }
1486: }
1487: return ($currbalancer,$currtargets);
1488: }
1489:
1490: sub check_loadbalancing {
1.1172.2.88 raeburn 1491: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1492: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1493: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1494: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1495: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1496: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1497: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1498: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1499: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1500: my $domneedscache;
1.1129 raeburn 1501: my $cachetime = 60*60*24;
1502:
1503: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1504: $dom_in_use = $udom;
1505: $homeintdom = 1;
1506: } else {
1507: $dom_in_use = $serverhomedom;
1508: }
1509: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1510: unless (defined($cached)) {
1511: my %domconfig =
1512: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1513: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1514: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1515: } else {
1516: $domneedscache = $dom_in_use;
1.1129 raeburn 1517: }
1518: }
1519: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1520: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1521: &check_balancer_result($result,@hosts);
1.1129 raeburn 1522: if ($is_balancer) {
1523: if (ref($currrules) eq 'HASH') {
1524: if ($homeintdom) {
1525: if ($uname ne '') {
1526: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1527: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1528: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1529: $rule_in_effect = $currrules->{'_LC_author'};
1530: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1531: $rule_in_effect = $currrules->{'_LC_adv'}
1532: }
1533: }
1534: if ($rule_in_effect eq '') {
1535: my %userenv = &userenvironment($udom,$uname,'inststatus');
1536: if ($userenv{'inststatus'} ne '') {
1537: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1538: my ($othertitle,$usertypes,$types) =
1539: &Apache::loncommon::sorted_inst_types($udom);
1540: if (ref($types) eq 'ARRAY') {
1541: foreach my $type (@{$types}) {
1542: if (grep(/^\Q$type\E$/,@statuses)) {
1543: if (exists($currrules->{$type})) {
1544: $rule_in_effect = $currrules->{$type};
1545: }
1546: }
1547: }
1548: }
1549: } else {
1550: if (exists($currrules->{'default'})) {
1551: $rule_in_effect = $currrules->{'default'};
1552: }
1553: }
1554: }
1555: } else {
1556: if (exists($currrules->{'default'})) {
1557: $rule_in_effect = $currrules->{'default'};
1558: }
1559: }
1560: } else {
1561: if ($currrules->{'_LC_external'} ne '') {
1562: $rule_in_effect = $currrules->{'_LC_external'};
1563: }
1564: }
1565: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1566: $uname,$udom);
1567: }
1568: }
1569: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1570: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1571: unless (defined($cached)) {
1572: my %domconfig =
1573: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1574: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1575: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1576: } else {
1577: $domneedscache = $serverhomedom;
1.1129 raeburn 1578: }
1579: }
1580: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1581: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1582: &check_balancer_result($result,@hosts);
1583: if ($is_balancer) {
1.1129 raeburn 1584: if (ref($currrules) eq 'HASH') {
1585: if ($currrules->{'_LC_internetdom'} ne '') {
1586: $rule_in_effect = $currrules->{'_LC_internetdom'};
1587: }
1588: }
1589: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1590: $uname,$udom);
1591: }
1592: } else {
1593: if ($perlvar{'lonBalancer'} eq 'yes') {
1594: $is_balancer = 1;
1595: $offloadto = &this_host_spares($dom_in_use);
1596: }
1.1172.2.75 raeburn 1597: unless (defined($cached)) {
1598: $domneedscache = $serverhomedom;
1599: }
1.1129 raeburn 1600: }
1601: } else {
1602: if ($perlvar{'lonBalancer'} eq 'yes') {
1603: $is_balancer = 1;
1604: $offloadto = &this_host_spares($dom_in_use);
1605: }
1.1172.2.75 raeburn 1606: unless (defined($cached)) {
1607: $domneedscache = $serverhomedom;
1608: }
1609: }
1610: if ($domneedscache) {
1611: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1612: }
1.1172.2.130 raeburn 1613: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1614: my $lowest_load = 30000;
1615: if (ref($offloadto) eq 'HASH') {
1616: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1617: foreach my $try_server (@{$offloadto->{'primary'}}) {
1618: ($otherserver,$lowest_load) =
1619: &compare_server_load($try_server,$otherserver,$lowest_load);
1620: }
1.1129 raeburn 1621: }
1.1172.2.5 raeburn 1622: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1623:
1.1172.2.5 raeburn 1624: if (!$found_server) {
1625: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1626: foreach my $try_server (@{$offloadto->{'default'}}) {
1627: ($otherserver,$lowest_load) =
1628: &compare_server_load($try_server,$otherserver,$lowest_load);
1629: }
1630: }
1631: }
1632: } elsif (ref($offloadto) eq 'ARRAY') {
1633: if (@{$offloadto} == 1) {
1634: $otherserver = $offloadto->[0];
1635: } elsif (@{$offloadto} > 1) {
1636: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1637: ($otherserver,$lowest_load) =
1638: &compare_server_load($try_server,$otherserver,$lowest_load);
1639: }
1640: }
1641: }
1.1172.2.88 raeburn 1642: unless ($caller eq 'login') {
1643: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1644: $is_balancer = 0;
1645: if ($uname ne '' && $udom ne '') {
1646: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1647: &appenv({'user.loadbalexempt' => $lonhost,
1648: 'user.loadbalcheck.time' => time});
1649: }
1.1172.2.5 raeburn 1650: }
1.1129 raeburn 1651: }
1652: }
1.1172.2.130 raeburn 1653: }
1654: if (($is_balancer) && (!$homeintdom)) {
1655: undef($setcookie);
1.1129 raeburn 1656: }
1.1172.2.107 raeburn 1657: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1658: }
1659:
1.1172.2.12 raeburn 1660: sub check_balancer_result {
1661: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1662: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1663: if (ref($result) eq 'HASH') {
1664: if ($result->{'lonhost'} ne '') {
1665: my $currbalancer = $result->{'lonhost'};
1666: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1667: $is_balancer = 1;
1668: $currtargets = $result->{'targets'};
1669: $currrules = $result->{'rules'};
1670: }
1671: } else {
1672: foreach my $key (keys(%{$result})) {
1673: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1674: (ref($result->{$key}) eq 'HASH')) {
1675: $is_balancer = 1;
1676: $currrules = $result->{$key}{'rules'};
1677: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1678: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1679: last;
1680: }
1681: }
1682: }
1683: }
1.1172.2.107 raeburn 1684: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1685: }
1686:
1.1129 raeburn 1687: sub get_loadbalancer_targets {
1688: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1689: my $offloadto;
1.1172.2.4 raeburn 1690: if ($rule_in_effect eq 'none') {
1691: return [$perlvar{'lonHostID'}];
1692: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1693: $offloadto = $currtargets;
1694: } else {
1695: if ($rule_in_effect eq 'homeserver') {
1696: my $homeserver = &homeserver($uname,$udom);
1697: if ($homeserver ne 'no_host') {
1698: $offloadto = [$homeserver];
1699: }
1700: } elsif ($rule_in_effect eq 'externalbalancer') {
1701: my %domconfig =
1702: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1703: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1704: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1705: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1706: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1707: }
1708: }
1709: } else {
1.1172.2.7 raeburn 1710: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1711: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1712: if (&hostname($remotebalancer) ne '') {
1713: $offloadto = [$remotebalancer];
1714: }
1715: }
1716: } elsif (&hostname($rule_in_effect) ne '') {
1717: $offloadto = [$rule_in_effect];
1718: }
1719: }
1720: return $offloadto;
1721: }
1722:
1.1127 raeburn 1723: sub internet_dom_servers {
1724: my ($dom) = @_;
1725: my (%uniqservers,%servers);
1726: my $primaryserver = &hostname(&domain($dom,'primary'));
1727: my @machinedoms = &machine_domains($primaryserver);
1728: foreach my $mdom (@machinedoms) {
1729: my %currservers = %servers;
1730: my %server = &get_servers($mdom);
1731: %servers = (%currservers,%server);
1732: }
1733: my %by_hostname;
1734: foreach my $id (keys(%servers)) {
1735: push(@{$by_hostname{$servers{$id}}},$id);
1736: }
1737: foreach my $hostname (sort(keys(%by_hostname))) {
1738: if (@{$by_hostname{$hostname}} > 1) {
1739: my $match = 0;
1740: foreach my $id (@{$by_hostname{$hostname}}) {
1741: if (&host_domain($id) eq $dom) {
1742: $uniqservers{$id} = $hostname;
1743: $match = 1;
1744: }
1745: }
1746: unless ($match) {
1747: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1748: }
1749: } else {
1750: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1751: }
1752: }
1753: return %uniqservers;
1754: }
1755:
1.1 albertel 1756: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1757:
1.599 albertel 1758: my %homecache;
1.1 albertel 1759: sub homeserver {
1.230 stredwic 1760: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1761: my $index="$uname:$udom";
1.426 albertel 1762:
1.599 albertel 1763: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1764:
1765: my %servers = &get_servers($udom,'library');
1766: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1767: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1768: exists($badServerCache{$tryserver}));
1.841 albertel 1769:
1770: my $answer=reply("home:$udom:$uname",$tryserver);
1771: if ($answer eq 'found') {
1772: delete($badServerCache{$tryserver});
1773: return $homecache{$index}=$tryserver;
1774: } elsif ($answer eq 'no_host') {
1775: $badServerCache{$tryserver}=1;
1776: }
1.1 albertel 1777: }
1778: return 'no_host';
1.70 www 1779: }
1780:
1781: # ------------------------------------- Find the usernames behind a list of IDs
1782:
1783: sub idget {
1784: my ($udom,@ids)=@_;
1785: my %returnhash=();
1786:
1.841 albertel 1787: my %servers = &get_servers($udom,'library');
1788: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1789: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1790: $idlist=~tr/A-Z/a-z/;
1791: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1792: my @answer=();
1793: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1794: @answer=split(/\&/,$reply);
1795: } ;
1796: my $i;
1797: for ($i=0;$i<=$#ids;$i++) {
1798: if ($answer[$i]) {
1.1172.2.73 raeburn 1799: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1800: }
1801: }
1802: }
1.70 www 1803: return %returnhash;
1804: }
1805:
1806: # ------------------------------------- Find the IDs behind a list of usernames
1807:
1808: sub idrget {
1809: my ($udom,@unames)=@_;
1810: my %returnhash=();
1.800 albertel 1811: foreach my $uname (@unames) {
1812: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1813: }
1.70 www 1814: return %returnhash;
1815: }
1816:
1817: # ------------------------------- Store away a list of names and associated IDs
1818:
1819: sub idput {
1820: my ($udom,%ids)=@_;
1821: my %servers=();
1.800 albertel 1822: foreach my $uname (keys(%ids)) {
1823: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1824: my $uhom=&homeserver($uname,$udom);
1.70 www 1825: if ($uhom ne 'no_host') {
1.800 albertel 1826: my $id=&escape($ids{$uname});
1.70 www 1827: $id=~tr/A-Z/a-z/;
1.800 albertel 1828: my $esc_unam=&escape($uname);
1.70 www 1829: if ($servers{$uhom}) {
1.800 albertel 1830: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1831: } else {
1.800 albertel 1832: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1833: }
1834: }
1.191 harris41 1835: }
1.800 albertel 1836: foreach my $server (keys(%servers)) {
1837: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1838: }
1.344 www 1839: }
1840:
1.1172.2.30 raeburn 1841: # ---------------------------------------- Delete unwanted IDs from ids.db file
1842:
1843: sub iddel {
1844: my ($udom,$idshashref,$uhome)=@_;
1845: my %result=();
1846: unless (ref($idshashref) eq 'HASH') {
1847: return %result;
1848: }
1849: my %servers=();
1850: while (my ($id,$uname) = each(%{$idshashref})) {
1851: my $uhom;
1852: if ($uhome) {
1853: $uhom = $uhome;
1854: } else {
1855: $uhom=&homeserver($uname,$udom);
1856: }
1857: if ($uhom ne 'no_host') {
1858: if ($servers{$uhom}) {
1859: $servers{$uhom}.='&'.&escape($id);
1860: } else {
1861: $servers{$uhom}=&escape($id);
1862: }
1863: }
1864: }
1865: foreach my $server (keys(%servers)) {
1866: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1867: }
1868: return %result;
1869: }
1870:
1.1023 raeburn 1871: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1872: sub dump_dom {
1.1165 droeschl 1873: my ($namespace, $udom, $regexp) = @_;
1874:
1875: $udom ||= $env{'user.domain'};
1876:
1877: return () unless $udom;
1878:
1879: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1880: }
1881:
1.1023 raeburn 1882: # ------------------------------------------ get items from domain db files
1.806 raeburn 1883:
1884: sub get_dom {
1.860 raeburn 1885: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1886: return if ($udom eq 'public');
1.806 raeburn 1887: my $items='';
1888: foreach my $item (@$storearr) {
1889: $items.=&escape($item).'&';
1890: }
1891: $items=~s/\&$//;
1.860 raeburn 1892: if (!$udom) {
1893: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1894: return if ($udom eq 'public');
1.860 raeburn 1895: if (defined(&domain($udom,'primary'))) {
1896: $uhome=&domain($udom,'primary');
1897: } else {
1.874 albertel 1898: undef($uhome);
1.860 raeburn 1899: }
1900: } else {
1901: if (!$uhome) {
1902: if (defined(&domain($udom,'primary'))) {
1903: $uhome=&domain($udom,'primary');
1904: }
1905: }
1906: }
1907: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139 raeburn 1908: my $rep;
1909: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
1910: # domain information is hosted on this machine
1911: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1912: } else {
1913: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1914: }
1.866 raeburn 1915: my %returnhash;
1.875 albertel 1916: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1917: return %returnhash;
1918: }
1.806 raeburn 1919: my @pairs=split(/\&/,$rep);
1920: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1921: return @pairs;
1922: }
1923: my $i=0;
1924: foreach my $item (@$storearr) {
1925: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1926: $i++;
1927: }
1928: return %returnhash;
1929: } else {
1.880 banghart 1930: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1931: }
1932: }
1933:
1934: # -------------------------------------------- put items in domain db files
1935:
1936: sub put_dom {
1.860 raeburn 1937: my ($namespace,$storehash,$udom,$uhome)=@_;
1938: if (!$udom) {
1939: $udom=$env{'user.domain'};
1940: if (defined(&domain($udom,'primary'))) {
1941: $uhome=&domain($udom,'primary');
1942: } else {
1.874 albertel 1943: undef($uhome);
1.860 raeburn 1944: }
1945: } else {
1946: if (!$uhome) {
1947: if (defined(&domain($udom,'primary'))) {
1948: $uhome=&domain($udom,'primary');
1949: }
1950: }
1951: }
1952: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1953: my $items='';
1954: foreach my $item (keys(%$storehash)) {
1955: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1956: }
1957: $items=~s/\&$//;
1958: return &reply("putdom:$udom:$namespace:$items",$uhome);
1959: } else {
1.860 raeburn 1960: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1961: }
1962: }
1963:
1.1023 raeburn 1964: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1965: sub newput_dom {
1.1023 raeburn 1966: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1967: my $result;
1968: if (!$udom) {
1969: $udom=$env{'user.domain'};
1970: }
1.1023 raeburn 1971: if ($udom) {
1972: my $uname = &get_domainconfiguser($udom);
1973: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1974: }
1975: return $result;
1976: }
1977:
1.1023 raeburn 1978: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1979: sub del_dom {
1.1023 raeburn 1980: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1981: if (ref($storearr) eq 'ARRAY') {
1982: if (!$udom) {
1983: $udom=$env{'user.domain'};
1984: }
1.1023 raeburn 1985: if ($udom) {
1986: my $uname = &get_domainconfiguser($udom);
1987: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1988: }
1989: }
1990: }
1991:
1.1023 raeburn 1992: # ----------------------------------construct domainconfig user for a domain
1993: sub get_domainconfiguser {
1994: my ($udom) = @_;
1995: return $udom.'-domainconfig';
1996: }
1997:
1.837 raeburn 1998: sub retrieve_inst_usertypes {
1999: my ($udom) = @_;
2000: my (%returnhash,@order);
1.989 raeburn 2001: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2002: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2003: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 2004: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2005: } else {
2006: if (defined(&domain($udom,'primary'))) {
2007: my $uhome=&domain($udom,'primary');
2008: my $rep=&reply("inst_usertypes:$udom",$uhome);
2009: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 2010: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2011: return (\%returnhash,\@order);
2012: }
2013: my ($hashitems,$orderitems) = split(/:/,$rep);
2014: my @pairs=split(/\&/,$hashitems);
2015: foreach my $item (@pairs) {
2016: my ($key,$value)=split(/=/,$item,2);
2017: $key = &unescape($key);
2018: next if ($key =~ /^error: 2 /);
2019: $returnhash{$key}=&thaw_unescape($value);
2020: }
2021: my @esc_order = split(/\&/,$orderitems);
2022: foreach my $item (@esc_order) {
2023: push(@order,&unescape($item));
2024: }
2025: } else {
1.1172.2.44 raeburn 2026: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2027: }
1.1172.2.44 raeburn 2028: return (\%returnhash,\@order);
1.837 raeburn 2029: }
2030: }
2031:
1.868 raeburn 2032: sub is_domainimage {
2033: my ($url) = @_;
1.1172.2.142 raeburn 2034: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2035: if (&domain($1) ne '') {
2036: return '1';
2037: }
2038: }
2039: return;
2040: }
2041:
1.899 raeburn 2042: sub inst_directory_query {
2043: my ($srch) = @_;
2044: my $udom = $srch->{'srchdomain'};
2045: my %results;
2046: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2047: my $outcome;
1.899 raeburn 2048: if ($homeserver ne '') {
1.1172.2.116 raeburn 2049: unless ($homeserver eq $perlvar{'lonHostID'}) {
2050: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2051: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2052: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2053: if (($major eq '' && $minor eq '') || ($major < 2) ||
2054: (($major == 2) && ($minor < 11)) ||
2055: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2056: return;
2057: }
2058: }
2059: }
1.904 albertel 2060: my $queryid=&reply("querysend:instdirsearch:".
2061: &escape($srch->{'srchby'}).':'.
2062: &escape($srch->{'srchterm'}).':'.
2063: &escape($srch->{'srchtype'}),$homeserver);
2064: my $host=&hostname($homeserver);
2065: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2066: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2067: return;
2068: }
2069: my $response = &get_query_reply($queryid);
2070: my $maxtries = 5;
2071: my $tries = 1;
2072: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2073: $response = &get_query_reply($queryid);
2074: $tries ++;
2075: }
2076:
2077: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2078: if ($response eq 'unavailable') {
2079: $outcome = $response;
2080: } else {
2081: $outcome = 'ok';
2082: my @matches = split(/\n/,$response);
2083: foreach my $match (@matches) {
2084: my ($key,$value) = split(/=/,$match);
2085: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2086: }
1.899 raeburn 2087: }
2088: }
2089: }
1.909 raeburn 2090: return ($outcome,%results);
1.899 raeburn 2091: }
2092:
2093: sub usersearch {
2094: my ($srch) = @_;
2095: my $dom = $srch->{'srchdomain'};
2096: my %results;
2097: my %libserv = &all_library();
2098: my $query = 'usersearch';
2099: foreach my $tryserver (keys(%libserv)) {
2100: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2101: unless ($tryserver eq $perlvar{'lonHostID'}) {
2102: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2103: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2104: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2105: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2106: (($major == 2) && ($minor < 11)) ||
2107: (($major == 2) && ($minor == 11) && ($subver < 3)));
2108: }
2109: }
1.899 raeburn 2110: my $host=&hostname($tryserver);
2111: my $queryid=
1.911 raeburn 2112: &reply("querysend:".&escape($query).':'.
2113: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2114: &escape($srch->{'srchtype'}).':'.
2115: &escape($srch->{'srchterm'}),$tryserver);
2116: if ($queryid !~/^\Q$host\E\_/) {
2117: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2118: next;
1.899 raeburn 2119: }
2120: my $reply = &get_query_reply($queryid);
2121: my $maxtries = 1;
2122: my $tries = 1;
2123: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2124: $reply = &get_query_reply($queryid);
2125: $tries ++;
2126: }
2127: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2128: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2129: } else {
1.911 raeburn 2130: my @matches;
2131: if ($reply =~ /\n/) {
2132: @matches = split(/\n/,$reply);
2133: } else {
2134: @matches = split(/\&/,$reply);
2135: }
1.899 raeburn 2136: foreach my $match (@matches) {
2137: my ($uname,$udom,%userhash);
1.911 raeburn 2138: foreach my $entry (split(/:/,$match)) {
2139: my ($key,$value) =
2140: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2141: $userhash{$key} = $value;
2142: if ($key eq 'username') {
2143: $uname = $value;
2144: } elsif ($key eq 'domain') {
2145: $udom = $value;
1.911 raeburn 2146: }
1.899 raeburn 2147: }
2148: $results{$uname.':'.$udom} = \%userhash;
2149: }
2150: }
2151: }
2152: }
2153: return %results;
2154: }
2155:
1.912 raeburn 2156: sub get_instuser {
2157: my ($udom,$uname,$id) = @_;
2158: my $homeserver = &domain($udom,'primary');
2159: my ($outcome,%results);
2160: if ($homeserver ne '') {
2161: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2162: &escape($id).':'.&escape($udom),$homeserver);
2163: my $host=&hostname($homeserver);
2164: if ($queryid !~/^\Q$host\E\_/) {
2165: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2166: return;
2167: }
2168: my $response = &get_query_reply($queryid);
2169: my $maxtries = 5;
2170: my $tries = 1;
2171: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2172: $response = &get_query_reply($queryid);
2173: $tries ++;
2174: }
2175: if (!&error($response) && $response ne 'refused') {
2176: if ($response eq 'unavailable') {
2177: $outcome = $response;
2178: } else {
2179: $outcome = 'ok';
2180: my @matches = split(/\n/,$response);
2181: foreach my $match (@matches) {
2182: my ($key,$value) = split(/=/,$match);
2183: $results{&unescape($key)} = &thaw_unescape($value);
2184: }
2185: }
2186: }
2187: }
2188: my %userinfo;
2189: if (ref($results{$uname}) eq 'HASH') {
2190: %userinfo = %{$results{$uname}};
2191: }
2192: return ($outcome,%userinfo);
2193: }
2194:
1.1172.2.69 raeburn 2195: sub get_multiple_instusers {
2196: my ($udom,$users,$caller) = @_;
2197: my ($outcome,$results);
2198: if (ref($users) eq 'HASH') {
2199: my $count = keys(%{$users});
2200: my $requested = &freeze_escape($users);
2201: my $homeserver = &domain($udom,'primary');
2202: if ($homeserver ne '') {
2203: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2204: my $host=&hostname($homeserver);
2205: if ($queryid !~/^\Q$host\E\_/) {
2206: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2207: ' for host: '.$homeserver.'in domain '.$udom);
2208: return ($outcome,$results);
2209: }
2210: my $response = &get_query_reply($queryid);
2211: my $maxtries = 5;
2212: if ($count > 100) {
2213: $maxtries = 1+int($count/20);
2214: }
2215: my $tries = 1;
2216: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2217: $response = &get_query_reply($queryid);
2218: $tries ++;
2219: }
2220: if ($response eq '') {
2221: $results = {};
2222: foreach my $key (keys(%{$users})) {
2223: my ($uname,$id);
2224: if ($caller eq 'id') {
2225: $id = $key;
2226: } else {
2227: $uname = $key;
2228: }
2229: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2230: $outcome = $resp;
2231: if ($resp eq 'ok') {
2232: %{$results} = (%{$results}, %info);
2233: } else {
2234: last;
2235: }
2236: }
2237: } elsif(!&error($response) && ($response ne 'refused')) {
2238: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2239: $outcome = $response;
2240: } else {
2241: ($outcome,my $userdata) = split(/=/,$response,2);
2242: if ($outcome eq 'ok') {
2243: $results = &thaw_unescape($userdata);
2244: }
2245: }
2246: }
2247: }
2248: }
2249: return ($outcome,$results);
2250: }
2251:
1.912 raeburn 2252: sub inst_rulecheck {
1.923 raeburn 2253: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2254: my %returnhash;
2255: if ($udom ne '') {
2256: if (ref($rules) eq 'ARRAY') {
2257: @{$rules} = map {&escape($_);} (@{$rules});
2258: my $rulestr = join(':',@{$rules});
2259: my $homeserver=&domain($udom,'primary');
2260: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2261: my $response;
2262: if ($item eq 'username') {
2263: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2264: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2265: $homeserver));
1.923 raeburn 2266: } elsif ($item eq 'id') {
2267: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2268: ':'.&escape($id).':'.$rulestr,
2269: $homeserver));
1.945 raeburn 2270: } elsif ($item eq 'selfcreate') {
2271: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2272: &escape($udom).':'.&escape($uname).
2273: ':'.$rulestr,$homeserver));
1.1172.2.147 raeburn 2274: } elsif ($item eq 'unamemap') {
2275: $response=&unescape(&reply('instunamemapcheck:'.
2276: &escape($udom).':'.&escape($uname).
2277: ':'.$rulestr,$homeserver));
1.923 raeburn 2278: }
1.912 raeburn 2279: if ($response ne 'refused') {
2280: my @pairs=split(/\&/,$response);
2281: foreach my $item (@pairs) {
2282: my ($key,$value)=split(/=/,$item,2);
2283: $key = &unescape($key);
2284: next if ($key =~ /^error: 2 /);
2285: $returnhash{$key}=&thaw_unescape($value);
2286: }
2287: }
2288: }
2289: }
2290: }
2291: return %returnhash;
2292: }
2293:
2294: sub inst_userrules {
1.923 raeburn 2295: my ($udom,$check) = @_;
1.912 raeburn 2296: my (%ruleshash,@ruleorder);
2297: if ($udom ne '') {
2298: my $homeserver=&domain($udom,'primary');
2299: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2300: my $response;
2301: if ($check eq 'id') {
2302: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2303: $homeserver);
1.943 raeburn 2304: } elsif ($check eq 'email') {
2305: $response=&reply('instemailrules:'.&escape($udom),
2306: $homeserver);
1.1172.2.147 raeburn 2307: } elsif ($check eq 'unamemap') {
2308: $response=&reply('unamemaprules:'.&escape($udom),
2309: $homeserver);
1.923 raeburn 2310: } else {
2311: $response=&reply('instuserrules:'.&escape($udom),
2312: $homeserver);
2313: }
1.912 raeburn 2314: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2315: ($response ne 'unknown_cmd') &&
1.912 raeburn 2316: ($response ne 'no_such_host')) {
2317: my ($hashitems,$orderitems) = split(/:/,$response);
2318: my @pairs=split(/\&/,$hashitems);
2319: foreach my $item (@pairs) {
2320: my ($key,$value)=split(/=/,$item,2);
2321: $key = &unescape($key);
2322: next if ($key =~ /^error: 2 /);
2323: $ruleshash{$key}=&thaw_unescape($value);
2324: }
2325: my @esc_order = split(/\&/,$orderitems);
2326: foreach my $item (@esc_order) {
2327: push(@ruleorder,&unescape($item));
2328: }
2329: }
2330: }
2331: }
2332: return (\%ruleshash,\@ruleorder);
2333: }
2334:
1.976 raeburn 2335: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2336:
2337: sub get_domain_defaults {
1.1172.2.35 raeburn 2338: my ($domain,$ignore_cache) = @_;
2339: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2340: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2341: unless ($ignore_cache) {
2342: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2343: if (defined($cached)) {
2344: if (ref($result) eq 'HASH') {
2345: return %{$result};
2346: }
1.943 raeburn 2347: }
2348: }
2349: my %domdefaults;
2350: my %domconfig =
1.989 raeburn 2351: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2352: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2353: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2354: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2355: 'coursecategories','autoenroll',
1.1172.2.146 raeburn 2356: 'helpsettings','wafproxy'],$domain);
1.1172.2.41 raeburn 2357: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2358: if (ref($domconfig{'defaults'}) eq 'HASH') {
2359: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2360: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2361: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2362: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2363: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2364: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2365: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2366: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2367: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.147 raeburn 2368: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2369: } else {
2370: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2371: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2372: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2373: }
1.976 raeburn 2374: if (ref($domconfig{'quotas'}) eq 'HASH') {
2375: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2376: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2377: } else {
2378: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2379: }
1.1172.2.6 raeburn 2380: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2381: foreach my $item (@usertools) {
2382: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2383: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2384: }
2385: }
1.1172.2.29 raeburn 2386: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2387: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2388: }
1.976 raeburn 2389: }
1.985 raeburn 2390: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2391: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2392: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2393: }
2394: }
1.1172.2.9 raeburn 2395: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2396: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2397: }
1.989 raeburn 2398: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2399: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2400: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2401: }
2402: }
1.1047 raeburn 2403: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2404: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144 raeburn 2405: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60 raeburn 2406: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2407: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2408: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2409: }
1.1172.2.41 raeburn 2410: foreach my $type (@coursetypes) {
2411: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2412: unless ($type eq 'community') {
2413: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2414: }
2415: }
2416: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2417: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2418: }
1.1172.2.60 raeburn 2419: if ($domdefaults{'postsubmit'} eq 'on') {
2420: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2421: $domdefaults{$type.'postsubtimeout'} =
2422: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2423: }
2424: }
1.1172.2.30 raeburn 2425: }
1.1172.2.67 raeburn 2426: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2427: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2428: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2429: if (@clonecodes) {
2430: $domdefaults{'canclone'} = join('+',@clonecodes);
2431: }
2432: }
2433: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2434: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2435: }
1.1172.2.103 raeburn 2436: if ($domconfig{'coursedefaults'}{'texengine'}) {
2437: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2438: }
1.1047 raeburn 2439: }
1.1073 raeburn 2440: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2441: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2442: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2443: }
2444: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2445: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2446: }
1.1172.2.62 raeburn 2447: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2448: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2449: }
1.1172.2.137 raeburn 2450: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136 raeburn 2451: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2452: }
1.1073 raeburn 2453: }
1.1172.2.41 raeburn 2454: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2455: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2456: my @settings = ('types','registered','enroll_dates','access_dates','section',
2457: 'approval','limit');
2458: foreach my $type (@coursetypes) {
2459: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2460: my @mgrdc = ();
2461: foreach my $item (@settings) {
2462: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2463: push(@mgrdc,$item);
2464: }
2465: }
2466: if (@mgrdc) {
2467: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2468: }
2469: }
2470: }
2471: }
2472: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2473: foreach my $type (@coursetypes) {
2474: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2475: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2476: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2477: }
2478: }
2479: }
2480: }
2481: }
1.1172.2.46 raeburn 2482: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2483: $domdefaults{'catauth'} = 'std';
2484: $domdefaults{'catunauth'} = 'std';
2485: if ($domconfig{'coursecategories'}{'auth'}) {
2486: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2487: }
2488: if ($domconfig{'coursecategories'}{'unauth'}) {
2489: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2490: }
2491: }
1.1172.2.76 raeburn 2492: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2493: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146 raeburn 2494: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76 raeburn 2495: }
1.1172.2.89 raeburn 2496: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2497: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2498: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2499: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2500: }
2501: }
1.1172.2.142 raeburn 2502: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
2503: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
2504: if ($domconfig{'wafproxy'}{$item}) {
2505: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2506: }
2507: }
2508: }
1.1172.2.23 raeburn 2509: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2510: return %domdefaults;
2511: }
2512:
1.1172.2.106 raeburn 2513: sub get_dom_cats {
2514: my ($dom) = @_;
2515: return unless (&domain($dom));
2516: my ($cats,$cached)=&is_cached_new('cats',$dom);
2517: unless (defined($cached)) {
2518: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2519: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2520: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2521: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2522: } else {
2523: $cats = {};
2524: }
2525: } else {
2526: $cats = {};
2527: }
2528: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2529: }
2530: return $cats;
2531: }
2532:
2533: sub get_dom_instcats {
2534: my ($dom) = @_;
2535: return unless (&domain($dom));
2536: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2537: unless (defined($cached)) {
2538: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2539: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2540: if ($totcodes > 0) {
2541: my $caller = 'global';
2542: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2543: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2544: $instcats = {
2545: codes => \%codes,
2546: codetitles => \@codetitles,
2547: cat_titles => \%cat_titles,
2548: cat_order => \%cat_order,
2549: };
2550: &do_cache_new('instcats',$dom,$instcats,3600);
2551: }
2552: }
2553: }
2554: return $instcats;
2555: }
2556:
2557: sub retrieve_instcodes {
2558: my ($coursecodes,$dom) = @_;
2559: my $totcodes;
2560: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2561: foreach my $course (keys(%courses)) {
2562: if (ref($courses{$course}) eq 'HASH') {
2563: if ($courses{$course}{'inst_code'} ne '') {
2564: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2565: $totcodes ++;
2566: }
2567: }
2568: }
2569: return $totcodes;
2570: }
2571:
1.1172.2.113 raeburn 2572: # --------------------------------------------- Get domain config for passwords
2573:
2574: sub get_passwdconf {
2575: my ($dom) = @_;
2576: my (%passwdconf,$gotconf,$lookup);
2577: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2578: if (defined($cached)) {
2579: if (ref($result) eq 'HASH') {
2580: %passwdconf = %{$result};
2581: $gotconf = 1;
2582: }
2583: }
2584: unless ($gotconf) {
2585: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2586: if (ref($domconfig{'passwords'}) eq 'HASH') {
2587: %passwdconf = %{$domconfig{'passwords'}};
2588: }
2589: my $cachetime = 24*60*60;
2590: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2591: }
2592: return %passwdconf;
2593: }
2594:
1.344 www 2595: # --------------------------------------------------- Assign a key to a student
2596:
2597: sub assign_access_key {
1.364 www 2598: #
2599: # a valid key looks like uname:udom#comments
2600: # comments are being appended
2601: #
1.498 www 2602: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2603: $kdom=
1.620 albertel 2604: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2605: $knum=
1.620 albertel 2606: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2607: $cdom=
1.620 albertel 2608: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2609: $cnum=
1.620 albertel 2610: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2611: $udom=$env{'user.name'} unless (defined($udom));
2612: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2613: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2614: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2615: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2616: # assigned to this person
2617: # - this should not happen,
1.345 www 2618: # unless something went wrong
2619: # the first time around
2620: # ready to assign
1.364 www 2621: $logentry=$1.'; '.$logentry;
1.496 www 2622: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2623: $kdom,$knum) eq 'ok') {
1.345 www 2624: # key now belongs to user
1.346 www 2625: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2626: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2627: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2628: return 'ok';
2629: } else {
2630: return
2631: 'error: Count not permanently assign key, will need to be re-entered later.';
2632: }
2633: } else {
2634: return 'error: Could not assign key, try again later.';
2635: }
1.364 www 2636: } elsif (!$existing{$ckey}) {
1.345 www 2637: # the key does not exist
2638: return 'error: The key does not exist';
2639: } else {
2640: # the key is somebody else's
2641: return 'error: The key is already in use';
2642: }
1.344 www 2643: }
2644:
1.364 www 2645: # ------------------------------------------ put an additional comment on a key
2646:
2647: sub comment_access_key {
2648: #
2649: # a valid key looks like uname:udom#comments
2650: # comments are being appended
2651: #
2652: my ($ckey,$cdom,$cnum,$logentry)=@_;
2653: $cdom=
1.620 albertel 2654: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2655: $cnum=
1.620 albertel 2656: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2657: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2658: if ($existing{$ckey}) {
2659: $existing{$ckey}.='; '.$logentry;
2660: # ready to assign
1.367 www 2661: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2662: $cdom,$cnum) eq 'ok') {
2663: return 'ok';
2664: } else {
2665: return 'error: Count not store comment.';
2666: }
2667: } else {
2668: # the key does not exist
2669: return 'error: The key does not exist';
2670: }
2671: }
2672:
1.344 www 2673: # ------------------------------------------------------ Generate a set of keys
2674:
2675: sub generate_access_keys {
1.364 www 2676: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2677: $cdom=
1.620 albertel 2678: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2679: $cnum=
1.620 albertel 2680: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2681: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2682: unless (($cdom) && ($cnum)) { return 0; }
2683: if ($number>10000) { return 0; }
2684: sleep(2); # make sure don't get same seed twice
2685: srand(time()^($$+($$<<15))); # from "Programming Perl"
2686: my $total=0;
2687: for (my $i=1;$i<=$number;$i++) {
2688: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2689: sprintf("%lx",int(100000*rand)).'-'.
2690: sprintf("%lx",int(100000*rand));
2691: $newkey=~s/1/g/g; # folks mix up 1 and l
2692: $newkey=~s/0/h/g; # and also 0 and O
2693: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2694: if ($existing{$newkey}) {
2695: $i--;
2696: } else {
1.364 www 2697: if (&put('accesskeys',
2698: { $newkey => '# generated '.localtime().
1.620 albertel 2699: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2700: '; '.$logentry },
2701: $cdom,$cnum) eq 'ok') {
1.344 www 2702: $total++;
2703: }
2704: }
2705: }
1.620 albertel 2706: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2707: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2708: return $total;
2709: }
2710:
2711: # ------------------------------------------------------- Validate an accesskey
2712:
2713: sub validate_access_key {
2714: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2715: $cdom=
1.620 albertel 2716: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2717: $cnum=
1.620 albertel 2718: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2719: $udom=$env{'user.domain'} unless (defined($udom));
2720: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2721: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2722: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2723: }
2724:
2725: # ------------------------------------- Find the section of student in a course
1.652 albertel 2726: sub devalidate_getsection_cache {
2727: my ($udom,$unam,$courseid)=@_;
2728: my $hashid="$udom:$unam:$courseid";
2729: &devalidate_cache_new('getsection',$hashid);
2730: }
1.298 matthew 2731:
1.815 albertel 2732: sub courseid_to_courseurl {
2733: my ($courseid) = @_;
2734: #already url style courseid
2735: return $courseid if ($courseid =~ m{^/});
2736:
2737: if (exists($env{'course.'.$courseid.'.num'})) {
2738: my $cnum = $env{'course.'.$courseid.'.num'};
2739: my $cdom = $env{'course.'.$courseid.'.domain'};
2740: return "/$cdom/$cnum";
2741: }
2742:
2743: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2744: if (exists($courseinfo{'num'})) {
2745: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2746: }
2747:
2748: return undef;
2749: }
2750:
1.298 matthew 2751: sub getsection {
2752: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2753: my $cachetime=1800;
1.551 albertel 2754:
2755: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2756: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2757: if (defined($cached)) { return $result; }
2758:
1.298 matthew 2759: my %Pending;
2760: my %Expired;
2761: #
2762: # Each role can either have not started yet (pending), be active,
2763: # or have expired.
2764: #
2765: # If there is an active role, we are done.
2766: #
2767: # If there is more than one role which has not started yet,
2768: # choose the one which will start sooner
2769: # If there is one role which has not started yet, return it.
2770: #
2771: # If there is more than one expired role, choose the one which ended last.
2772: # If there is a role which has expired, return it.
2773: #
1.815 albertel 2774: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2775: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2776: foreach my $key (keys(%roleshash)) {
1.479 albertel 2777: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2778: my $section=$1;
2779: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2780: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2781: my $now=time;
1.548 albertel 2782: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2783: $Expired{$end}=$section;
2784: next;
2785: }
1.548 albertel 2786: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2787: $Pending{$start}=$section;
2788: next;
2789: }
1.599 albertel 2790: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2791: }
2792: #
2793: # Presumedly there will be few matching roles from the above
2794: # loop and the sorting time will be negligible.
2795: if (scalar(keys(%Pending))) {
2796: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2797: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2798: }
2799: if (scalar(keys(%Expired))) {
2800: my @sorted = sort {$a <=> $b} keys(%Expired);
2801: my $time = pop(@sorted);
1.599 albertel 2802: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2803: }
1.599 albertel 2804: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2805: }
1.70 www 2806:
1.599 albertel 2807: sub save_cache {
2808: &purge_remembered();
1.722 albertel 2809: #&Apache::loncommon::validate_page();
1.620 albertel 2810: undef(%env);
1.780 albertel 2811: undef($env_loaded);
1.599 albertel 2812: }
1.452 albertel 2813:
1.599 albertel 2814: my $to_remember=-1;
2815: my %remembered;
2816: my %accessed;
2817: my $kicks=0;
2818: my $hits=0;
1.849 albertel 2819: sub make_key {
2820: my ($name,$id) = @_;
1.872 albertel 2821: if (length($id) > 65
2822: && length(&escape($id)) > 200) {
2823: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2824: }
1.849 albertel 2825: return &escape($name.':'.$id);
2826: }
2827:
1.599 albertel 2828: sub devalidate_cache_new {
2829: my ($name,$id,$debug) = @_;
2830: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2831: my $remembered_id=$name.':'.$id;
1.849 albertel 2832: $id=&make_key($name,$id);
1.599 albertel 2833: $memcache->delete($id);
1.1172.2.81 raeburn 2834: delete($remembered{$remembered_id});
2835: delete($accessed{$remembered_id});
1.599 albertel 2836: }
2837:
2838: sub is_cached_new {
2839: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2840: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2841: # keys in %remembered hash, which persists for
2842: # duration of request (no restriction on key length).
2843: if (exists($remembered{$remembered_id})) {
2844: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2845: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2846: $hits++;
1.1172.2.81 raeburn 2847: return ($remembered{$remembered_id},1);
1.599 albertel 2848: }
1.1172.2.81 raeburn 2849: $id=&make_key($name,$id);
1.599 albertel 2850: my $value = $memcache->get($id);
2851: if (!(defined($value))) {
2852: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2853: return (undef,undef);
1.416 albertel 2854: }
1.599 albertel 2855: if ($value eq '__undef__') {
2856: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2857: $value=undef;
2858: }
1.1172.2.81 raeburn 2859: &make_room($remembered_id,$value,$debug);
1.599 albertel 2860: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2861: return ($value,1);
2862: }
2863:
2864: sub do_cache_new {
2865: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2866: my $remembered_id=$name.':'.$id;
1.849 albertel 2867: $id=&make_key($name,$id);
1.599 albertel 2868: my $setvalue=$value;
2869: if (!defined($setvalue)) {
2870: $setvalue='__undef__';
2871: }
1.623 albertel 2872: if (!defined($time) ) {
2873: $time=600;
2874: }
1.599 albertel 2875: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2876: my $result = $memcache->set($id,$setvalue,$time);
2877: if (! $result) {
1.872 albertel 2878: &logthis("caching of id -> $id failed");
1.910 albertel 2879: $memcache->disconnect_all();
1.872 albertel 2880: }
1.600 albertel 2881: # need to make a copy of $value
1.1172.2.81 raeburn 2882: &make_room($remembered_id,$value,$debug);
1.599 albertel 2883: return $value;
2884: }
2885:
2886: sub make_room {
1.1172.2.81 raeburn 2887: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2888:
1.1172.2.81 raeburn 2889: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2890: : $value;
1.599 albertel 2891: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2892: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2893: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2894: my $to_kick;
2895: my $max_time=0;
2896: foreach my $other (keys(%accessed)) {
2897: if (&tv_interval($accessed{$other}) > $max_time) {
2898: $to_kick=$other;
2899: $max_time=&tv_interval($accessed{$other});
2900: }
2901: }
2902: delete($remembered{$to_kick});
2903: delete($accessed{$to_kick});
2904: $kicks++;
2905: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2906: return;
2907: }
2908:
1.599 albertel 2909: sub purge_remembered {
1.604 albertel 2910: #&logthis("Tossing ".scalar(keys(%remembered)));
2911: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2912: undef(%remembered);
2913: undef(%accessed);
1.428 albertel 2914: }
1.70 www 2915: # ------------------------------------- Read an entry from a user's environment
2916:
2917: sub userenvironment {
2918: my ($udom,$unam,@what)=@_;
1.976 raeburn 2919: my $items;
2920: foreach my $item (@what) {
2921: $items.=&escape($item).'&';
2922: }
2923: $items=~s/\&$//;
1.70 www 2924: my %returnhash=();
1.1009 raeburn 2925: my $uhome = &homeserver($unam,$udom);
2926: unless ($uhome eq 'no_host') {
2927: my @answer=split(/\&/,
2928: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2929: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2930: return %returnhash;
2931: }
1.1009 raeburn 2932: my $i;
2933: for ($i=0;$i<=$#what;$i++) {
2934: $returnhash{$what[$i]}=&unescape($answer[$i]);
2935: }
1.70 www 2936: }
2937: return %returnhash;
1.1 albertel 2938: }
2939:
1.617 albertel 2940: # ---------------------------------------------------------- Get a studentphoto
2941: sub studentphoto {
2942: my ($udom,$unam,$ext) = @_;
2943: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2944: if (defined($env{'request.course.id'})) {
1.708 raeburn 2945: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2946: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2947: return(&retrievestudentphoto($udom,$unam,$ext));
2948: } else {
2949: my ($result,$perm_reqd)=
1.707 albertel 2950: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2951: if ($result eq 'ok') {
2952: if (!($perm_reqd eq 'yes')) {
2953: return(&retrievestudentphoto($udom,$unam,$ext));
2954: }
2955: }
2956: }
2957: }
2958: } else {
2959: my ($result,$perm_reqd) =
1.707 albertel 2960: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2961: if ($result eq 'ok') {
2962: if (!($perm_reqd eq 'yes')) {
2963: return(&retrievestudentphoto($udom,$unam,$ext));
2964: }
2965: }
2966: }
2967: return '/adm/lonKaputt/lonlogo_broken.gif';
2968: }
2969:
2970: sub retrievestudentphoto {
2971: my ($udom,$unam,$ext,$type) = @_;
2972: my $home=&Apache::lonnet::homeserver($unam,$udom);
2973: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2974: if ($ret eq 'ok') {
2975: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2976: if ($type eq 'thumbnail') {
2977: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2978: }
2979: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2980: return $tokenurl;
2981: } else {
2982: if ($type eq 'thumbnail') {
2983: return '/adm/lonKaputt/genericstudent_tn.gif';
2984: } else {
2985: return '/adm/lonKaputt/lonlogo_broken.gif';
2986: }
1.617 albertel 2987: }
2988: }
2989:
1.263 www 2990: # -------------------------------------------------------------------- New chat
2991:
2992: sub chatsend {
1.724 raeburn 2993: my ($newentry,$anon,$group)=@_;
1.620 albertel 2994: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2995: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2996: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2997: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2998: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2999: &escape($newentry)).':'.$group,$chome);
1.292 www 3000: }
3001:
3002: # ------------------------------------------ Find current version of a resource
3003:
3004: sub getversion {
3005: my $fname=&clutter(shift);
1.1172.2.10 raeburn 3006: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3007: return ¤tversion(&filelocation('',$fname));
3008: }
3009:
3010: sub currentversion {
3011: my $fname=shift;
3012: my $author=$fname;
3013: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3014: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3015: my $home=&homeserver($uname,$udom);
1.292 www 3016: if ($home eq 'no_host') {
3017: return -1;
3018: }
1.1112 www 3019: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3020: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3021: return -1;
3022: }
1.1112 www 3023: return $answer;
1.263 www 3024: }
3025:
1.1111 www 3026: #
3027: # Return special version number of resource if set by override, empty otherwise
3028: #
3029: sub usedversion {
3030: my $fname=shift;
3031: unless ($fname) { $fname=$env{'request.uri'}; }
3032: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3033: if ($urlversion) { return $urlversion; }
3034: return '';
3035: }
3036:
1.1 albertel 3037: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3038:
1.1 albertel 3039: sub subscribe {
3040: my $fname=shift;
1.761 raeburn 3041: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3042: $fname=~s/[\n\r]//g;
1.1 albertel 3043: my $author=$fname;
3044: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3045: my ($udom,$uname)=split(/\//,$author);
3046: my $home=homeserver($uname,$udom);
1.335 albertel 3047: if ($home eq 'no_host') {
3048: return 'not_found';
1.1 albertel 3049: }
3050: my $answer=reply("sub:$fname",$home);
1.64 www 3051: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3052: $answer.=' by '.$home;
3053: }
1.1 albertel 3054: return $answer;
3055: }
3056:
1.8 www 3057: # -------------------------------------------------------------- Replicate file
3058:
3059: sub repcopy {
3060: my $filename=shift;
1.23 www 3061: $filename=~s/\/+/\//g;
1.1142 raeburn 3062: my $londocroot = $perlvar{'lonDocRoot'};
3063: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3064: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3065: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3066: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3067: return &repcopy_userfile($filename);
3068: }
1.532 albertel 3069: $filename=~s/[\n\r]//g;
1.8 www 3070: my $transname="$filename.in.transfer";
1.828 www 3071: # FIXME: this should flock
1.607 raeburn 3072: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3073: my $remoteurl=subscribe($filename);
1.64 www 3074: if ($remoteurl =~ /^con_lost by/) {
3075: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3076: return 'unavailable';
1.8 www 3077: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3078: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3079: return 'not_found';
1.64 www 3080: } elsif ($remoteurl =~ /^rejected by/) {
3081: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3082: return 'forbidden';
1.20 www 3083: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3084: return 'ok';
1.8 www 3085: } else {
1.290 www 3086: my $author=$filename;
3087: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3088: my ($udom,$uname)=split(/\//,$author);
3089: my $home=homeserver($uname,$udom);
3090: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3091: my @parts=split(/\//,$filename);
3092: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3093: if ($path ne "$londocroot/res") {
1.8 www 3094: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3095: return 'bad_request';
1.8 www 3096: }
3097: my $count;
3098: for ($count=5;$count<$#parts;$count++) {
3099: $path.="/$parts[$count]";
3100: if ((-e $path)!=1) {
3101: mkdir($path,0777);
3102: }
3103: }
3104: my $ua=new LWP::UserAgent;
3105: my $request=new HTTP::Request('GET',"$remoteurl");
3106: my $response=$ua->request($request,$transname);
3107: if ($response->is_error()) {
3108: unlink($transname);
3109: my $message=$response->status_line;
1.672 albertel 3110: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3111: ." LWP get: $message: $filename</font>");
1.607 raeburn 3112: return 'unavailable';
1.8 www 3113: } else {
1.16 www 3114: if ($remoteurl!~/\.meta$/) {
3115: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3116: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3117: if ($mresponse->is_error()) {
3118: unlink($filename.'.meta');
3119: &logthis(
1.672 albertel 3120: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3121: }
3122: }
1.8 www 3123: rename($transname,$filename);
1.607 raeburn 3124: return 'ok';
1.8 www 3125: }
1.290 www 3126: }
1.8 www 3127: }
1.330 www 3128: }
3129:
1.1172.2.124 raeburn 3130: # ------------------------------------------------- Unsubscribe from a resource
3131:
3132: sub unsubscribe {
3133: my ($fname) = @_;
3134: my $answer;
3135: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3136: $fname=~s/[\n\r]//g;
3137: my $author=$fname;
3138: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3139: my ($udom,$uname)=split(/\//,$author);
3140: my $home=homeserver($uname,$udom);
3141: if ($home eq 'no_host') {
3142: $answer = 'no_host';
3143: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3144: $answer = 'home';
3145: } else {
1.1172.2.125 raeburn 3146: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3147: }
3148: return $answer;
3149: }
3150:
1.330 www 3151: # ------------------------------------------------ Get server side include body
3152: sub ssi_body {
1.381 albertel 3153: my ($filelink,%form)=@_;
1.606 matthew 3154: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3155: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3156: }
1.953 www 3157: my $output='';
3158: my $response;
1.980 raeburn 3159: if ($filelink=~/^https?\:/) {
1.954 raeburn 3160: ($output,$response)=&externalssi($filelink);
1.953 www 3161: } else {
1.1004 droeschl 3162: $filelink .= $filelink=~/\?/ ? '&' : '?';
3163: $filelink .= 'inhibitmenu=yes';
1.953 www 3164: ($output,$response)=&ssi($filelink,%form);
3165: }
1.778 albertel 3166: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3167: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3168: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3169: if (wantarray) {
3170: return ($output, $response);
3171: } else {
3172: return $output;
3173: }
1.8 www 3174: }
3175:
1.15 www 3176: # --------------------------------------------------------- Server Side Include
3177:
1.782 albertel 3178: sub absolute_url {
1.1172.2.145 raeburn 3179: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3180: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3181: if ($host_name eq '') {
3182: $host_name = $ENV{'SERVER_NAME'};
3183: }
1.1172.2.145 raeburn 3184: if ($unalias) {
3185: my $alias = &get_proxy_alias();
3186: if ($alias eq $host_name) {
3187: my $lonhost = $perlvar{'lonHostID'};
3188: my $hostname = &hostname($lonhost);
3189: my $lcproto;
3190: if (($keep_proto) || ($hostname eq '')) {
3191: $lcproto = $protocol;
3192: } else {
3193: $lcproto = $protocol{$lonhost};
3194: $lcproto = 'http' if ($lcproto ne 'https');
3195: $lcproto .= '://';
3196: }
3197: unless ($hostname eq '') {
3198: return $lcproto.$hostname;
3199: }
3200: }
3201: }
1.782 albertel 3202: return $protocol.$host_name;
3203: }
3204:
1.942 foxr 3205: #
3206: # Server side include.
3207: # Parameters:
3208: # fn Possibly encrypted resource name/id.
3209: # form Hash that describes how the rendering should be done
3210: # and other things.
1.944 foxr 3211: # Returns:
1.950 raeburn 3212: # Scalar context: The content of the response.
3213: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3214: #
1.15 www 3215: sub ssi {
3216:
1.944 foxr 3217: my ($fn,%form)=@_;
1.1172.2.145 raeburn 3218: my ($host,$request,$response);
3219: $host = &absolute_url('',1);
1.711 albertel 3220:
3221: $form{'no_update_last_known'}=1;
1.895 albertel 3222: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3223: if (%form) {
1.1172.2.145 raeburn 3224: $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58 raeburn 3225: $request->content(join('&',map {
3226: my $name = escape($_);
3227: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3228: ? join("&$name=", map {escape($_) } @{$form{$_}})
3229: : &escape($form{$_}) );
3230: } keys(%form)));
1.23 www 3231: } else {
1.1172.2.145 raeburn 3232: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3233: }
3234:
1.15 www 3235: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3236:
1.1172.2.101 raeburn 3237: if (($env{'request.course.id'}) &&
3238: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3239: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3240: ($form{'grade_symb'} ne '') &&
3241: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3242: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3243: if (LWP::UserAgent->VERSION >= 5.834) {
3244: my $ua=new LWP::UserAgent;
3245: $ua->local_address('127.0.0.1');
3246: $response = $ua->request($request);
3247: } else {
3248: {
3249: require LWP::Protocol::http;
3250: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3251: my $ua=new LWP::UserAgent;
3252: $response = $ua->request($request);
3253: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3254: }
3255: }
3256: } else {
3257: my $ua=new LWP::UserAgent;
3258: $response = $ua->request($request);
3259: }
1.944 foxr 3260: if (wantarray) {
1.1172.2.3 raeburn 3261: return ($response->content, $response);
1.944 foxr 3262: } else {
1.1172.2.3 raeburn 3263: return $response->content;
1.942 foxr 3264: }
1.324 www 3265: }
3266:
3267: sub externalssi {
3268: my ($url)=@_;
3269: my $ua=new LWP::UserAgent;
3270: my $request=new HTTP::Request('GET',$url);
3271: my $response=$ua->request($request);
1.954 raeburn 3272: if (wantarray) {
3273: return ($response->content, $response);
3274: } else {
3275: return $response->content;
3276: }
1.15 www 3277: }
1.254 www 3278:
1.1172.2.98 raeburn 3279: # If the local copy of a replicated resource is outdated, trigger a
3280: # connection from the homeserver to flush the delayed queue. If no update
3281: # happens, remove local copies of outdated resource (and corresponding
3282: # metadata file).
3283:
3284: sub remove_stale_resfile {
3285: my ($url) = @_;
3286: my $removed;
3287: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3288: my $audom = $1;
3289: my $auname = $2;
3290: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3291: my $homeserver = &homeserver($auname,$audom);
3292: unless (($homeserver eq 'no_host') ||
3293: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3294: my $fname = &filelocation('',$url);
3295: if (-e $fname) {
3296: my $hostname = &hostname($homeserver);
3297: if ($hostname) {
1.1172.2.120 raeburn 3298: my $protocol = $protocol{$homeserver};
3299: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3300: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3301: my $ua=new LWP::UserAgent;
3302: $ua->timeout(5);
1.1172.2.98 raeburn 3303: my $request=new HTTP::Request('HEAD',$uri);
3304: my $response=$ua->request($request);
3305: if ($response->is_success()) {
3306: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3307: my $locmodtime = (stat($fname))[9];
3308: if ($locmodtime < $remmodtime) {
3309: my $stale;
3310: my $answer = &reply('pong',$homeserver);
3311: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3312: sleep(0.2);
3313: $locmodtime = (stat($fname))[9];
3314: if ($locmodtime < $remmodtime) {
3315: my $posstransfer = $fname.'.in.transfer';
3316: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3317: $removed = 1;
3318: } else {
3319: $stale = 1;
3320: }
3321: } else {
3322: $removed = 1;
3323: }
3324: } else {
3325: $stale = 1;
3326: }
3327: if ($stale) {
1.1172.2.124 raeburn 3328: if (unlink($fname)) {
3329: if ($uri!~/\.meta$/) {
3330: if (-e $fname.'.meta') {
3331: unlink($fname.'.meta');
3332: }
3333: }
3334: my $unsubresult = &unsubscribe($fname);
3335: unless ($unsubresult eq 'ok') {
3336: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3337: }
3338: $removed = 1;
1.1172.2.98 raeburn 3339: }
3340: }
3341: }
3342: }
3343: }
3344: }
3345: }
3346: }
3347: }
3348: return $removed;
3349: }
3350:
1.492 albertel 3351: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3352:
3353: sub allowuploaded {
3354: my ($srcurl,$url)=@_;
3355: $url=&clutter(&declutter($url));
3356: my $dir=$url;
3357: $dir=~s/\/[^\/]+$//;
3358: my %httpref=();
3359: my $httpurl=&hreflocation('',$url);
3360: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3361: &Apache::lonnet::appenv(\%httpref);
1.254 www 3362: }
1.477 raeburn 3363:
1.1172.2.13 raeburn 3364: #
3365: # Determine if the current user should be able to edit a particular resource,
3366: # when viewing in course context.
3367: # (a) When viewing resource used to determine if "Edit" item is included in
3368: # Functions.
3369: # (b) When displaying folder contents in course editor, used to determine if
3370: # "Edit" link will be displayed alongside resource.
3371: #
3372: # input: six args -- filename (decluttered), course number, course domain,
3373: # url, symb (if registered) and group (if this is a group
3374: # item -- e.g., bulletin board, group page etc.).
3375: # output: array of five scalars --
3376: # $cfile -- url for file editing if editable on current server
3377: # $home -- homeserver of resource (i.e., for author if published,
3378: # or course if uploaded.).
3379: # $switchserver -- 1 if server switch will be needed.
3380: # $forceedit -- 1 if icon/link should be to go to edit mode
3381: # $forceview -- 1 if icon/link should be to go to view mode
3382: #
3383:
3384: sub can_edit_resource {
3385: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3386: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3387: #
3388: # For aboutme pages user can only edit his/her own.
3389: #
3390: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3391: my ($sdom,$sname) = ($1,$2);
3392: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3393: $home = $env{'user.home'};
3394: $cfile = $resurl;
3395: if ($env{'form.forceedit'}) {
3396: $forceview = 1;
3397: } else {
3398: $forceedit = 1;
3399: }
3400: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3401: } else {
3402: return;
3403: }
3404: }
3405:
3406: if ($env{'request.course.id'}) {
3407: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3408: if ($group ne '') {
3409: # if this is a group homepage or group bulletin board, check group privs
3410: my $allowed = 0;
3411: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3412: if ((&allowed('mdg',$env{'request.course.id'}.
3413: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3414: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3415: $allowed = 1;
3416: }
3417: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3418: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3419: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3420: $allowed = 1;
3421: }
3422: }
3423: if ($allowed) {
3424: $home=&homeserver($cnum,$cdom);
3425: if ($env{'form.forceedit'}) {
3426: $forceview = 1;
3427: } else {
3428: $forceedit = 1;
3429: }
3430: $cfile = $resurl;
3431: } else {
3432: return;
3433: }
3434: } else {
1.1172.2.15 raeburn 3435: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3436: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3437: return;
3438: }
3439: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3440: #
3441: # No edit allowed where CC has switched to student role.
3442: #
3443: return;
3444: }
3445: }
3446: }
3447:
3448: if ($file ne '') {
3449: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3450: if (&is_course_upload($file,$cnum,$cdom)) {
3451: $uploaded = 1;
3452: $incourse = 1;
3453: if ($file =~/\.(htm|html|css|js|txt)$/) {
3454: $cfile = &hreflocation('',$file);
3455: if ($env{'form.forceedit'}) {
3456: $forceview = 1;
3457: } else {
3458: $forceedit = 1;
3459: }
3460: }
3461: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3462: $incourse = 1;
3463: if ($env{'form.forceedit'}) {
3464: $forceview = 1;
3465: } else {
3466: $forceedit = 1;
3467: }
3468: $cfile = $resurl;
3469: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3470: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3471: $incourse = 1;
3472: if ($env{'form.forceedit'}) {
3473: $forceview = 1;
3474: } else {
3475: $forceedit = 1;
3476: }
3477: $cfile = $resurl;
3478: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3479: $incourse = 1;
3480: $cfile = $resurl.'/smpedit';
3481: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3482: $incourse = 1;
3483: if ($env{'form.forceedit'}) {
3484: $forceview = 1;
3485: } else {
3486: $forceedit = 1;
3487: }
3488: $cfile = $resurl;
1.1172.2.122 raeburn 3489: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3490: my ($map,$id,$res) = &decode_symb($symb);
3491: if ($map =~ /\.page$/) {
3492: $incourse = 1;
3493: if ($env{'form.forceedit'}) {
3494: $forceview = 1;
3495: $cfile = $map;
3496: } else {
3497: $forceedit = 1;
3498: $cfile = '/adm/wrapper'.$resurl;
3499: }
3500: }
1.1172.2.15 raeburn 3501: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3502: $incourse = 1;
3503: if ($env{'form.forceedit'}) {
3504: $forceview = 1;
3505: } else {
3506: $forceedit = 1;
3507: }
3508: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3509: }
3510: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3511: my $template = '/res/lib/templates/simpleproblem.problem';
3512: if (&is_on_map($template)) {
3513: $incourse = 1;
3514: $forceview = 1;
3515: $cfile = $template;
3516: }
3517: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3518: $incourse = 1;
3519: if ($env{'form.forceedit'}) {
3520: $forceview = 1;
3521: } else {
3522: $forceedit = 1;
3523: }
3524: $cfile = $resurl;
1.1172.2.13 raeburn 3525: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3526: $incourse = 1;
3527: $forceview = 1;
3528: if ($symb) {
3529: my ($map,$id,$res)=&decode_symb($symb);
3530: $env{'request.symb'} = $symb;
3531: $cfile = &clutter($res);
3532: } else {
3533: $cfile = $env{'form.suppurl'};
3534: $cfile =~ s{^http://}{};
3535: $cfile = '/adm/wrapper/ext/'.$cfile;
3536: }
1.1172.2.31 raeburn 3537: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3538: if ($env{'form.forceedit'}) {
3539: $forceview = 1;
3540: } else {
3541: $forceedit = 1;
3542: }
3543: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3544: }
3545: }
3546: if ($uploaded || $incourse) {
3547: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3548: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3549: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3550: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3551: # Check that the user has permission to edit this resource
3552: my $setpriv = 1;
3553: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3554: if (defined($cfudom)) {
3555: $home=&homeserver($cfuname,$cfudom);
3556: $cfile=$file;
3557: }
3558: }
3559: if (($cfile ne '') && (!$incourse || $uploaded) &&
3560: (($home ne '') && ($home ne 'no_host'))) {
3561: my @ids=¤t_machine_ids();
3562: unless (grep(/^\Q$home\E$/,@ids)) {
3563: $switchserver=1;
3564: }
3565: }
3566: }
3567: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3568: }
3569:
3570: sub is_course_upload {
3571: my ($file,$cnum,$cdom) = @_;
3572: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3573: $uploadpath =~ s{^\/}{};
3574: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3575: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3576: return 1;
3577: }
3578: return;
3579: }
3580:
3581: sub in_course {
3582: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3583: if ($hideprivileged) {
3584: my $skipuser;
1.1172.2.23 raeburn 3585: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3586: my @possdoms = ($cdom);
3587: if ($coursehash{'checkforpriv'}) {
3588: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3589: }
3590: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3591: $skipuser = 1;
3592: if ($coursehash{'nothideprivileged'}) {
3593: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3594: my $user;
3595: if ($item =~ /:/) {
3596: $user = $item;
3597: } else {
3598: $user = join(':',split(/[\@]/,$item));
3599: }
3600: if ($user eq $uname.':'.$udom) {
3601: undef($skipuser);
3602: last;
3603: }
3604: }
3605: }
3606: if ($skipuser) {
3607: return 0;
3608: }
3609: }
3610: }
3611: $type ||= 'any';
3612: if (!defined($cdom) || !defined($cnum)) {
3613: my $cid = $env{'request.course.id'};
3614: $cdom = $env{'course.'.$cid.'.domain'};
3615: $cnum = $env{'course.'.$cid.'.num'};
3616: }
3617: my $typesref;
3618: if (($type eq 'any') || ($type eq 'all')) {
3619: $typesref = ['active','previous','future'];
3620: } elsif ($type eq 'previous' || $type eq 'future') {
3621: $typesref = [$type];
3622: }
3623: my %roles = &get_my_roles($uname,$udom,'userroles',
3624: $typesref,undef,[$cdom]);
3625: my ($tmp) = keys(%roles);
3626: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3627: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3628: if (@course_roles > 0) {
3629: return 1;
3630: }
3631: return 0;
3632: }
3633:
1.478 albertel 3634: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3635: # input: action, courseID, current domain, intended
1.637 raeburn 3636: # path to file, source of file, instruction to parse file for objects,
3637: # ref to hash for embedded objects,
3638: # ref to hash for codebase of java objects.
1.1095 raeburn 3639: # reference to scalar to accommodate mime type determined
3640: # from File::MMagic if $parser = parse.
1.637 raeburn 3641: #
1.485 raeburn 3642: # output: url to file (if action was uploaddoc),
3643: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3644: #
1.478 albertel 3645: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3646: # course.
1.477 raeburn 3647: #
1.478 albertel 3648: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3649: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3650: # course's home server.
1.477 raeburn 3651: #
1.478 albertel 3652: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3653: # be copied from $source (current location) to
3654: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3655: # and will then be copied to
3656: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3657: # course's home server.
1.485 raeburn 3658: #
1.481 raeburn 3659: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3660: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3661: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3662: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3663: # in course's home server.
1.637 raeburn 3664: #
1.477 raeburn 3665:
3666: sub process_coursefile {
1.1095 raeburn 3667: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3668: $mimetype)=@_;
1.477 raeburn 3669: my $fetchresult;
1.638 albertel 3670: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3671: if ($action eq 'propagate') {
1.638 albertel 3672: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3673: $home);
1.481 raeburn 3674: } else {
1.477 raeburn 3675: my $fpath = '';
3676: my $fname = $file;
1.478 albertel 3677: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3678: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3679: my $filepath = &build_filepath($fpath);
1.481 raeburn 3680: if ($action eq 'copy') {
3681: if ($source eq '') {
3682: $fetchresult = 'no source file';
3683: return $fetchresult;
3684: } else {
3685: my $destination = $filepath.'/'.$fname;
3686: rename($source,$destination);
3687: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3688: $home);
1.481 raeburn 3689: }
3690: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3691: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3692: print $fh $env{'form.'.$source};
1.481 raeburn 3693: close($fh);
1.637 raeburn 3694: if ($parser eq 'parse') {
1.1024 raeburn 3695: my $mm = new File::MMagic;
1.1095 raeburn 3696: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3697: if ($type eq 'text/html') {
1.1024 raeburn 3698: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3699: unless ($parse_result eq 'ok') {
3700: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3701: }
1.637 raeburn 3702: }
1.1095 raeburn 3703: if (ref($mimetype)) {
3704: $$mimetype = $type;
3705: }
1.637 raeburn 3706: }
1.477 raeburn 3707: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3708: $home);
1.481 raeburn 3709: if ($fetchresult eq 'ok') {
3710: return '/uploaded/'.$fpath.'/'.$fname;
3711: } else {
3712: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3713: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3714: return '/adm/notfound.html';
3715: }
1.477 raeburn 3716: }
3717: }
1.485 raeburn 3718: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3719: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3720: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3721: }
3722: return $fetchresult;
3723: }
3724:
1.637 raeburn 3725: sub build_filepath {
3726: my ($fpath) = @_;
3727: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3728: unless ($fpath eq '') {
3729: my @parts=split('/',$fpath);
3730: foreach my $part (@parts) {
3731: $filepath.= '/'.$part;
3732: if ((-e $filepath)!=1) {
3733: mkdir($filepath,0777);
3734: }
3735: }
3736: }
3737: return $filepath;
3738: }
3739:
3740: sub store_edited_file {
1.638 albertel 3741: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3742: my $file = $primary_url;
3743: $file =~ s#^/uploaded/$docudom/$docuname/##;
3744: my $fpath = '';
3745: my $fname = $file;
3746: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3747: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3748: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3749: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3750: print $fh $content;
3751: close($fh);
1.638 albertel 3752: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3753: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3754: $home);
1.637 raeburn 3755: if ($$fetchresult eq 'ok') {
3756: return '/uploaded/'.$fpath.'/'.$fname;
3757: } else {
1.638 albertel 3758: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3759: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3760: return '/adm/notfound.html';
3761: }
3762: }
3763:
1.531 albertel 3764: sub clean_filename {
1.831 albertel 3765: my ($fname,$args)=@_;
1.315 www 3766: # Replace Windows backslashes by forward slashes
1.257 www 3767: $fname=~s/\\/\//g;
1.831 albertel 3768: if (!$args->{'keep_path'}) {
3769: # Get rid of everything but the actual filename
3770: $fname=~s/^.*\/([^\/]+)$/$1/;
3771: }
1.315 www 3772: # Replace spaces by underscores
3773: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3774: # Transliterate non-ascii text to ascii
3775: my $lang = &Apache::lonlocal::current_language();
3776: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3777: # Replace all other weird characters by nothing
1.831 albertel 3778: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3779: # Replace all .\d. sequences with _\d. so they no longer look like version
3780: # numbers
3781: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 3782: # Replace three or more adjacent underscores with one for consistency
3783: # with loncfile::filename_check() so complete url can be extracted by
3784: # lonnet::decode_symb()
3785: $fname=~s/_{3,}/_/g;
1.531 albertel 3786: return $fname;
3787: }
1.1172.2.110 raeburn 3788:
1.1051 raeburn 3789: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3790: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3791: # image with the same aspect ratio as the original, but with dimensions which do
3792: # not exceed $resizewidth and $resizeheight.
3793:
1.984 neumanie 3794: sub resizeImage {
1.1051 raeburn 3795: my ($img_path,$resizewidth,$resizeheight) = @_;
3796: my $ima = Image::Magick->new;
3797: my $resized;
3798: if (-e $img_path) {
3799: $ima->Read($img_path);
3800: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3801: my $width = $ima->Get('width');
3802: my $height = $ima->Get('height');
3803: if ($width > $resizewidth) {
3804: my $factor = $width/$resizewidth;
3805: my $newheight = $height/$factor;
3806: $ima->Scale(width=>$resizewidth,height=>$newheight);
3807: $resized = 1;
3808: }
3809: }
3810: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3811: my $width = $ima->Get('width');
3812: my $height = $ima->Get('height');
3813: if ($height > $resizeheight) {
3814: my $factor = $height/$resizeheight;
3815: my $newwidth = $width/$factor;
3816: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3817: $resized = 1;
3818: }
3819: }
3820: if ($resized) {
3821: $ima->Write($img_path);
3822: }
3823: }
3824: return;
1.977 amueller 3825: }
3826:
1.608 albertel 3827: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3828: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3829: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3830: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3831: # canceloverwrite, scantron or ''.
1.1090 raeburn 3832: # if 'coursedoc': upload to the current course
3833: # if 'existingfile': write file to tmp/overwrites directory
3834: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3835: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3836: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3837: # $parser - instruction to parse file for objects ($parser = parse) or
3838: # if context is 'scantron', $parser is hashref of csv column mapping
3839: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3840: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3841: # $allfiles - reference to hash for embedded objects
3842: # $codebase - reference to hash for codebase of java objects
3843: # $desuname - username for permanent storage of uploaded file
3844: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3845: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3846: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3847: # $resizewidth - width (pixels) to which to resize uploaded image
3848: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3849: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3850: # from File::MMagic.
1.858 raeburn 3851: #
1.686 albertel 3852: # output: url of file in userspace, or error: <message>
3853: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3854:
1.531 albertel 3855: sub userfileupload {
1.1090 raeburn 3856: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3857: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3858: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3859: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3860: $fname=&clean_filename($fname);
1.1090 raeburn 3861: # See if there is anything left
1.257 www 3862: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3863: # If filename now begins with a . prepend unix timestamp _ milliseconds
3864: if ($fname =~ /^\./) {
3865: my ($s,$usec) = &gettimeofday();
3866: while (length($usec) < 6) {
3867: $usec = '0'.$usec;
3868: }
3869: $fname = $s.'_'.substr($usec,0,3).$fname;
3870: }
1.1090 raeburn 3871: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3872: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3873: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3874: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3875: my $now = time;
1.1090 raeburn 3876: my $filepath;
1.1095 raeburn 3877: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3878: $filepath = 'tmp/helprequests/'.$now;
3879: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3880: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3881: '_'.$env{'user.domain'}.'/pending';
3882: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3883: my ($docuname,$docudom);
1.1172.2.96 raeburn 3884: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3885: $docudom = $destudom;
3886: } else {
3887: $docudom = $env{'user.domain'};
3888: }
1.1172.2.96 raeburn 3889: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3890: $docuname = $destuname;
3891: } else {
3892: $docuname = $env{'user.name'};
3893: }
3894: if (exists($env{'form.group'})) {
3895: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3896: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3897: }
3898: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3899: if ($context eq 'canceloverwrite') {
3900: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3901: if (-e $tempfile) {
3902: my @info = stat($tempfile);
3903: if ($info[9] eq $env{'form.timestamp'}) {
3904: unlink($tempfile);
3905: }
3906: }
3907: return;
1.523 raeburn 3908: }
3909: }
1.1090 raeburn 3910: # Create the directory if not present
1.741 raeburn 3911: my @parts=split(/\//,$filepath);
3912: my $fullpath = $perlvar{'lonDaemons'};
3913: for (my $i=0;$i<@parts;$i++) {
3914: $fullpath .= '/'.$parts[$i];
3915: if ((-e $fullpath)!=1) {
3916: mkdir($fullpath,0777);
3917: }
3918: }
1.1172.2.96 raeburn 3919: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3920: print $fh $env{'form.'.$formname};
3921: close($fh);
1.1090 raeburn 3922: if ($context eq 'existingfile') {
3923: my @info = stat($fullpath.'/'.$fname);
3924: return ($fullpath.'/'.$fname,$info[9]);
3925: } else {
3926: return $fullpath.'/'.$fname;
3927: }
1.523 raeburn 3928: }
1.995 raeburn 3929: if ($subdir eq 'scantron') {
3930: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3931: } else {
1.995 raeburn 3932: $fname="$subdir/$fname";
3933: }
1.1090 raeburn 3934: if ($context eq 'coursedoc') {
1.638 albertel 3935: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3936: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3937: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3938: return &finishuserfileupload($docuname,$docudom,
3939: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3940: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3941: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3942: } else {
1.1172.2.21 raeburn 3943: if ($env{'form.folder'}) {
3944: $fname=$env{'form.folder'}.'/'.$fname;
3945: }
1.638 albertel 3946: return &process_coursefile('uploaddoc',$docuname,$docudom,
3947: $fname,$formname,$parser,
1.1095 raeburn 3948: $allfiles,$codebase,$mimetype);
1.481 raeburn 3949: }
1.719 banghart 3950: } elsif (defined($destuname)) {
3951: my $docuname=$destuname;
3952: my $docudom=$destudom;
1.860 raeburn 3953: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3954: $parser,$allfiles,$codebase,
1.1051 raeburn 3955: $thumbwidth,$thumbheight,
1.1095 raeburn 3956: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3957: } else {
1.638 albertel 3958: my $docuname=$env{'user.name'};
3959: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3960: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3961: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3962: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3963: }
1.860 raeburn 3964: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3965: $parser,$allfiles,$codebase,
1.1051 raeburn 3966: $thumbwidth,$thumbheight,
1.1095 raeburn 3967: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3968: }
1.271 www 3969: }
3970:
3971: sub finishuserfileupload {
1.860 raeburn 3972: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3973: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3974: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3975: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3976:
1.860 raeburn 3977: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3978: $file=$fname;
3979: if ($fname=~m|/|) {
3980: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3981: $path.=$fnamepath.'/';
3982: }
1.259 www 3983: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3984: my $count;
3985: for ($count=4;$count<=$#parts;$count++) {
3986: $filepath.="/$parts[$count]";
3987: if ((-e $filepath)!=1) {
3988: mkdir($filepath,0777);
3989: }
3990: }
1.984 neumanie 3991:
1.258 www 3992: # Save the file
3993: {
1.1172.2.96 raeburn 3994: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3995: &logthis('Failed to create '.$filepath.'/'.$file);
3996: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3997: return '/adm/notfound.html';
3998: }
1.1090 raeburn 3999: if ($context eq 'overwrite') {
1.1117 foxr 4000: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4001: my $target = $filepath.'/'.$file;
4002: if (-e $source) {
4003: my @info = stat($source);
4004: if ($info[9] eq $env{'form.timestamp'}) {
4005: unless (&File::Copy::move($source,$target)) {
4006: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4007: return "Moving from $source failed";
4008: }
4009: } else {
4010: return "Temporary file: $source had unexpected date/time for last modification";
4011: }
4012: } else {
4013: return "Temporary file: $source missing";
4014: }
4015: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4016: &logthis('Failed to write to '.$filepath.'/'.$file);
4017: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4018: return '/adm/notfound.html';
4019: }
1.570 albertel 4020: close(FH);
1.1051 raeburn 4021: if ($resizewidth && $resizeheight) {
4022: my $mm = new File::MMagic;
4023: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4024: if ($mime_type =~ m{^image/}) {
4025: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4026: }
1.977 amueller 4027: }
1.258 www 4028: }
1.1152 raeburn 4029: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4030: if (ref($mimetype)) {
4031: if ($$mimetype eq '') {
4032: my $mm = new File::MMagic;
4033: my $type = $mm->checktype_filename($filepath.'/'.$file);
4034: $$mimetype = $type;
4035: }
4036: }
4037: }
1.1172.2.109 raeburn 4038: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4039: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4040: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4041: $allfiles,$codebase);
4042: unless ($parse_result eq 'ok') {
4043: &logthis('Failed to parse '.$filepath.$file.
4044: ' for embedded media: '.$parse_result);
4045: }
1.637 raeburn 4046: }
1.1172.2.109 raeburn 4047: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4048: my $format = $env{'form.scantron_format'};
4049: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4050: }
1.860 raeburn 4051: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4052: my $input = $filepath.'/'.$file;
4053: my $output = $filepath.'/'.'tn-'.$file;
4054: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4055: my @args = ('convert','-sample',$thumbsize,$input,$output);
4056: system({$args[0]} @args);
1.860 raeburn 4057: if (-e $filepath.'/'.'tn-'.$file) {
4058: $fetchthumb = 1;
4059: }
4060: }
1.858 raeburn 4061:
1.259 www 4062: # Notify homeserver to grep it
4063: #
1.984 neumanie 4064: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4065: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4066: if ($fetchresult eq 'ok') {
1.860 raeburn 4067: if ($fetchthumb) {
4068: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4069: if ($thumbresult ne 'ok') {
4070: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4071: $docuhome.': '.$thumbresult);
4072: }
4073: }
1.259 www 4074: #
1.258 www 4075: # Return the URL to it
1.494 albertel 4076: return '/uploaded/'.$path.$file;
1.263 www 4077: } else {
1.494 albertel 4078: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4079: ': '.$fetchresult);
1.263 www 4080: return '/adm/notfound.html';
1.858 raeburn 4081: }
1.493 albertel 4082: }
4083:
1.637 raeburn 4084: sub extract_embedded_items {
1.961 raeburn 4085: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4086: my @state = ();
1.1164 raeburn 4087: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4088: my %javafiles = (
4089: codebase => '',
4090: code => '',
4091: archive => ''
4092: );
4093: my %mediafiles = (
4094: src => '',
4095: movie => '',
4096: );
1.648 raeburn 4097: my $p;
4098: if ($content) {
4099: $p = HTML::LCParser->new($content);
4100: } else {
1.961 raeburn 4101: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4102: }
1.641 albertel 4103: while (my $t=$p->get_token()) {
1.640 albertel 4104: if ($t->[0] eq 'S') {
4105: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4106: push(@state, $tagname);
1.648 raeburn 4107: if (lc($tagname) eq 'allow') {
4108: &add_filetype($allfiles,$attr->{'src'},'src');
4109: }
1.640 albertel 4110: if (lc($tagname) eq 'img') {
4111: &add_filetype($allfiles,$attr->{'src'},'src');
4112: }
1.886 albertel 4113: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4114: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4115: &add_filetype($allfiles,$attr->{'href'},'href');
4116: }
1.886 albertel 4117: }
1.645 raeburn 4118: if (lc($tagname) eq 'script') {
1.1164 raeburn 4119: my $src;
1.645 raeburn 4120: if ($attr->{'archive'} =~ /\.jar$/i) {
4121: &add_filetype($allfiles,$attr->{'archive'},'archive');
4122: } else {
1.1164 raeburn 4123: if ($attr->{'src'} ne '') {
4124: $src = $attr->{'src'};
4125: &add_filetype($allfiles,$src,'src');
4126: }
4127: }
4128: my $text = $p->get_trimmed_text();
4129: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4130: my @swfargs = split(/,/,$1);
4131: foreach my $item (@swfargs) {
4132: $item =~ s/["']//g;
4133: $item =~ s/^\s+//;
4134: $item =~ s/\s+$//;
4135: }
4136: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4137: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4138: push(@{$related{$swfargs[0]}},$swfargs[2]);
4139: } else {
4140: $related{$swfargs[0]} = [$swfargs[2]];
4141: }
4142: }
1.645 raeburn 4143: }
4144: }
4145: if (lc($tagname) eq 'link') {
4146: if (lc($attr->{'rel'}) eq 'stylesheet') {
4147: &add_filetype($allfiles,$attr->{'href'},'href');
4148: }
4149: }
1.640 albertel 4150: if (lc($tagname) eq 'object' ||
4151: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4152: foreach my $item (keys(%javafiles)) {
4153: $javafiles{$item} = '';
4154: }
1.1164 raeburn 4155: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4156: $lastids{lc($tagname)} = $attr->{'id'};
4157: }
1.640 albertel 4158: }
4159: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4160: my $name = lc($attr->{'name'});
4161: foreach my $item (keys(%javafiles)) {
4162: if ($name eq $item) {
4163: $javafiles{$item} = $attr->{'value'};
4164: last;
4165: }
4166: }
1.1164 raeburn 4167: my $pathfrom;
1.640 albertel 4168: foreach my $item (keys(%mediafiles)) {
4169: if ($name eq $item) {
1.1164 raeburn 4170: $pathfrom = $attr->{'value'};
4171: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4172: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4173: last;
4174: }
4175: }
1.1164 raeburn 4176: if ($name eq 'flashvars') {
4177: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4178: }
4179: if ($pathfrom ne '') {
4180: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4181: $pathfrom);
4182: }
1.640 albertel 4183: }
4184: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4185: foreach my $item (keys(%javafiles)) {
4186: if ($attr->{$item}) {
4187: $javafiles{$item} = $attr->{$item};
4188: last;
4189: }
4190: }
4191: foreach my $item (keys(%mediafiles)) {
4192: if ($attr->{$item}) {
4193: &add_filetype($allfiles,$attr->{$item},$item);
4194: last;
4195: }
4196: }
1.1164 raeburn 4197: if (lc($tagname) eq 'embed') {
4198: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4199: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4200: $attr->{'src'});
4201: }
4202: }
1.640 albertel 4203: }
1.1172.2.35 raeburn 4204: if (lc($tagname) eq 'iframe') {
4205: my $src = $attr->{'src'} ;
4206: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4207: &add_filetype($allfiles,$src,'src');
4208: } elsif ($src =~ m{^/}) {
4209: if ($env{'request.course.id'}) {
4210: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4211: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4212: my $url = &hreflocation('',$fullpath);
4213: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4214: my $relpath = $1;
4215: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4216: &add_filetype($allfiles,$1,'src');
4217: }
4218: }
4219: }
4220: }
4221: }
1.1164 raeburn 4222: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4223: pop(@state);
1.1164 raeburn 4224: }
1.640 albertel 4225: } elsif ($t->[0] eq 'E') {
4226: my ($tagname) = ($t->[1]);
4227: if ($javafiles{'codebase'} ne '') {
4228: $javafiles{'codebase'} .= '/';
4229: }
4230: if (lc($tagname) eq 'applet' ||
4231: lc($tagname) eq 'object' ||
4232: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4233: ) {
4234: foreach my $item (keys(%javafiles)) {
4235: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4236: my $file=$javafiles{'codebase'}.$javafiles{$item};
4237: &add_filetype($allfiles,$file,$item);
4238: }
4239: }
4240: }
4241: pop @state;
4242: }
4243: }
1.1164 raeburn 4244: foreach my $id (sort(keys(%flashvars))) {
4245: if ($shockwave{$id} ne '') {
4246: my @pairs = split(/\&/,$flashvars{$id});
4247: foreach my $pair (@pairs) {
4248: my ($key,$value) = split(/\=/,$pair);
4249: if ($key eq 'thumb') {
4250: &add_filetype($allfiles,$value,$key);
4251: } elsif ($key eq 'content') {
4252: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4253: my ($ext) = ($value =~ /\.([^.]+)$/);
4254: if ($ext ne '') {
4255: &add_filetype($allfiles,$path.$value,$ext);
4256: }
4257: }
4258: }
4259: }
4260: }
1.637 raeburn 4261: return 'ok';
4262: }
4263:
1.639 albertel 4264: sub add_filetype {
4265: my ($allfiles,$file,$type)=@_;
4266: if (exists($allfiles->{$file})) {
4267: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4268: push(@{$allfiles->{$file}}, &escape($type));
4269: }
4270: } else {
4271: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4272: }
4273: }
4274:
1.1164 raeburn 4275: sub embedded_dependency {
4276: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4277: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4278: if (($identifier ne '') &&
4279: (ref($related->{$identifier}) eq 'ARRAY') &&
4280: ($pathfrom ne '')) {
4281: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4282: foreach my $dep (@{$related->{$identifier}}) {
4283: &add_filetype($allfiles,$path.$dep,'object');
4284: }
4285: }
4286: }
4287: return;
4288: }
4289:
1.1172.2.109 raeburn 4290: sub bubblesheet_converter {
4291: my ($cdom,$fullpath,$config,$format) = @_;
4292: if ((&domain($cdom) ne '') &&
4293: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4294: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4295: my (%csvcols,%csvoptions);
4296: if (ref($config->{'fields'}) eq 'HASH') {
4297: %csvcols = %{$config->{'fields'}};
4298: }
4299: if (ref($config->{'options'}) eq 'HASH') {
4300: %csvoptions = %{$config->{'options'}};
4301: }
4302: my %csvbynum = reverse(%csvcols);
4303: my %scantronconf = &get_scantron_config($format,$cdom);
4304: if (keys(%scantronconf)) {
4305: my %bynum = (
4306: $scantronconf{CODEstart} => 'CODEstart',
4307: $scantronconf{IDstart} => 'IDstart',
4308: $scantronconf{PaperID} => 'PaperID',
4309: $scantronconf{FirstName} => 'FirstName',
4310: $scantronconf{LastName} => 'LastName',
4311: $scantronconf{Qstart} => 'Qstart',
4312: );
4313: my @ordered;
4314: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4315: push(@ordered,$bynum{$item});
4316: }
4317: my %mapstart = (
4318: CODEstart => 'CODE',
4319: IDstart => 'ID',
4320: PaperID => 'PaperID',
4321: FirstName => 'FirstName',
4322: LastName => 'LastName',
4323: Qstart => 'FirstQuestion',
4324: );
4325: my %maplength = (
4326: CODEstart => 'CODElength',
4327: IDstart => 'IDlength',
4328: PaperID => 'PaperIDlength',
4329: FirstName => 'FirstNamelength',
4330: LastName => 'LastNamelength',
4331: );
4332: if (open(my $fh,'<',$fullpath)) {
4333: my $output;
4334: my %lettdig = &letter_to_digits();
4335: my %diglett = reverse(%lettdig);
4336: my $numletts = scalar(keys(%lettdig));
4337: my $num = 0;
4338: while (my $line=<$fh>) {
4339: $num ++;
4340: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4341: $line =~ s{[\r\n]+$}{};
4342: my %found;
1.1172.2.143 raeburn 4343: my @values = split(/,/,$line,-1);
1.1172.2.109 raeburn 4344: my ($qstart,$record);
4345: for (my $i=0; $i<@values; $i++) {
4346: if ((($qstart ne '') && ($i > $qstart)) ||
4347: ($csvbynum{$i} eq 'FirstQuestion')) {
4348: if ($values[$i] eq '') {
4349: $values[$i] = $scantronconf{'Qoff'};
4350: } elsif ($scantronconf{'Qon'} eq 'number') {
4351: if ($values[$i] =~ /^[A-Ja-j]$/) {
4352: $values[$i] = $lettdig{uc($values[$i])};
4353: }
4354: } elsif ($scantronconf{'Qon'} eq 'letter') {
4355: if ($values[$i] =~ /^[0-9]$/) {
4356: $values[$i] = $diglett{$values[$i]};
4357: }
4358: } else {
4359: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4360: my $digit;
4361: if ($values[$i] =~ /^[A-Ja-j]$/) {
4362: $digit = $lettdig{uc($values[$i])}-1;
4363: if ($values[$i] eq 'J') {
4364: $digit += $numletts;
4365: }
4366: } elsif ($values[$i] =~ /^[0-9]$/) {
4367: $digit = $values[$i]-1;
4368: if ($values[$i] eq '0') {
4369: $digit += $numletts;
4370: }
4371: }
4372: my $qval='';
4373: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4374: if ($j == $digit) {
4375: $qval .= $scantronconf{'Qon'};
4376: } else {
4377: $qval .= $scantronconf{'Qoff'};
4378: }
4379: }
4380: $values[$i] = $qval;
4381: }
4382: }
4383: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4384: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4385: }
4386: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4387: if ($numblank > 0) {
4388: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4389: }
4390: if ($csvbynum{$i} eq 'FirstQuestion') {
4391: $qstart = $i;
4392: $found{$csvbynum{$i}} = $values[$i];
4393: } else {
4394: $found{'FirstQuestion'} .= $values[$i];
4395: }
4396: } elsif (exists($csvbynum{$i})) {
4397: if ($csvoptions{'rem'}) {
4398: $values[$i] =~ s/^\s+//;
4399: }
4400: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4401: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4402: $values[$i] = '0'.$values[$i];
4403: }
4404: }
4405: $found{$csvbynum{$i}} = $values[$i];
4406: }
4407: }
4408: foreach my $item (@ordered) {
4409: my $currlength = 1+length($record);
4410: my $numspaces = $scantronconf{$item} - $currlength;
4411: if ($numspaces > 0) {
4412: $record .= (' ' x $numspaces);
4413: }
4414: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4415: unless ($item eq 'Qstart') {
4416: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4417: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4418: }
4419: }
4420: $record .= $found{$mapstart{$item}};
4421: }
4422: }
4423: $output .= "$record\n";
4424: }
4425: close($fh);
4426: if ($output) {
4427: if (open(my $fh,'>',$fullpath)) {
4428: print $fh $output;
4429: close($fh);
4430: }
4431: }
4432: }
4433: }
4434: return;
4435: }
4436: }
4437:
4438: sub letter_to_digits {
4439: my %lettdig = (
4440: A => 1,
4441: B => 2,
4442: C => 3,
4443: D => 4,
4444: E => 5,
4445: F => 6,
4446: G => 7,
4447: H => 8,
4448: I => 9,
4449: J => 0,
4450: );
4451: return %lettdig;
4452: }
4453:
4454: sub get_scantron_config {
4455: my ($which,$cdom) = @_;
4456: my @lines = &get_scantronformat_file($cdom);
4457: my %config;
4458: #FIXME probably should move to XML it has already gotten a bit much now
4459: foreach my $line (@lines) {
4460: my ($name,$descrip)=split(/:/,$line);
4461: if ($name ne $which ) { next; }
4462: chomp($line);
4463: my @config=split(/:/,$line);
4464: $config{'name'}=$config[0];
4465: $config{'description'}=$config[1];
4466: $config{'CODElocation'}=$config[2];
4467: $config{'CODEstart'}=$config[3];
4468: $config{'CODElength'}=$config[4];
4469: $config{'IDstart'}=$config[5];
4470: $config{'IDlength'}=$config[6];
4471: $config{'Qstart'}=$config[7];
4472: $config{'Qlength'}=$config[8];
4473: $config{'Qoff'}=$config[9];
4474: $config{'Qon'}=$config[10];
4475: $config{'PaperID'}=$config[11];
4476: $config{'PaperIDlength'}=$config[12];
4477: $config{'FirstName'}=$config[13];
4478: $config{'FirstNamelength'}=$config[14];
4479: $config{'LastName'}=$config[15];
4480: $config{'LastNamelength'}=$config[16];
4481: $config{'BubblesPerRow'}=$config[17];
4482: last;
4483: }
4484: return %config;
4485: }
4486:
4487: sub get_scantronformat_file {
4488: my ($cdom) = @_;
4489: if ($cdom eq '') {
4490: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4491: }
4492: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4493: my $gottab = 0;
4494: my @lines;
4495: if (ref($domconfig{'scantron'}) eq 'HASH') {
4496: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4497: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4498: if ($formatfile ne '-1') {
4499: @lines = split("\n",$formatfile,-1);
4500: $gottab = 1;
4501: }
4502: }
4503: }
4504: if (!$gottab) {
4505: my $confname = $cdom.'-domainconfig';
4506: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4507: my $formatfile = &getfile($default);
4508: if ($formatfile ne '-1') {
4509: @lines = split("\n",$formatfile,-1);
4510: $gottab = 1;
4511: }
4512: }
4513: if (!$gottab) {
4514: my @domains = ¤t_machine_domains();
4515: if (grep(/^\Q$cdom\E$/,@domains)) {
4516: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4517: @lines = <$fh>;
4518: close($fh);
4519: }
4520: } else {
4521: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4522: @lines = <$fh>;
4523: close($fh);
4524: }
4525: }
4526: }
4527: return @lines;
4528: }
4529:
1.493 albertel 4530: sub removeuploadedurl {
1.984 neumanie 4531: my ($url)=@_;
4532: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4533: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4534: }
4535:
4536: sub removeuserfile {
4537: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4538: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4539: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4540: if ($result eq 'ok') {
1.798 raeburn 4541: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4542: my $metafile = $fname.'.meta';
4543: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4544: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4545: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4546: my $sqlresult =
1.823 albertel 4547: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4548: 'portfolio_metadata',$group,
4549: 'delete');
1.798 raeburn 4550: }
4551: }
4552: return $result;
1.257 www 4553: }
1.15 www 4554:
1.530 albertel 4555: sub mkdiruserfile {
4556: my ($docuname,$docudom,$dir)=@_;
4557: my $home=&homeserver($docuname,$docudom);
4558: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4559: }
4560:
1.531 albertel 4561: sub renameuserfile {
4562: my ($docuname,$docudom,$old,$new)=@_;
4563: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4564: my $result = &reply("renameuserfile:$docudom:$docuname:".
4565: &escape("$old").':'.&escape("$new"),$home);
4566: if ($result eq 'ok') {
4567: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4568: my $oldmeta = $old.'.meta';
4569: my $newmeta = $new.'.meta';
4570: my $metaresult =
4571: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4572: my $url = "/uploaded/$docudom/$docuname/$old";
4573: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4574: my $sqlresult =
1.823 albertel 4575: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4576: 'portfolio_metadata',$group,
4577: 'delete');
1.798 raeburn 4578: }
4579: }
4580: return $result;
1.531 albertel 4581: }
4582:
1.14 www 4583: # ------------------------------------------------------------------------- Log
4584:
4585: sub log {
4586: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4587: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4588: }
4589:
4590: # ------------------------------------------------------------------ Course Log
1.352 www 4591: #
4592: # This routine flushes several buffers of non-mission-critical nature
4593: #
1.157 www 4594:
4595: sub flushcourselogs {
1.352 www 4596: &logthis('Flushing log buffers');
4597: #
4598: # course logs
4599: # This is a log of all transactions in a course, which can be used
4600: # for data mining purposes
4601: #
4602: # It also collects the courseid database, which lists last transaction
4603: # times and course titles for all courseids
4604: #
4605: my %courseidbuffer=();
1.921 raeburn 4606: foreach my $crsid (keys(%courselogs)) {
1.352 www 4607: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4608: &escape($courselogs{$crsid}),
4609: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4610: delete $courselogs{$crsid};
4611: } else {
4612: &logthis('Failed to flush log buffer for '.$crsid);
4613: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4614: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4615: " exceeded maximum size, deleting.</font>");
4616: delete $courselogs{$crsid};
4617: }
1.352 www 4618: }
1.920 raeburn 4619: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4620: 'description' => $coursedescrbuf{$crsid},
4621: 'inst_code' => $courseinstcodebuf{$crsid},
4622: 'type' => $coursetypebuf{$crsid},
4623: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4624: };
1.191 harris41 4625: }
1.352 www 4626: #
4627: # Write course id database (reverse lookup) to homeserver of courses
4628: # Is used in pickcourse
4629: #
1.840 albertel 4630: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4631: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4632: $courseidbuffer{$crs_home},
4633: $crs_home,'timeonly');
1.352 www 4634: }
4635: #
4636: # File accesses
4637: # Writes to the dynamic metadata of resources to get hit counts, etc.
4638: #
1.449 matthew 4639: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4640: if ($entry =~ /___count$/) {
4641: my ($dom,$name);
1.807 albertel 4642: ($dom,$name,undef)=
1.811 albertel 4643: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4644: if (! defined($dom) || $dom eq '' ||
4645: ! defined($name) || $name eq '') {
1.620 albertel 4646: my $cid = $env{'request.course.id'};
1.1172.2.142 raeburn 4647: #
4648: # FIXME 11/29/2021
4649: # Typo in rev. 1.458 (2003/12/09)??
4650: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
4651: #
4652: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
4653: # $dom and $name will always be null, so the &inc() call will default to storing this data
4654: # in a nohist_accesscount.db file for the user rather than the course.
4655: #
4656: # That said there is a lot of noise in the data being stored.
4657: # So counts for prtspool/ and adm/ etc. are recorded.
4658: #
4659: # A review of which items ending '___count' are written to %accesshash should likely be
4660: # made before deciding whether to set these to 'course.' instead of 'request.'
4661: #
4662: # Under the current scheme each user receives a nohist_accesscount.db file listing
4663: # accesses for things which are not published resources, regardless of course, and
4664: # there is not a nohist_accesscount.db file in a course, which might log accesses from
4665: # anyone in the course for things which are not published resources.
4666: #
4667: # For an author, nohist_accesscount.db ends up having records for other items
4668: # mixed up with the legitimate access counts for the author's published resources.
4669: #
1.620 albertel 4670: $dom = $env{'request.'.$cid.'.domain'};
4671: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4672: }
1.450 matthew 4673: my $value = $accesshash{$entry};
4674: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4675: my %temphash=($url => $value);
1.449 matthew 4676: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4677: if ($result eq 'ok') {
4678: delete $accesshash{$entry};
4679: }
4680: } else {
1.811 albertel 4681: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4682: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4683: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4684: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4685: delete $accesshash{$entry};
4686: }
1.185 www 4687: }
1.191 harris41 4688: }
1.352 www 4689: #
4690: # Roles
4691: # Reverse lookup of user roles for course faculty/staff and co-authorship
4692: #
1.800 albertel 4693: foreach my $entry (keys(%userrolehash)) {
1.351 www 4694: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4695: split(/\:/,$entry);
4696: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4697: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4698: $rudom,$runame) eq 'ok') {
4699: delete $userrolehash{$entry};
4700: }
4701: }
1.662 raeburn 4702: #
1.1172.2.90 raeburn 4703: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4704: #
4705: my %domrolebuffer = ();
1.1000 raeburn 4706: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4707: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4708: if ($domrolebuffer{$rudom}) {
4709: $domrolebuffer{$rudom}.='&'.&escape($entry).
4710: '='.&escape($domainrolehash{$entry});
4711: } else {
4712: $domrolebuffer{$rudom}.=&escape($entry).
4713: '='.&escape($domainrolehash{$entry});
4714: }
4715: delete $domainrolehash{$entry};
4716: }
4717: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4718: my %servers;
4719: if (defined(&domain($dom,'primary'))) {
4720: my $primary=&domain($dom,'primary');
4721: my $hostname=&hostname($primary);
4722: $servers{$primary} = $hostname;
4723: } else {
4724: %servers = &get_servers($dom,'library');
4725: }
1.841 albertel 4726: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4727: if (&reply('domroleput:'.$dom.':'.
4728: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4729: last;
4730: } else {
1.841 albertel 4731: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4732: }
1.662 raeburn 4733: }
4734: }
1.186 www 4735: $dumpcount++;
1.157 www 4736: }
4737:
4738: sub courselog {
4739: my $what=shift;
1.158 www 4740: $what=time.':'.$what;
1.620 albertel 4741: unless ($env{'request.course.id'}) { return ''; }
4742: $coursedombuf{$env{'request.course.id'}}=
4743: $env{'course.'.$env{'request.course.id'}.'.domain'};
4744: $coursenumbuf{$env{'request.course.id'}}=
4745: $env{'course.'.$env{'request.course.id'}.'.num'};
4746: $coursehombuf{$env{'request.course.id'}}=
4747: $env{'course.'.$env{'request.course.id'}.'.home'};
4748: $coursedescrbuf{$env{'request.course.id'}}=
4749: $env{'course.'.$env{'request.course.id'}.'.description'};
4750: $courseinstcodebuf{$env{'request.course.id'}}=
4751: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4752: $courseownerbuf{$env{'request.course.id'}}=
4753: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4754: $coursetypebuf{$env{'request.course.id'}}=
4755: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4756: if (defined $courselogs{$env{'request.course.id'}}) {
4757: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4758: } else {
1.620 albertel 4759: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4760: }
1.620 albertel 4761: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4762: &flushcourselogs();
4763: }
1.158 www 4764: }
4765:
4766: sub courseacclog {
4767: my $fnsymb=shift;
1.620 albertel 4768: unless ($env{'request.course.id'}) { return ''; }
4769: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4770: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4771: $what.=':POST';
1.583 matthew 4772: # FIXME: Probably ought to escape things....
1.800 albertel 4773: foreach my $key (keys(%env)) {
4774: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4775: my $formitem = $1;
4776: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4777: $what.=':'.$formitem.'='.$env{$key};
4778: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4779: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4780: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4781: } else {
4782: $what.=':'.$formitem.'='.$env{$key};
4783: }
1.975 raeburn 4784: }
1.158 www 4785: }
1.191 harris41 4786: }
1.583 matthew 4787: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4788: # FIXME: We should not be depending on a form parameter that someone
4789: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4790: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4791: $what.= ':POST';
4792: # FIXME: Probably ought to escape things....
4793: foreach my $element ('courseexp','crsfulltext','crsrelated',
4794: 'crsdiscuss') {
1.620 albertel 4795: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4796: }
4797: }
1.158 www 4798: }
4799: &courselog($what);
1.149 www 4800: }
4801:
1.185 www 4802: sub countacc {
4803: my $url=&declutter(shift);
1.458 matthew 4804: return if (! defined($url) || $url eq '');
1.620 albertel 4805: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4806: #
4807: # Mark that this url was used in this course
4808: #
1.620 albertel 4809: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4810: #
4811: # Increase the access count for this resource in this child process
4812: #
1.281 www 4813: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4814: $accesshash{$key}++;
1.185 www 4815: }
1.349 www 4816:
1.361 www 4817: sub linklog {
4818: my ($from,$to)=@_;
4819: $from=&declutter($from);
4820: $to=&declutter($to);
4821: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4822: $accesshash{$to.'___'.$from.'___goto'}=1;
4823: }
1.1160 www 4824:
4825: sub statslog {
4826: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4827: if ($users<2) { return; }
4828: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4829: 'course' => $env{'request.course.id'},
4830: 'sections' => '"all"',
4831: 'num_students' => $users,
4832: 'part' => $part,
4833: 'symb' => $symb,
4834: 'mean_tries' => $av_attempts,
4835: 'deg_of_diff' => $degdiff});
4836: foreach my $key (keys(%dynstore)) {
4837: $accesshash{$key}=$dynstore{$key};
4838: }
4839: }
1.361 www 4840:
1.349 www 4841: sub userrolelog {
4842: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4843: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4844: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4845: $userrolehash
4846: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4847: =$tend.':'.$tstart;
1.662 raeburn 4848: }
1.1169 droeschl 4849: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4850: $userrolehash
4851: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4852: =$tend.':'.$tstart;
4853: }
1.1172.2.90 raeburn 4854: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4855: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4856: $domainrolehash
4857: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4858: = $tend.':'.$tstart;
4859: }
1.351 www 4860: }
4861:
1.957 raeburn 4862: sub courserolelog {
4863: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4864: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4865: my $cdom = $1;
4866: my $cnum = $2;
4867: my $sec = $3;
4868: my $namespace = 'rolelog';
4869: my %storehash = (
4870: role => $trole,
4871: start => $tstart,
4872: end => $tend,
4873: selfenroll => $selfenroll,
4874: context => $context,
4875: );
4876: if ($trole eq 'gr') {
4877: $namespace = 'groupslog';
4878: $storehash{'group'} = $sec;
4879: } else {
4880: $storehash{'section'} = $sec;
4881: }
4882: &write_log('course',$namespace,\%storehash,$delflag,$username,
4883: $domain,$cnum,$cdom);
4884: if (($trole ne 'st') || ($sec ne '')) {
4885: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4886: }
4887: }
4888: return;
4889: }
4890:
1.1172.2.9 raeburn 4891: sub domainrolelog {
4892: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4893: if ($area =~ m{^/($match_domain)/$}) {
4894: my $cdom = $1;
4895: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4896: my $namespace = 'rolelog';
4897: my %storehash = (
4898: role => $trole,
4899: start => $tstart,
4900: end => $tend,
4901: context => $context,
4902: );
4903: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4904: $domain,$domconfiguser,$cdom);
4905: }
4906: return;
4907:
4908: }
4909:
4910: sub coauthorrolelog {
4911: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4912: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4913: my $audom = $1;
4914: my $auname = $2;
4915: my $namespace = 'rolelog';
4916: my %storehash = (
4917: role => $trole,
4918: start => $tstart,
4919: end => $tend,
4920: context => $context,
4921: );
4922: &write_log('author',$namespace,\%storehash,$delflag,$username,
4923: $domain,$auname,$audom);
4924: }
4925: return;
4926: }
4927:
1.351 www 4928: sub get_course_adv_roles {
1.948 raeburn 4929: my ($cid,$codes) = @_;
1.620 albertel 4930: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4931: my %coursehash=&coursedescription($cid);
1.988 raeburn 4932: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4933: my %nothide=();
1.800 albertel 4934: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4935: if ($user !~ /:/) {
4936: $nothide{join(':',split(/[\@]/,$user))}=1;
4937: } else {
4938: $nothide{$user}=1;
4939: }
1.470 www 4940: }
1.1172.2.23 raeburn 4941: my @possdoms = ($coursehash{'domain'});
4942: if ($coursehash{'checkforpriv'}) {
4943: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4944: }
1.351 www 4945: my %returnhash=();
4946: my %dumphash=
4947: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4948: my $now=time;
1.997 raeburn 4949: my %privileged;
1.1000 raeburn 4950: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4951: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4952: if (($tstart) && ($tstart<0)) { next; }
4953: if (($tend) && ($tend<$now)) { next; }
4954: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4955: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4956: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4957: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4958: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4959: if ($role eq 'cr') { next; }
1.948 raeburn 4960: if ($codes) {
4961: if ($section) { $role .= ':'.$section; }
4962: if ($returnhash{$role}) {
4963: $returnhash{$role}.=','.$username.':'.$domain;
4964: } else {
4965: $returnhash{$role}=$username.':'.$domain;
4966: }
1.351 www 4967: } else {
1.988 raeburn 4968: my $key=&plaintext($role,$crstype);
1.973 bisitz 4969: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4970: if ($returnhash{$key}) {
4971: $returnhash{$key}.=','.$username.':'.$domain;
4972: } else {
4973: $returnhash{$key}=$username.':'.$domain;
4974: }
1.351 www 4975: }
1.948 raeburn 4976: }
1.400 www 4977: return %returnhash;
4978: }
4979:
4980: sub get_my_roles {
1.937 raeburn 4981: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4982: unless (defined($uname)) { $uname=$env{'user.name'}; }
4983: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4984: my (%dumphash,%nothide);
1.1086 raeburn 4985: if ($context eq 'userroles') {
1.1166 raeburn 4986: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4987: } else {
1.1172.2.23 raeburn 4988: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4989: if ($hidepriv) {
4990: my %coursehash=&coursedescription($udom.'_'.$uname);
4991: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4992: if ($user !~ /:/) {
4993: $nothide{join(':',split(/[\@]/,$user))} = 1;
4994: } else {
4995: $nothide{$user} = 1;
4996: }
4997: }
4998: }
1.858 raeburn 4999: }
1.400 www 5000: my %returnhash=();
5001: my $now=time;
1.999 raeburn 5002: my %privileged;
1.800 albertel 5003: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5004: my ($role,$tend,$tstart);
5005: if ($context eq 'userroles') {
1.1149 raeburn 5006: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5007: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5008: } else {
5009: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5010: }
1.400 www 5011: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5012: my $status = 'active';
1.939 raeburn 5013: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5014: $status = 'previous';
5015: }
5016: if (($tstart) && ($now<$tstart)) {
5017: $status = 'future';
5018: }
5019: if (ref($types) eq 'ARRAY') {
5020: if (!grep(/^\Q$status\E$/,@{$types})) {
5021: next;
5022: }
5023: } else {
5024: if ($status ne 'active') {
5025: next;
5026: }
5027: }
1.867 raeburn 5028: my ($rolecode,$username,$domain,$section,$area);
5029: if ($context eq 'userroles') {
1.1172.2.9 raeburn 5030: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5031: (undef,$domain,$username,$section) = split(/\//,$area);
5032: } else {
5033: ($role,$username,$domain,$section) = split(/\:/,$entry);
5034: }
1.832 raeburn 5035: if (ref($roledoms) eq 'ARRAY') {
5036: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5037: next;
5038: }
5039: }
5040: if (ref($roles) eq 'ARRAY') {
5041: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5042: if ($role =~ /^cr\//) {
5043: if (!grep(/^cr$/,@{$roles})) {
5044: next;
5045: }
1.1104 raeburn 5046: } elsif ($role =~ /^gr\//) {
5047: if (!grep(/^gr$/,@{$roles})) {
5048: next;
5049: }
1.922 raeburn 5050: } else {
5051: next;
5052: }
1.832 raeburn 5053: }
1.867 raeburn 5054: }
1.937 raeburn 5055: if ($hidepriv) {
1.1172.2.23 raeburn 5056: my @privroles = ('dc','su');
1.999 raeburn 5057: if ($context eq 'userroles') {
1.1172.2.23 raeburn 5058: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5059: } else {
1.1172.2.23 raeburn 5060: my $possdoms = [$domain];
5061: if (ref($roledoms) eq 'ARRAY') {
5062: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5063: }
1.1172.2.23 raeburn 5064: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5065: if (!$nothide{$username.':'.$domain}) {
5066: next;
5067: }
5068: }
1.937 raeburn 5069: }
5070: }
1.933 raeburn 5071: if ($withsec) {
5072: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5073: $tstart.':'.$tend;
5074: } else {
5075: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5076: }
1.832 raeburn 5077: }
1.373 www 5078: return %returnhash;
1.399 www 5079: }
5080:
1.1172.2.89 raeburn 5081: sub get_all_adhocroles {
5082: my ($dom) = @_;
5083: my @roles_by_num = ();
5084: my %domdefaults = &get_domain_defaults($dom);
5085: my (%description,%access_in_dom,%access_info);
5086: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5087: my $count = 0;
5088: my %domcurrent = %{$domdefaults{'adhocroles'}};
5089: my %ordered;
5090: foreach my $role (sort(keys(%domcurrent))) {
5091: my ($order,$desc,$access_in_dom);
5092: if (ref($domcurrent{$role}) eq 'HASH') {
5093: $order = $domcurrent{$role}{'order'};
5094: $desc = $domcurrent{$role}{'desc'};
5095: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5096: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5097: }
5098: if ($order eq '') {
5099: $order = $count;
5100: }
5101: $ordered{$order} = $role;
5102: if ($desc ne '') {
5103: $description{$role} = $desc;
5104: } else {
5105: $description{$role}= $role;
5106: }
5107: $count++;
5108: }
5109: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5110: push(@roles_by_num,$ordered{$item});
5111: }
5112: }
5113: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5114: }
5115:
5116: sub get_my_adhocroles {
5117: my ($cid,$checkreg) = @_;
5118: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5119: if ($env{'request.course.id'} eq $cid) {
5120: $cdom = $env{'course.'.$cid.'.domain'};
5121: $cnum = $env{'course.'.$cid.'.num'};
5122: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5123: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5124: $cdom = $1;
5125: $cnum = $2;
5126: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5127: $cdom,$cnum);
5128: }
5129: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5130: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5131: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5132: if ($rosterhash{$user} ne '') {
5133: my $type = (split(/:/,$rosterhash{$user}))[5];
5134: return ([],{}) if ($type eq 'auto');
5135: }
5136: }
5137: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5138: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5139: my $then=$env{'user.login.time'};
5140: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5141: if (!$update) {
5142: $update = $then;
5143: }
5144: my @liveroles;
5145: foreach my $role ('dh','da') {
5146: if ($env{"user.role.$role./$cdom/"}) {
5147: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5148: my $limit = $update;
5149: if ($env{'request.role'} eq "$role./$cdom/") {
5150: $limit = $then;
5151: }
5152: my $activerole = 1;
5153: if ($tstart && $tstart>$limit) { $activerole = 0; }
5154: if ($tend && $tend <$limit) { $activerole = 0; }
5155: if ($activerole) {
5156: push(@liveroles,$role);
5157: }
5158: }
5159: }
5160: if (@liveroles) {
1.1172.2.89 raeburn 5161: if (&homeserver($cnum,$cdom) ne 'no_host') {
5162: my ($accessref,$accessinfo,%access_in_dom);
5163: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5164: if (ref($roles_by_num) eq 'ARRAY') {
5165: if (@{$roles_by_num}) {
5166: my %settings;
5167: if ($env{'request.course.id'} eq $cid) {
5168: foreach my $envkey (keys(%env)) {
5169: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5170: $settings{$1} = $env{$envkey};
5171: }
5172: }
5173: } else {
5174: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5175: }
5176: my %setincrs;
5177: if ($settings{'internal.adhocaccess'}) {
5178: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5179: }
5180: my @statuses;
5181: if ($env{'environment.inststatus'}) {
5182: @statuses = split(/,/,$env{'environment.inststatus'});
5183: }
5184: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5185: if (ref($accessref) eq 'HASH') {
5186: %access_in_dom = %{$accessref};
5187: }
5188: foreach my $role (@{$roles_by_num}) {
5189: my ($curraccess,@okstatus,@personnel);
5190: if ($setincrs{$role}) {
5191: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5192: if ($curraccess eq 'status') {
5193: @okstatus = split(/\&/,$rest);
5194: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5195: @personnel = split(/\&/,$rest);
5196: }
5197: } else {
5198: $curraccess = $access_in_dom{$role};
5199: if (ref($accessinfo) eq 'HASH') {
5200: if ($curraccess eq 'status') {
5201: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5202: @okstatus = @{$accessinfo->{$role}};
5203: }
5204: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5205: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5206: @personnel = @{$accessinfo->{$role}};
5207: }
5208: }
5209: }
5210: }
5211: if ($curraccess eq 'none') {
5212: next;
5213: } elsif ($curraccess eq 'all') {
5214: push(@possroles,$role);
1.1172.2.90 raeburn 5215: } elsif ($curraccess eq 'dh') {
5216: if (grep(/^dh$/,@liveroles)) {
5217: push(@possroles,$role);
5218: } else {
5219: next;
5220: }
5221: } elsif ($curraccess eq 'da') {
5222: if (grep(/^da$/,@liveroles)) {
5223: push(@possroles,$role);
5224: } else {
5225: next;
5226: }
1.1172.2.89 raeburn 5227: } elsif ($curraccess eq 'status') {
5228: if (@okstatus) {
5229: if (!@statuses) {
5230: if (grep(/^default$/,@okstatus)) {
5231: push(@possroles,$role);
5232: }
5233: } else {
5234: foreach my $status (@okstatus) {
5235: if (grep(/^\Q$status\E$/,@statuses)) {
5236: push(@possroles,$role);
5237: last;
5238: }
5239: }
5240: }
5241: }
5242: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5243: if (grep(/^\Q$user\E$/,@personnel)) {
5244: if ($curraccess eq 'exc') {
5245: push(@possroles,$role);
5246: }
5247: } elsif ($curraccess eq 'inc') {
5248: push(@possroles,$role);
5249: }
5250: }
5251: }
5252: }
5253: }
5254: }
5255: }
5256: }
5257: }
5258: unless (ref($description) eq 'HASH') {
5259: if (ref($roles_by_num) eq 'ARRAY') {
5260: my %desc;
5261: map { $desc{$_} = $_; } (@{$roles_by_num});
5262: $description = \%desc;
5263: } else {
5264: $description = {};
5265: }
5266: }
5267: return (\@possroles,$description);
5268: }
5269:
1.399 www 5270: # ----------------------------------------------------- Frontpage Announcements
5271: #
5272: #
5273:
5274: sub postannounce {
5275: my ($server,$text)=@_;
1.844 albertel 5276: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5277: unless ($text=~/\w/) { $text=''; }
5278: return &reply('setannounce:'.&escape($text),$server);
5279: }
5280:
5281: sub getannounce {
1.448 albertel 5282:
1.1172.2.96 raeburn 5283: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5284: my $announcement='';
1.800 albertel 5285: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5286: close($fh);
1.399 www 5287: if ($announcement=~/\w/) {
5288: return
5289: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5290: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5291: } else {
5292: return '';
5293: }
5294: } else {
5295: return '';
5296: }
1.351 www 5297: }
1.353 www 5298:
5299: # ---------------------------------------------------------- Course ID routines
5300: # Deal with domain's nohist_courseid.db files
5301: #
5302:
5303: sub courseidput {
1.921 raeburn 5304: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5305: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5306: my $outcome;
5307: if ($caller eq 'timeonly') {
5308: my $cids = '';
5309: foreach my $item (keys(%$storehash)) {
5310: $cids.=&escape($item).'&';
5311: }
5312: $cids=~s/\&$//;
5313: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5314: $coursehome);
5315: } else {
5316: my $items = '';
5317: foreach my $item (keys(%$storehash)) {
5318: $items.= &escape($item).'='.
5319: &freeze_escape($$storehash{$item}).'&';
5320: }
5321: $items=~s/\&$//;
5322: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5323: $coursehome);
1.918 raeburn 5324: }
5325: if ($outcome eq 'unknown_cmd') {
5326: my $what;
5327: foreach my $cid (keys(%$storehash)) {
5328: $what .= &escape($cid).'=';
1.921 raeburn 5329: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5330: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5331: }
5332: $what =~ s/\:$/&/;
5333: }
5334: $what =~ s/\&$//;
5335: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5336: } else {
5337: return $outcome;
5338: }
1.353 www 5339: }
5340:
5341: sub courseiddump {
1.921 raeburn 5342: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5343: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5344: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5345: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5346: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5347: my $as_hash = 1;
5348: my %returnhash;
5349: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5350: my %libserv = &all_library();
5351: foreach my $tryserver (keys(%libserv)) {
5352: if ( ( $hostidflag == 1
5353: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5354: || (!defined($hostidflag)) ) {
5355:
1.918 raeburn 5356: if (($domfilter eq '') ||
5357: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5358: my $rep;
5359: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5360: $rep = &LONCAPA::Lond::dump_course_id_handler(
5361: join(":", (&host_domain($tryserver), $sincefilter,
5362: &escape($descfilter), &escape($instcodefilter),
5363: &escape($ownerfilter), &escape($coursefilter),
5364: &escape($typefilter), &escape($regexp_ok),
5365: $as_hash, &escape($selfenrollonly),
5366: &escape($catfilter), $showhidden, $caller,
5367: &escape($cloner), &escape($cc_clone), $cloneonly,
5368: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5369: &escape($creationcontext),$domcloner,$hasuniquecode,
5370: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5371: } else {
5372: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5373: $sincefilter.':'.&escape($descfilter).':'.
5374: &escape($instcodefilter).':'.&escape($ownerfilter).
5375: ':'.&escape($coursefilter).':'.&escape($typefilter).
5376: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5377: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5378: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5379: &escape($cc_clone).':'.$cloneonly.':'.
5380: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5381: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5382: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5383: }
5384:
1.918 raeburn 5385: my @pairs=split(/\&/,$rep);
5386: foreach my $item (@pairs) {
5387: my ($key,$value)=split(/\=/,$item,2);
5388: $key = &unescape($key);
5389: next if ($key =~ /^error: 2 /);
5390: my $result = &thaw_unescape($value);
5391: if (ref($result) eq 'HASH') {
5392: $returnhash{$key}=$result;
5393: } else {
1.921 raeburn 5394: my @responses = split(/:/,$value);
5395: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5396: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5397: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5398: }
1.1008 raeburn 5399: }
1.353 www 5400: }
5401: }
5402: }
5403: }
5404: return %returnhash;
5405: }
5406:
1.1055 raeburn 5407: sub courselastaccess {
5408: my ($cdom,$cnum,$hostidref) = @_;
5409: my %returnhash;
5410: if ($cdom && $cnum) {
5411: my $chome = &homeserver($cnum,$cdom);
5412: if ($chome ne 'no_host') {
5413: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5414: &extract_lastaccess(\%returnhash,$rep);
5415: }
5416: } else {
5417: if (!$cdom) { $cdom=''; }
5418: my %libserv = &all_library();
5419: foreach my $tryserver (keys(%libserv)) {
5420: if (ref($hostidref) eq 'ARRAY') {
5421: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5422: }
5423: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5424: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5425: &extract_lastaccess(\%returnhash,$rep);
5426: }
5427: }
5428: }
5429: return %returnhash;
5430: }
5431:
5432: sub extract_lastaccess {
5433: my ($returnhash,$rep) = @_;
5434: if (ref($returnhash) eq 'HASH') {
5435: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5436: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5437: $rep eq '') {
5438: my @pairs=split(/\&/,$rep);
5439: foreach my $item (@pairs) {
5440: my ($key,$value)=split(/\=/,$item,2);
5441: $key = &unescape($key);
5442: next if ($key =~ /^error: 2 /);
5443: $returnhash->{$key} = &thaw_unescape($value);
5444: }
5445: }
5446: }
5447: return;
5448: }
5449:
1.658 raeburn 5450: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5451:
5452: sub dcmailput {
1.685 raeburn 5453: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5454: my $status = &Apache::lonnet::critical(
1.740 www 5455: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5456: &escape($message),$server);
1.662 raeburn 5457: return $status;
5458: }
5459:
1.658 raeburn 5460: sub dcmaildump {
5461: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5462: my %returnhash=();
1.846 albertel 5463:
5464: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5465: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5466: &escape($enddate).':';
5467: my @esc_senders=map { &escape($_)} @$senders;
5468: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5469: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5470: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5471: if (($key) && ($value)) {
5472: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5473: }
5474: }
5475: }
5476: return %returnhash;
5477: }
1.662 raeburn 5478: # ---------------------------------------------------------- Domain roles
5479:
5480: sub get_domain_roles {
5481: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5482: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5483: $startdate = '.';
5484: }
1.1018 raeburn 5485: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5486: $enddate = '.';
5487: }
1.922 raeburn 5488: my $rolelist;
5489: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5490: $rolelist = join('&',@{$roles});
1.922 raeburn 5491: }
1.662 raeburn 5492: my %personnel = ();
1.841 albertel 5493:
5494: my %servers = &get_servers($dom,'library');
5495: foreach my $tryserver (keys(%servers)) {
5496: %{$personnel{$tryserver}}=();
5497: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5498: &escape($startdate).':'.
5499: &escape($enddate).':'.
5500: &escape($rolelist), $tryserver))) {
5501: my ($key,$value) = split(/\=/,$line,2);
5502: if (($key) && ($value)) {
5503: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5504: }
5505: }
1.662 raeburn 5506: }
5507: return %personnel;
5508: }
1.658 raeburn 5509:
1.1172.2.89 raeburn 5510: sub get_active_domroles {
5511: my ($dom,$roles) = @_;
5512: return () unless (ref($roles) eq 'ARRAY');
5513: my $now = time;
5514: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5515: my %domroles;
5516: foreach my $server (keys(%dompersonnel)) {
5517: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5518: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5519: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5520: }
5521: }
5522: return %domroles;
5523: }
5524:
1.1057 www 5525: # ----------------------------------------------------------- Interval timing
1.149 www 5526:
1.1153 www 5527: {
5528: # Caches needed for speedup of navmaps
5529: # We don't want to cache this for very long at all (5 seconds at most)
5530: #
5531: # The user for whom we cache
5532: my $cachedkey='';
5533: # The cached times for this user
5534: my %cachedtimes=();
5535: # When this was last done
1.1172.2.66 raeburn 5536: my $cachedtime='';
1.1153 www 5537:
5538: sub load_all_first_access {
1.1172.2.147. .1(raebu 5539:22): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5540: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.147. .1(raebu 5541:22): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5542:22): (!$ignorecache)) {
1.1154 raeburn 5543: return;
5544: }
5545: $cachedtime=time;
5546: $cachedkey=$uname.':'.$udom;
5547: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5548: }
5549:
1.504 albertel 5550: sub get_first_access {
1.1172.2.147. .1(raebu 5551:22): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5552: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5553: if ($argsymb) { $symb=$argsymb; }
5554: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5555: if ($argmap) { $map = $argmap; }
1.926 albertel 5556: if ($type eq 'course') {
5557: $res='course';
5558: } elsif ($type eq 'map') {
1.588 albertel 5559: $res=&symbread($map);
5560: } else {
5561: $res=$symb;
5562: }
1.1172.2.147. .1(raebu 5563:22): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5564: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5565: }
5566:
5567: sub set_first_access {
1.1162 raeburn 5568: my ($type,$interval)=@_;
1.790 albertel 5569: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5570: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5571: if ($type eq 'course') {
5572: $res='course';
5573: } elsif ($type eq 'map') {
1.588 albertel 5574: $res=&symbread($map);
5575: } else {
5576: $res=$symb;
5577: }
1.1153 www 5578: $cachedkey='';
1.1162 raeburn 5579: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5580: if ($firstaccess) {
5581: &logthis("First access time already set ($firstaccess) when attempting ".
5582: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5583: "in $courseid");
5584: return 'already_set';
5585: } else {
1.1162 raeburn 5586: my $start = time;
5587: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5588: $udom,$uname);
5589: if ($putres eq 'ok') {
5590: &put('timerinterval',{"$courseid\0$res"=>$interval},
5591: $udom,$uname);
5592: &appenv(
5593: {
5594: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5595: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5596: }
5597: );
1.1172.2.97 raeburn 5598: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5599: $cachedtimes{"$courseid\0$res"} = $start;
5600: }
1.1172.2.102 raeburn 5601: } elsif ($putres ne 'refused') {
5602: &logthis("Result: $putres when attempting to set first access time ".
5603: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5604: }
5605: return $putres;
1.505 albertel 5606: }
5607: return 'already_set';
1.504 albertel 5608: }
1.1153 www 5609: }
1.1172.2.32 raeburn 5610:
5611: sub checkout {
5612: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5613: my $now=time;
5614: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5615: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5616: my $infostr=&escape(
5617: 'CHECKOUTTOKEN&'.
5618: $tuname.'&'.
5619: $tudom.'&'.
5620: $tcrsid.'&'.
5621: $symb.'&'.
1.1172.2.134 raeburn 5622: $now.'&'.$ip);
1.1172.2.32 raeburn 5623: my $token=&reply('tmpput:'.$infostr,$lonhost);
5624: if ($token=~/^error\:/) {
5625: &logthis("<font color=\"blue\">WARNING: ".
5626: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5627: "</font>");
5628: return '';
5629: }
5630:
5631: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5632: $token=~tr/a-z/A-Z/;
5633:
5634: my %infohash=('resource.0.outtoken' => $token,
5635: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5636: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5637:
5638: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5639: return '';
5640: } else {
5641: &logthis("<font color=\"blue\">WARNING: ".
5642: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5643: "</font>");
5644: }
5645:
5646: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5647: &escape('Checkout '.$infostr.' - '.
5648: $token)) ne 'ok') {
5649: return '';
5650: } else {
5651: &logthis("<font color=\"blue\">WARNING: ".
5652: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5653: "</font>");
5654: }
5655: return $token;
5656: }
5657:
5658: # ------------------------------------------------------------ Check in an item
5659:
5660: sub checkin {
5661: my $token=shift;
5662: my $now=time;
5663: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5664: $lonhost=~tr/A-Z/a-z/;
5665: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5666: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5667: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5668: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5669: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5670:
5671: unless (($tuname) && ($tudom)) {
5672: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5673: return '';
5674: }
5675:
5676: unless (&allowed('mgr',$tcrsid)) {
5677: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5678: $env{'user.name'}.' - '.$env{'user.domain'});
5679: return '';
5680: }
5681:
5682: my %infohash=('resource.0.intoken' => $token,
5683: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5684: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5685:
5686: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5687: return '';
5688: }
5689:
5690: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5691: &escape('Checkin - '.$token)) ne 'ok') {
5692: return '';
5693: }
5694:
5695: return ($symb,$tuname,$tudom,$tcrsid);
5696: }
5697:
1.110 www 5698: # --------------------------------------------- Set Expire Date for Spreadsheet
5699:
5700: sub expirespread {
5701: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5702: my $cid=$env{'request.course.id'};
1.110 www 5703: if ($cid) {
5704: my $now=time;
5705: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5706: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5707: $env{'course.'.$cid.'.num'}.
1.110 www 5708: ':nohist_expirationdates:'.
5709: &escape($key).'='.$now,
1.620 albertel 5710: $env{'course.'.$cid.'.home'})
1.110 www 5711: }
5712: return 'ok';
1.14 www 5713: }
5714:
1.109 www 5715: # ----------------------------------------------------- Devalidate Spreadsheets
5716:
5717: sub devalidate {
1.325 www 5718: my ($symb,$uname,$udom)=@_;
1.620 albertel 5719: my $cid=$env{'request.course.id'};
1.109 www 5720: if ($cid) {
1.391 matthew 5721: # delete the stored spreadsheets for
5722: # - the student level sheet of this user in course's homespace
5723: # - the assessment level sheet for this resource
5724: # for this user in user's homespace
1.553 albertel 5725: # - current conditional state info
1.325 www 5726: my $key=$uname.':'.$udom.':';
1.109 www 5727: my $status=
1.299 matthew 5728: &del('nohist_calculatedsheets',
1.391 matthew 5729: [$key.'studentcalc:'],
1.620 albertel 5730: $env{'course.'.$cid.'.domain'},
5731: $env{'course.'.$cid.'.num'})
1.133 albertel 5732: .' '.
5733: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5734: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5735: unless ($status eq 'ok ok') {
5736: &logthis('Could not devalidate spreadsheet '.
1.325 www 5737: $uname.' at '.$udom.' for '.
1.109 www 5738: $symb.': '.$status);
1.133 albertel 5739: }
1.553 albertel 5740: &delenv('user.state.'.$cid);
1.109 www 5741: }
5742: }
5743:
1.265 albertel 5744: sub get_scalar {
5745: my ($string,$end) = @_;
5746: my $value;
5747: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5748: $value = $1;
5749: } elsif ($$string =~ s/^([^&]*?)&//) {
5750: $value = $1;
5751: }
5752: return &unescape($value);
5753: }
5754:
5755: sub array2str {
5756: my (@array) = @_;
5757: my $result=&arrayref2str(\@array);
5758: $result=~s/^__ARRAY_REF__//;
5759: $result=~s/__END_ARRAY_REF__$//;
5760: return $result;
5761: }
5762:
1.204 albertel 5763: sub arrayref2str {
5764: my ($arrayref) = @_;
1.265 albertel 5765: my $result='__ARRAY_REF__';
1.204 albertel 5766: foreach my $elem (@$arrayref) {
1.265 albertel 5767: if(ref($elem) eq 'ARRAY') {
5768: $result.=&arrayref2str($elem).'&';
5769: } elsif(ref($elem) eq 'HASH') {
5770: $result.=&hashref2str($elem).'&';
5771: } elsif(ref($elem)) {
5772: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5773: } else {
5774: $result.=&escape($elem).'&';
5775: }
5776: }
5777: $result=~s/\&$//;
1.265 albertel 5778: $result .= '__END_ARRAY_REF__';
1.204 albertel 5779: return $result;
5780: }
5781:
1.168 albertel 5782: sub hash2str {
1.204 albertel 5783: my (%hash) = @_;
5784: my $result=&hashref2str(\%hash);
1.265 albertel 5785: $result=~s/^__HASH_REF__//;
5786: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5787: return $result;
5788: }
5789:
5790: sub hashref2str {
5791: my ($hashref)=@_;
1.265 albertel 5792: my $result='__HASH_REF__';
1.800 albertel 5793: foreach my $key (sort(keys(%$hashref))) {
5794: if (ref($key) eq 'ARRAY') {
5795: $result.=&arrayref2str($key).'=';
5796: } elsif (ref($key) eq 'HASH') {
5797: $result.=&hashref2str($key).'=';
5798: } elsif (ref($key)) {
1.265 albertel 5799: $result.='=';
1.800 albertel 5800: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5801: } else {
1.1132 raeburn 5802: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5803: }
5804:
1.800 albertel 5805: if(ref($hashref->{$key}) eq 'ARRAY') {
5806: $result.=&arrayref2str($hashref->{$key}).'&';
5807: } elsif(ref($hashref->{$key}) eq 'HASH') {
5808: $result.=&hashref2str($hashref->{$key}).'&';
5809: } elsif(ref($hashref->{$key})) {
1.265 albertel 5810: $result.='&';
1.800 albertel 5811: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5812: } else {
1.800 albertel 5813: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5814: }
5815: }
1.168 albertel 5816: $result=~s/\&$//;
1.265 albertel 5817: $result .= '__END_HASH_REF__';
1.168 albertel 5818: return $result;
5819: }
5820:
5821: sub str2hash {
1.265 albertel 5822: my ($string)=@_;
5823: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5824: return %$hash;
5825: }
5826:
5827: sub str2hashref {
1.168 albertel 5828: my ($string) = @_;
1.265 albertel 5829:
5830: my %hash;
5831:
5832: if($string !~ /^__HASH_REF__/) {
5833: if (! ($string eq '' || !defined($string))) {
5834: $hash{'error'}='Not hash reference';
5835: }
5836: return (\%hash, $string);
5837: }
5838:
5839: $string =~ s/^__HASH_REF__//;
5840:
5841: while($string !~ /^__END_HASH_REF__/) {
5842: #key
5843: my $key='';
5844: if($string =~ /^__HASH_REF__/) {
5845: ($key, $string)=&str2hashref($string);
5846: if(defined($key->{'error'})) {
5847: $hash{'error'}='Bad data';
5848: return (\%hash, $string);
5849: }
5850: } elsif($string =~ /^__ARRAY_REF__/) {
5851: ($key, $string)=&str2arrayref($string);
5852: if($key->[0] eq 'Array reference error') {
5853: $hash{'error'}='Bad data';
5854: return (\%hash, $string);
5855: }
5856: } else {
5857: $string =~ s/^(.*?)=//;
1.267 albertel 5858: $key=&unescape($1);
1.265 albertel 5859: }
5860: $string =~ s/^=//;
5861:
5862: #value
5863: my $value='';
5864: if($string =~ /^__HASH_REF__/) {
5865: ($value, $string)=&str2hashref($string);
5866: if(defined($value->{'error'})) {
5867: $hash{'error'}='Bad data';
5868: return (\%hash, $string);
5869: }
5870: } elsif($string =~ /^__ARRAY_REF__/) {
5871: ($value, $string)=&str2arrayref($string);
5872: if($value->[0] eq 'Array reference error') {
5873: $hash{'error'}='Bad data';
5874: return (\%hash, $string);
5875: }
5876: } else {
5877: $value=&get_scalar(\$string,'__END_HASH_REF__');
5878: }
5879: $string =~ s/^&//;
5880:
5881: $hash{$key}=$value;
1.204 albertel 5882: }
1.265 albertel 5883:
5884: $string =~ s/^__END_HASH_REF__//;
5885:
5886: return (\%hash, $string);
1.204 albertel 5887: }
5888:
5889: sub str2array {
1.265 albertel 5890: my ($string)=@_;
5891: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5892: return @$array;
5893: }
5894:
5895: sub str2arrayref {
1.204 albertel 5896: my ($string) = @_;
1.265 albertel 5897: my @array;
5898:
5899: if($string !~ /^__ARRAY_REF__/) {
5900: if (! ($string eq '' || !defined($string))) {
5901: $array[0]='Array reference error';
5902: }
5903: return (\@array, $string);
5904: }
5905:
5906: $string =~ s/^__ARRAY_REF__//;
5907:
5908: while($string !~ /^__END_ARRAY_REF__/) {
5909: my $value='';
5910: if($string =~ /^__HASH_REF__/) {
5911: ($value, $string)=&str2hashref($string);
5912: if(defined($value->{'error'})) {
5913: $array[0] ='Array reference error';
5914: return (\@array, $string);
5915: }
5916: } elsif($string =~ /^__ARRAY_REF__/) {
5917: ($value, $string)=&str2arrayref($string);
5918: if($value->[0] eq 'Array reference error') {
5919: $array[0] ='Array reference error';
5920: return (\@array, $string);
5921: }
5922: } else {
5923: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5924: }
5925: $string =~ s/^&//;
5926:
5927: push(@array, $value);
1.191 harris41 5928: }
1.265 albertel 5929:
5930: $string =~ s/^__END_ARRAY_REF__//;
5931:
5932: return (\@array, $string);
1.168 albertel 5933: }
5934:
1.167 albertel 5935: # -------------------------------------------------------------------Temp Store
5936:
1.168 albertel 5937: sub tmpreset {
5938: my ($symb,$namespace,$domain,$stuname) = @_;
5939: if (!$symb) {
5940: $symb=&symbread();
1.620 albertel 5941: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5942: }
5943: $symb=escape($symb);
5944:
1.620 albertel 5945: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5946: $namespace=~s/\//\_/g;
5947: $namespace=~s/\W//g;
5948:
1.620 albertel 5949: if (!$domain) { $domain=$env{'user.domain'}; }
5950: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5951: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5952: $stuname=&get_requestor_ip();
1.591 albertel 5953: }
1.1117 foxr 5954: my $path=LONCAPA::tempdir();
1.168 albertel 5955: my %hash;
5956: if (tie(%hash,'GDBM_File',
5957: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5958: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5959: foreach my $key (keys(%hash)) {
1.180 albertel 5960: if ($key=~ /:$symb/) {
1.168 albertel 5961: delete($hash{$key});
5962: }
5963: }
5964: }
5965: }
5966:
1.167 albertel 5967: sub tmpstore {
1.168 albertel 5968: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5969:
5970: if (!$symb) {
5971: $symb=&symbread();
1.620 albertel 5972: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5973: }
5974: $symb=escape($symb);
5975:
5976: if (!$namespace) {
5977: # I don't think we would ever want to store this for a course.
5978: # it seems this will only be used if we don't have a course.
1.620 albertel 5979: #$namespace=$env{'request.course.id'};
1.168 albertel 5980: #if (!$namespace) {
1.620 albertel 5981: $namespace=$env{'request.state'};
1.168 albertel 5982: #}
5983: }
5984: $namespace=~s/\//\_/g;
5985: $namespace=~s/\W//g;
1.620 albertel 5986: if (!$domain) { $domain=$env{'user.domain'}; }
5987: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5988: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5989: $stuname=&get_requestor_ip();
1.591 albertel 5990: }
1.168 albertel 5991: my $now=time;
5992: my %hash;
1.1117 foxr 5993: my $path=LONCAPA::tempdir();
1.168 albertel 5994: if (tie(%hash,'GDBM_File',
5995: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5996: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5997: $hash{"version:$symb"}++;
5998: my $version=$hash{"version:$symb"};
5999: my $allkeys='';
6000: foreach my $key (keys(%$storehash)) {
6001: $allkeys.=$key.':';
1.591 albertel 6002: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6003: }
6004: $hash{"$version:$symb:timestamp"}=$now;
6005: $allkeys.='timestamp';
6006: $hash{"$version:keys:$symb"}=$allkeys;
6007: if (untie(%hash)) {
6008: return 'ok';
6009: } else {
6010: return "error:$!";
6011: }
6012: } else {
6013: return "error:$!";
6014: }
6015: }
1.167 albertel 6016:
1.168 albertel 6017: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6018:
1.168 albertel 6019: sub tmprestore {
6020: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6021:
1.168 albertel 6022: if (!$symb) {
6023: $symb=&symbread();
1.620 albertel 6024: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6025: }
6026: $symb=escape($symb);
6027:
1.620 albertel 6028: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6029:
1.620 albertel 6030: if (!$domain) { $domain=$env{'user.domain'}; }
6031: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6032: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 6033: $stuname=&get_requestor_ip();
1.591 albertel 6034: }
1.168 albertel 6035: my %returnhash;
6036: $namespace=~s/\//\_/g;
6037: $namespace=~s/\W//g;
6038: my %hash;
1.1117 foxr 6039: my $path=LONCAPA::tempdir();
1.168 albertel 6040: if (tie(%hash,'GDBM_File',
6041: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6042: &GDBM_READER(),0640)) {
1.168 albertel 6043: my $version=$hash{"version:$symb"};
6044: $returnhash{'version'}=$version;
6045: my $scope;
6046: for ($scope=1;$scope<=$version;$scope++) {
6047: my $vkeys=$hash{"$scope:keys:$symb"};
6048: my @keys=split(/:/,$vkeys);
6049: my $key;
6050: $returnhash{"$scope:keys"}=$vkeys;
6051: foreach $key (@keys) {
1.591 albertel 6052: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6053: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6054: }
6055: }
1.168 albertel 6056: if (!(untie(%hash))) {
6057: return "error:$!";
6058: }
6059: } else {
6060: return "error:$!";
6061: }
6062: return %returnhash;
1.167 albertel 6063: }
6064:
1.9 www 6065: # ----------------------------------------------------------------------- Store
6066:
6067: sub store {
1.1172.2.64 raeburn 6068: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6069: my $home='';
6070:
1.168 albertel 6071: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6072:
1.213 www 6073: $symb=&symbclean($symb);
1.122 albertel 6074: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6075:
1.620 albertel 6076: if (!$domain) { $domain=$env{'user.domain'}; }
6077: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6078:
6079: &devalidate($symb,$stuname,$domain);
1.109 www 6080:
6081: $symb=escape($symb);
1.187 www 6082: if (!$namespace) {
1.620 albertel 6083: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6084: return '';
6085: }
6086: }
1.620 albertel 6087: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6088:
1.1172.2.138 raeburn 6089: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6090: $$storehash{'host'}=$perlvar{'lonHostID'};
6091:
1.12 www 6092: my $namevalue='';
1.800 albertel 6093: foreach my $key (keys(%$storehash)) {
6094: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6095: }
1.12 www 6096: $namevalue=~s/\&$//;
1.187 www 6097: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6098: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6099: }
6100:
1.47 www 6101: # -------------------------------------------------------------- Critical Store
6102:
6103: sub cstore {
1.1172.2.64 raeburn 6104: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6105: my $home='';
6106:
1.168 albertel 6107: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6108:
1.213 www 6109: $symb=&symbclean($symb);
1.122 albertel 6110: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6111:
1.620 albertel 6112: if (!$domain) { $domain=$env{'user.domain'}; }
6113: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6114:
6115: &devalidate($symb,$stuname,$domain);
1.109 www 6116:
6117: $symb=escape($symb);
1.187 www 6118: if (!$namespace) {
1.620 albertel 6119: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6120: return '';
6121: }
6122: }
1.620 albertel 6123: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6124:
1.1172.2.138 raeburn 6125: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6126: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6127:
1.47 www 6128: my $namevalue='';
1.800 albertel 6129: foreach my $key (keys(%$storehash)) {
6130: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6131: }
1.47 www 6132: $namevalue=~s/\&$//;
1.187 www 6133: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6134: return critical
1.1172.2.64 raeburn 6135: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6136: }
6137:
1.9 www 6138: # --------------------------------------------------------------------- Restore
6139:
6140: sub restore {
1.124 www 6141: my ($symb,$namespace,$domain,$stuname) = @_;
6142: my $home='';
6143:
1.168 albertel 6144: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6145:
1.122 albertel 6146: if (!$symb) {
1.1172.2.26 raeburn 6147: return if ($namespace eq 'courserequests');
6148: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6149: } else {
1.1172.2.26 raeburn 6150: unless ($namespace eq 'courserequests') {
6151: $symb=&escape(&symbclean($symb));
6152: }
1.122 albertel 6153: }
1.188 www 6154: if (!$namespace) {
1.620 albertel 6155: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6156: return '';
6157: }
6158: }
1.620 albertel 6159: if (!$domain) { $domain=$env{'user.domain'}; }
6160: if (!$stuname) { $stuname=$env{'user.name'}; }
6161: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6162: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6163:
1.12 www 6164: my %returnhash=();
1.800 albertel 6165: foreach my $line (split(/\&/,$answer)) {
6166: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6167: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6168: }
1.75 www 6169: my $version;
6170: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6171: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6172: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6173: }
1.75 www 6174: }
1.13 www 6175: return %returnhash;
1.34 www 6176: }
6177:
6178: # ---------------------------------------------------------- Course Description
1.1118 foxr 6179: #
6180: #
1.34 www 6181:
6182: sub coursedescription {
1.731 albertel 6183: my ($courseid,$args)=@_;
1.34 www 6184: $courseid=~s/^\///;
1.49 www 6185: $courseid=~s/\_/\//g;
1.34 www 6186: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6187: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6188: my $normalid=$cdomain.'_'.$cnum;
6189: # need to always cache even if we get errors otherwise we keep
6190: # trying and trying and trying to get the course description.
6191: my %envhash=();
6192: my %returnhash=();
1.731 albertel 6193:
6194: my $expiretime=600;
6195: if ($env{'request.course.id'} eq $normalid) {
6196: $expiretime=120;
6197: }
6198:
6199: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6200: if (!$args->{'freshen_cache'}
6201: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6202: foreach my $key (keys(%env)) {
6203: next if ($key !~ /^\Q$prefix\E(.*)/);
6204: my ($setting) = $1;
6205: $returnhash{$setting} = $env{$key};
6206: }
6207: return %returnhash;
6208: }
6209:
1.1118 foxr 6210: # get the data again
6211:
1.731 albertel 6212: if (!$args->{'one_time'}) {
6213: $envhash{'course.'.$normalid.'.last_cache'}=time;
6214: }
1.811 albertel 6215:
1.34 www 6216: if ($chome ne 'no_host') {
1.302 albertel 6217: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6218: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6219: my $username = $env{'user.name'}; # Defult username
6220: if(defined $args->{'user'}) {
6221: $username = $args->{'user'};
6222: }
1.129 albertel 6223: $returnhash{'home'}= $chome;
6224: $returnhash{'domain'} = $cdomain;
6225: $returnhash{'num'} = $cnum;
1.741 raeburn 6226: if (!defined($returnhash{'type'})) {
6227: $returnhash{'type'} = 'Course';
6228: }
1.130 albertel 6229: while (my ($name,$value) = each %returnhash) {
1.53 www 6230: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6231: }
1.270 www 6232: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6233: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6234: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6235: $envhash{'course.'.$normalid.'.home'}=$chome;
6236: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6237: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6238: }
6239: }
1.731 albertel 6240: if (!$args->{'one_time'}) {
1.949 raeburn 6241: &appenv(\%envhash);
1.731 albertel 6242: }
1.302 albertel 6243: return %returnhash;
1.461 www 6244: }
6245:
1.1080 raeburn 6246: sub update_released_required {
6247: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6248: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6249: $cid = $env{'request.course.id'};
6250: $cdom = $env{'course.'.$cid.'.domain'};
6251: $cnum = $env{'course.'.$cid.'.num'};
6252: $chome = $env{'course.'.$cid.'.home'};
6253: }
6254: if ($needsrelease) {
6255: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6256: my $needsupdate;
6257: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6258: $needsupdate = 1;
6259: } else {
6260: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6261: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6262: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6263: $needsupdate = 1;
6264: }
6265: }
6266: if ($needsupdate) {
6267: my %needshash = (
6268: 'internal.releaserequired' => $needsrelease,
6269: );
6270: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6271: if ($putresult eq 'ok') {
6272: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6273: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6274: if (ref($crsinfo{$cid}) eq 'HASH') {
6275: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6276: &courseidput($cdom,\%crsinfo,$chome,'notime');
6277: }
6278: }
6279: }
6280: }
6281: return;
6282: }
6283:
1.461 www 6284: # -------------------------------------------------See if a user is privileged
6285:
6286: sub privileged {
1.1172.2.23 raeburn 6287: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6288: my $now = time;
1.1172.2.23 raeburn 6289: my $roles;
6290: if (ref($possroles) eq 'ARRAY') {
6291: $roles = $possroles;
6292: } else {
6293: $roles = ['dc','su'];
6294: }
6295: if (ref($possdomains) eq 'ARRAY') {
6296: my %privileged = &privileged_by_domain($possdomains,$roles);
6297: foreach my $dom (@{$possdomains}) {
6298: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6299: (ref($privileged{$dom}) eq 'HASH')) {
6300: foreach my $role (@{$roles}) {
6301: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6302: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6303: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6304: return 1 unless (($end && $end < $now) ||
6305: ($start && $start > $now));
6306: }
6307: }
6308: }
6309: }
6310: }
6311: } else {
6312: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6313: my $now = time;
1.1170 droeschl 6314:
1.1172.2.58 raeburn 6315: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6316: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6317: if (grep(/^\Q$trole\E$/,@{$roles})) {
6318: return 1 unless ($tend && $tend < $now)
6319: or ($tstart && $tstart > $now);
1.1170 droeschl 6320: }
1.1172.2.23 raeburn 6321: }
6322: }
1.461 www 6323: return 0;
1.9 www 6324: }
1.1 albertel 6325:
1.1172.2.23 raeburn 6326: sub privileged_by_domain {
6327: my ($domains,$roles) = @_;
6328: my %privileged = ();
6329: my $cachetime = 60*60*24;
6330: my $now = time;
6331: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6332: return %privileged;
6333: }
6334: foreach my $dom (@{$domains}) {
6335: next if (ref($privileged{$dom}) eq 'HASH');
6336: my $needroles;
6337: foreach my $role (@{$roles}) {
6338: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6339: if (defined($cached)) {
6340: if (ref($result) eq 'HASH') {
6341: $privileged{$dom}{$role} = $result;
6342: }
6343: } else {
6344: $needroles = 1;
6345: }
6346: }
6347: if ($needroles) {
6348: my %dompersonnel = &get_domain_roles($dom,$roles);
6349: $privileged{$dom} = {};
6350: foreach my $server (keys(%dompersonnel)) {
6351: if (ref($dompersonnel{$server}) eq 'HASH') {
6352: foreach my $item (keys(%{$dompersonnel{$server}})) {
6353: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6354: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6355: next if ($end && $end < $now);
6356: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6357: $dompersonnel{$server}{$item};
6358: }
6359: }
6360: }
6361: if (ref($privileged{$dom}) eq 'HASH') {
6362: foreach my $role (@{$roles}) {
6363: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6364: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6365: } else {
6366: my %hash = ();
6367: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6368: }
6369: }
6370: }
6371: }
6372: }
6373: return %privileged;
6374: }
6375:
1.103 harris41 6376: # -------------------------------------------------------- Get user privileges
1.11 www 6377:
6378: sub rolesinit {
1.1169 droeschl 6379: my ($domain, $username) = @_;
6380: my %userroles = ('user.login.time' => time);
6381: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6382:
6383: # firstaccess and timerinterval are related to timed maps/resources.
6384: # also, blocking can be triggered by an activating timer
6385: # it's saved in the user's %env.
6386: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6387: my %timerinterval = &dump('timerinterval', $domain, $username);
6388: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6389: %timerintchk, %timerintenv);
6390:
1.1162 raeburn 6391: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6392: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6393: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6394: }
1.1169 droeschl 6395:
1.1162 raeburn 6396: foreach my $key (keys(%timerinterval)) {
6397: my ($cid,$rest) = split(/\0/,$key);
6398: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6399: }
1.1169 droeschl 6400:
1.11 www 6401: my %allroles=();
1.1162 raeburn 6402: my %allgroups=();
1.11 www 6403:
1.1172.2.58 raeburn 6404: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6405: my $role = $rolesdump{$area};
6406: $area =~ s/\_\w\w$//;
6407:
6408: my ($trole, $tend, $tstart, $group_privs);
6409:
6410: if ($role =~ /^cr/) {
6411: # Custom role, defined by a user
6412: # e.g., user.role.cr/msu/smith/mynewrole
6413: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6414: $trole = $1;
6415: ($tend, $tstart) = split('_', $2);
6416: } else {
6417: $trole = $role;
6418: }
6419: } elsif ($role =~ m|^gr/|) {
6420: # Role of member in a group, defined within a course/community
6421: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6422: ($trole, $tend, $tstart) = split(/_/, $role);
6423: next if $tstart eq '-1';
6424: ($trole, $group_privs) = split(/\//, $trole);
6425: $group_privs = &unescape($group_privs);
6426: } else {
6427: # Just a normal role, defined in roles.tab
6428: ($trole, $tend, $tstart) = split(/_/,$role);
6429: }
6430:
6431: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6432: $username);
6433: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6434:
6435: # role expired or not available yet?
6436: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6437: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6438:
6439: next if $area eq '' or $trole eq '';
6440:
6441: my $spec = "$trole.$area";
6442: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6443:
6444: if ($trole =~ /^cr\//) {
6445: # Custom role, defined by a user
6446: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6447: } elsif ($trole eq 'gr') {
6448: # Role of a member in a group, defined within a course/community
6449: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6450: next;
6451: } else {
6452: # Normal role, defined in roles.tab
6453: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6454: }
6455:
6456: my $cid = $tdomain.'_'.$trest;
6457: unless ($firstaccchk{$cid}) {
6458: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6459: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6460: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6461: $coursetimerstarts{$cid}{$item};
6462: }
6463: }
6464: $firstaccchk{$cid} = 1;
6465: }
6466: unless ($timerintchk{$cid}) {
6467: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6468: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6469: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6470: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6471: }
1.12 www 6472: }
1.1169 droeschl 6473: $timerintchk{$cid} = 1;
1.191 harris41 6474: }
1.11 www 6475: }
1.1169 droeschl 6476:
1.1172.2.91 raeburn 6477: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6478: \%allroles, \%allgroups);
1.1169 droeschl 6479: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6480: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6481:
1.1162 raeburn 6482: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6483: }
6484:
1.567 raeburn 6485: sub set_arearole {
1.1172.2.19 raeburn 6486: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6487: unless ($nolog) {
1.567 raeburn 6488: # log the associated role with the area
1.1172.2.19 raeburn 6489: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6490: }
1.743 albertel 6491: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6492: }
6493:
6494: sub custom_roleprivs {
6495: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6496: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6497: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6498: if (&hostname($homsvr) ne '') {
1.567 raeburn 6499: my ($rdummy,$roledef)=
6500: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6501: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6502: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6503: if (defined($syspriv)) {
1.1043 raeburn 6504: if ($trest =~ /^$match_community$/) {
6505: $syspriv =~ s/bre\&S//;
6506: }
1.567 raeburn 6507: $$allroles{'cm./'}.=':'.$syspriv;
6508: $$allroles{$spec.'./'}.=':'.$syspriv;
6509: }
6510: if ($tdomain ne '') {
6511: if (defined($dompriv)) {
6512: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6513: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6514: }
6515: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6516: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6517: my $rolename = $1;
6518: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6519: }
1.567 raeburn 6520: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6521: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6522: }
6523: }
6524: }
6525: }
6526: }
6527:
1.1172.2.89 raeburn 6528: sub course_adhocrole_privs {
6529: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6530: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6531: if ($overrides{"internal.adhocpriv.$rolename"}) {
6532: my (%currprivs,%storeprivs);
6533: foreach my $item (split(/:/,$coursepriv)) {
6534: my ($priv,$restrict) = split(/\&/,$item);
6535: $currprivs{$priv} = $restrict;
6536: }
6537: my (%possadd,%possremove,%full);
6538: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6539: my ($priv,$restrict)=split(/\&/,$item);
6540: $full{$priv} = $restrict;
6541: }
6542: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6543: next if ($item eq '');
6544: my ($rule,$rest) = split(/=/,$item);
6545: next unless (($rule eq 'off') || ($rule eq 'on'));
6546: foreach my $priv (split(/:/,$rest)) {
6547: if ($priv ne '') {
6548: if ($rule eq 'off') {
6549: $possremove{$priv} = 1;
6550: } else {
6551: $possadd{$priv} = 1;
6552: }
6553: }
6554: }
6555: }
6556: foreach my $priv (sort(keys(%full))) {
6557: if (exists($currprivs{$priv})) {
6558: unless (exists($possremove{$priv})) {
6559: $storeprivs{$priv} = $currprivs{$priv};
6560: }
6561: } elsif (exists($possadd{$priv})) {
6562: $storeprivs{$priv} = $full{$priv};
6563: }
6564: }
6565: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6566: }
6567: return $coursepriv;
6568: }
6569:
1.678 raeburn 6570: sub group_roleprivs {
6571: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6572: my $access = 1;
6573: my $now = time;
6574: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6575: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6576: if ($access) {
1.811 albertel 6577: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6578: $$allgroups{$course}{$group} .=':'.$group_privs;
6579: }
6580: }
1.567 raeburn 6581:
6582: sub standard_roleprivs {
6583: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6584: if (defined($pr{$trole.':s'})) {
6585: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6586: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6587: }
6588: if ($tdomain ne '') {
6589: if (defined($pr{$trole.':d'})) {
6590: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6591: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6592: }
6593: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6594: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6595: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6596: }
6597: }
6598: }
6599:
6600: sub set_userprivs {
1.1064 raeburn 6601: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6602: my $author=0;
6603: my $adv=0;
1.1172.2.91 raeburn 6604: my $rar=0;
1.678 raeburn 6605: my %grouproles = ();
6606: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6607: my @groupkeys;
1.1000 raeburn 6608: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6609: push(@groupkeys,$role);
6610: }
6611: if (ref($groups_roles) eq 'HASH') {
6612: foreach my $key (keys(%{$groups_roles})) {
6613: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6614: push(@groupkeys,$key);
6615: }
6616: }
6617: }
6618: if (@groupkeys > 0) {
6619: foreach my $role (@groupkeys) {
6620: my ($trole,$area,$sec,$extendedarea);
6621: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6622: $trole = $1;
6623: $area = $2;
6624: $sec = $3;
6625: $extendedarea = $area.$sec;
6626: if (exists($$allgroups{$area})) {
6627: foreach my $group (keys(%{$$allgroups{$area}})) {
6628: my $spec = $trole.'.'.$extendedarea;
6629: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6630: $$allgroups{$area}{$group};
1.1064 raeburn 6631: }
1.678 raeburn 6632: }
6633: }
6634: }
6635: }
6636: }
1.800 albertel 6637: foreach my $group (keys(%grouproles)) {
6638: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6639: }
1.800 albertel 6640: foreach my $role (keys(%{$allroles})) {
6641: my %thesepriv;
1.941 raeburn 6642: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6643: foreach my $item (split(/:/,$$allroles{$role})) {
6644: if ($item ne '') {
6645: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6646: if ($restrictions eq '') {
6647: $thesepriv{$privilege}='F';
6648: } elsif ($thesepriv{$privilege} ne 'F') {
6649: $thesepriv{$privilege}.=$restrictions;
6650: }
6651: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6652: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6653: }
6654: }
6655: my $thesestr='';
1.1104 raeburn 6656: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6657: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6658: }
6659: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6660: }
1.1172.2.91 raeburn 6661: return ($author,$adv,$rar);
1.567 raeburn 6662: }
6663:
1.994 raeburn 6664: sub role_status {
1.1104 raeburn 6665: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6666: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6667: my ($one,$two) = split(m{\./},$rolekey,2);
6668: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6669: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6670: $$where = '/'.$two;
1.994 raeburn 6671: $$trolecode=$$role.'.'.$$where;
6672: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6673: $$tstatus='is';
1.1104 raeburn 6674: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6675: $$tstatus='future';
1.1034 raeburn 6676: if ($$tstart<$now) {
6677: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6678: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6679: my (%allroles,%allgroups,$group_privs,
6680: %groups_roles,@rolecodes);
1.1002 raeburn 6681: my %userroles = (
6682: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6683: );
1.1064 raeburn 6684: @rolecodes = ('cm');
1.1002 raeburn 6685: my $spec=$$role.'.'.$$where;
6686: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6687: if ($$role =~ /^cr\//) {
6688: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6689: push(@rolecodes,'cr');
1.1002 raeburn 6690: } elsif ($$role eq 'gr') {
1.1064 raeburn 6691: push(@rolecodes,$$role);
1.1002 raeburn 6692: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6693: $env{'user.name'});
1.1064 raeburn 6694: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6695: (undef,my $group_privs) = split(/\//,$trole);
6696: $group_privs = &unescape($group_privs);
6697: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6698: 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 6699: &get_groups_roles($tdomain,$trest,
6700: \%course_roles,\@rolecodes,
6701: \%groups_roles);
1.1002 raeburn 6702: } else {
1.1064 raeburn 6703: push(@rolecodes,$$role);
1.1002 raeburn 6704: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6705: }
1.1172.2.91 raeburn 6706: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6707: \%groups_roles);
1.1064 raeburn 6708: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6709: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6710: }
6711: }
1.1034 raeburn 6712: $$tstatus = 'is';
1.1002 raeburn 6713: }
1.994 raeburn 6714: }
6715: if ($$tend) {
1.1104 raeburn 6716: if ($$tend<$update) {
1.994 raeburn 6717: $$tstatus='expired';
6718: } elsif ($$tend<$now) {
6719: $$tstatus='will_not';
6720: }
6721: }
6722: }
6723: }
6724: }
6725:
1.1104 raeburn 6726: sub get_groups_roles {
6727: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6728: return unless((ref($cdom_courseroles) eq 'HASH') &&
6729: (ref($rolecodes) eq 'ARRAY') &&
6730: (ref($groups_roles) eq 'HASH'));
6731: if (keys(%{$cdom_courseroles}) > 0) {
6732: my ($cnum) = ($rest =~ /^($match_courseid)/);
6733: if ($cdom ne '' && $cnum ne '') {
6734: foreach my $key (keys(%{$cdom_courseroles})) {
6735: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6736: my $crsrole = $1;
6737: my $crssec = $2;
6738: if ($crsrole =~ /^cr/) {
6739: unless (grep(/^cr$/,@{$rolecodes})) {
6740: push(@{$rolecodes},'cr');
6741: }
6742: } else {
6743: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6744: push(@{$rolecodes},$crsrole);
6745: }
6746: }
6747: my $rolekey = "$crsrole./$cdom/$cnum";
6748: if ($crssec ne '') {
6749: $rolekey .= "/$crssec";
6750: }
6751: $rolekey .= './';
6752: $groups_roles->{$rolekey} = $rolecodes;
6753: }
6754: }
6755: }
6756: }
6757: return;
6758: }
6759:
6760: sub delete_env_groupprivs {
6761: my ($where,$courseroles,$possroles) = @_;
6762: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6763: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6764: unless (ref($courseroles->{$udom}) eq 'HASH') {
6765: %{$courseroles->{$udom}} =
6766: &get_my_roles('','','userroles',['active'],
6767: $possroles,[$udom],1);
6768: }
6769: if (ref($courseroles->{$udom}) eq 'HASH') {
6770: foreach my $item (keys(%{$courseroles->{$udom}})) {
6771: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6772: my $area = '/'.$cdom.'/'.$cnum;
6773: my $privkey = "user.priv.$crsrole.$area";
6774: if ($crssec ne '') {
6775: $privkey .= '/'.$crssec;
6776: }
6777: $privkey .= ".$area/$group";
6778: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6779: }
6780: }
6781: return;
6782: }
6783:
1.994 raeburn 6784: sub check_adhoc_privs {
1.1172.2.86 raeburn 6785: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6786: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6787: if ($sec) {
6788: $cckey .= '/'.$sec;
6789: }
1.1172.2.9 raeburn 6790: my $setprivs;
1.994 raeburn 6791: if ($env{$cckey}) {
6792: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6793: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6794: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6795: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6796: $setprivs = 1;
1.994 raeburn 6797: }
6798: } else {
1.1172.2.87 raeburn 6799: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6800: $setprivs = 1;
1.994 raeburn 6801: }
1.1172.2.9 raeburn 6802: return $setprivs;
1.994 raeburn 6803: }
6804:
6805: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6806: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6807: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6808: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6809: if ($sec ne '') {
6810: $area .= '/'.$sec;
6811: }
1.994 raeburn 6812: my $spec = $role.'.'.$area;
6813: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6814: $env{'user.name'},1);
1.1172.2.84 raeburn 6815: my %rolehash = ();
1.1172.2.89 raeburn 6816: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6817: my $rolename = $1;
1.1172.2.84 raeburn 6818: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6819: my %domdef = &get_domain_defaults($dcdom);
6820: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6821: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6822: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6823: }
6824: }
1.1172.2.84 raeburn 6825: } else {
6826: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6827: }
1.1172.2.91 raeburn 6828: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6829: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6830: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6831: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6832: &appenv( {'request.role' => $spec,
6833: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6834: 'request.course.sec' => $sec,
1.1088 raeburn 6835: }
6836: );
6837: my $tadv=0;
6838: if (&allowed('adv') eq 'F') { $tadv=1; }
6839: &appenv({'request.role.adv' => $tadv});
6840: }
1.994 raeburn 6841: }
6842:
1.12 www 6843: # --------------------------------------------------------------- get interface
6844:
6845: sub get {
1.131 albertel 6846: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6847: my $items='';
1.800 albertel 6848: foreach my $item (@$storearr) {
6849: $items.=&escape($item).'&';
1.191 harris41 6850: }
1.12 www 6851: $items=~s/\&$//;
1.620 albertel 6852: if (!$udomain) { $udomain=$env{'user.domain'}; }
6853: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6854: my $uhome=&homeserver($uname,$udomain);
6855:
1.133 albertel 6856: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6857: my @pairs=split(/\&/,$rep);
1.273 albertel 6858: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6859: return @pairs;
6860: }
1.15 www 6861: my %returnhash=();
1.42 www 6862: my $i=0;
1.800 albertel 6863: foreach my $item (@$storearr) {
6864: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6865: $i++;
1.191 harris41 6866: }
1.15 www 6867: return %returnhash;
1.27 www 6868: }
6869:
6870: # --------------------------------------------------------------- del interface
6871:
6872: sub del {
1.133 albertel 6873: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6874: my $items='';
1.800 albertel 6875: foreach my $item (@$storearr) {
6876: $items.=&escape($item).'&';
1.191 harris41 6877: }
1.984 neumanie 6878:
1.27 www 6879: $items=~s/\&$//;
1.620 albertel 6880: if (!$udomain) { $udomain=$env{'user.domain'}; }
6881: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6882: my $uhome=&homeserver($uname,$udomain);
6883: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6884: }
6885:
6886: # -------------------------------------------------------------- dump interface
6887:
1.1172.2.22 raeburn 6888: sub unserialize {
6889: my ($rep, $escapedkeys) = @_;
6890:
6891: return {} if $rep =~ /^error/;
6892:
6893: my %returnhash=();
6894: foreach my $item (split(/\&/,$rep)) {
6895: my ($key, $value) = split(/=/, $item, 2);
6896: $key = unescape($key) unless $escapedkeys;
6897: next if $key =~ /^error: 2 /;
6898: $returnhash{$key} = &thaw_unescape($value);
6899: }
6900: return \%returnhash;
6901: }
6902:
6903: # see Lond::dump_with_regexp
6904: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6905: sub dump {
1.1172.2.22 raeburn 6906: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6907: if (!$udomain) { $udomain=$env{'user.domain'}; }
6908: if (!$uname) { $uname=$env{'user.name'}; }
6909: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6910:
1.1172.2.55 raeburn 6911: if ($regexp) {
6912: $regexp=&escape($regexp);
6913: } else {
6914: $regexp='.';
6915: }
1.1172.2.22 raeburn 6916: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6917: # user is hosted on this machine
1.1172.2.55 raeburn 6918: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6919: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6920: return %{&unserialize($reply, $escapedkeys)};
6921: }
1.1166 raeburn 6922: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6923: my @pairs=split(/\&/,$rep);
6924: my %returnhash=();
1.1098 foxr 6925: if (!($rep =~ /^error/ )) {
6926: foreach my $item (@pairs) {
6927: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6928: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6929: next if ($key =~ /^error: 2 /);
6930: $returnhash{$key}=&thaw_unescape($value);
6931: }
1.755 albertel 6932: }
6933: return %returnhash;
1.407 www 6934: }
6935:
1.1098 foxr 6936:
1.717 albertel 6937: # --------------------------------------------------------- dumpstore interface
6938:
6939: sub dumpstore {
6940: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6941: # same as dump but keys must be escaped. They may contain colon separated
6942: # lists of values that may themself contain colons (e.g. symbs).
6943: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6944: }
6945:
1.407 www 6946: # -------------------------------------------------------------- keys interface
6947:
6948: sub getkeys {
6949: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6950: if (!$udomain) { $udomain=$env{'user.domain'}; }
6951: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6952: my $uhome=&homeserver($uname,$udomain);
6953: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6954: my @keyarray=();
1.800 albertel 6955: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6956: next if ($key =~ /^error: 2 /);
1.800 albertel 6957: push(@keyarray,&unescape($key));
1.407 www 6958: }
6959: return @keyarray;
1.318 matthew 6960: }
6961:
1.319 matthew 6962: # --------------------------------------------------------------- currentdump
6963: sub currentdump {
1.328 matthew 6964: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6965: $courseid = $env{'request.course.id'} if (! defined($courseid));
6966: $sdom = $env{'user.domain'} if (! defined($sdom));
6967: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6968: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6969: my $rep;
6970:
6971: if (grep { $_ eq $uhome } current_machine_ids()) {
6972: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6973: $courseid)));
6974: } else {
6975: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6976: }
6977:
1.318 matthew 6978: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6979: #
1.318 matthew 6980: my %returnhash=();
1.319 matthew 6981: #
6982: if ($rep eq "unknown_cmd") {
6983: # an old lond will not know currentdump
6984: # Do a dump and make it look like a currentdump
1.822 albertel 6985: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6986: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6987: my %hash = @tmp;
6988: @tmp=();
1.424 matthew 6989: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6990: } else {
6991: my @pairs=split(/\&/,$rep);
1.800 albertel 6992: foreach my $pair (@pairs) {
6993: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6994: my ($symb,$param) = split(/:/,$key);
6995: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6996: &thaw_unescape($value);
1.319 matthew 6997: }
1.191 harris41 6998: }
1.12 www 6999: return %returnhash;
1.424 matthew 7000: }
7001:
7002: sub convert_dump_to_currentdump{
7003: my %hash = %{shift()};
7004: my %returnhash;
7005: # Code ripped from lond, essentially. The only difference
7006: # here is the unescaping done by lonnet::dump(). Conceivably
7007: # we might run in to problems with parameter names =~ /^v\./
7008: while (my ($key,$value) = each(%hash)) {
7009: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7010: $symb = &unescape($symb);
7011: $param = &unescape($param);
1.424 matthew 7012: next if ($v eq 'version' || $symb eq 'keys');
7013: next if (exists($returnhash{$symb}) &&
7014: exists($returnhash{$symb}->{$param}) &&
7015: $returnhash{$symb}->{'v.'.$param} > $v);
7016: $returnhash{$symb}->{$param}=$value;
7017: $returnhash{$symb}->{'v.'.$param}=$v;
7018: }
7019: #
7020: # Remove all of the keys in the hashes which keep track of
7021: # the version of the parameter.
7022: while (my ($symb,$param_hash) = each(%returnhash)) {
7023: # use a foreach because we are going to delete from the hash.
7024: foreach my $key (keys(%$param_hash)) {
7025: delete($param_hash->{$key}) if ($key =~ /^v\./);
7026: }
7027: }
7028: return \%returnhash;
1.12 www 7029: }
7030:
1.627 albertel 7031: # ------------------------------------------------------ critical inc interface
7032:
7033: sub cinc {
7034: return &inc(@_,'critical');
7035: }
7036:
1.449 matthew 7037: # --------------------------------------------------------------- inc interface
7038:
7039: sub inc {
1.627 albertel 7040: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7041: if (!$udomain) { $udomain=$env{'user.domain'}; }
7042: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7043: my $uhome=&homeserver($uname,$udomain);
7044: my $items='';
7045: if (! ref($store)) {
7046: # got a single value, so use that instead
7047: $items = &escape($store).'=&';
7048: } elsif (ref($store) eq 'SCALAR') {
7049: $items = &escape($$store).'=&';
7050: } elsif (ref($store) eq 'ARRAY') {
7051: $items = join('=&',map {&escape($_);} @{$store});
7052: } elsif (ref($store) eq 'HASH') {
7053: while (my($key,$value) = each(%{$store})) {
7054: $items.= &escape($key).'='.&escape($value).'&';
7055: }
7056: }
7057: $items=~s/\&$//;
1.627 albertel 7058: if ($critical) {
7059: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7060: } else {
7061: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7062: }
1.449 matthew 7063: }
7064:
1.12 www 7065: # --------------------------------------------------------------- put interface
7066:
7067: sub put {
1.134 albertel 7068: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7069: if (!$udomain) { $udomain=$env{'user.domain'}; }
7070: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7071: my $uhome=&homeserver($uname,$udomain);
1.12 www 7072: my $items='';
1.800 albertel 7073: foreach my $item (keys(%$storehash)) {
7074: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7075: }
1.12 www 7076: $items=~s/\&$//;
1.134 albertel 7077: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7078: }
7079:
1.631 albertel 7080: # ------------------------------------------------------------ newput interface
7081:
7082: sub newput {
7083: my ($namespace,$storehash,$udomain,$uname)=@_;
7084: if (!$udomain) { $udomain=$env{'user.domain'}; }
7085: if (!$uname) { $uname=$env{'user.name'}; }
7086: my $uhome=&homeserver($uname,$udomain);
7087: my $items='';
7088: foreach my $key (keys(%$storehash)) {
7089: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7090: }
7091: $items=~s/\&$//;
7092: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7093: }
7094:
7095: # --------------------------------------------------------- putstore interface
7096:
1.524 raeburn 7097: sub putstore {
1.1172.2.59 raeburn 7098: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7099: if (!$udomain) { $udomain=$env{'user.domain'}; }
7100: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7101: my $uhome=&homeserver($uname,$udomain);
7102: my $items='';
1.715 albertel 7103: foreach my $key (keys(%$storehash)) {
7104: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7105: }
1.715 albertel 7106: $items=~s/\&$//;
1.716 albertel 7107: my $esc_symb=&escape($symb);
7108: my $esc_v=&escape($version);
1.715 albertel 7109: my $reply =
1.716 albertel 7110: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7111: $uhome);
1.1172.2.59 raeburn 7112: if (($tolog) && ($reply eq 'ok')) {
7113: my $namevalue='';
7114: foreach my $key (keys(%{$storehash})) {
7115: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7116: }
1.1172.2.134 raeburn 7117: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7118: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7119: '&host='.&escape($perlvar{'lonHostID'}).
7120: '&version='.$esc_v.
7121: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7122: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7123: }
1.715 albertel 7124: if ($reply eq 'unknown_cmd') {
1.716 albertel 7125: # gfall back to way things use to be done
1.715 albertel 7126: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7127: $uname);
1.524 raeburn 7128: }
1.715 albertel 7129: return $reply;
7130: }
7131:
7132: sub old_putstore {
1.716 albertel 7133: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7134: if (!$udomain) { $udomain=$env{'user.domain'}; }
7135: if (!$uname) { $uname=$env{'user.name'}; }
7136: my $uhome=&homeserver($uname,$udomain);
7137: my %newstorehash;
1.800 albertel 7138: foreach my $item (keys(%$storehash)) {
7139: my $key = $version.':'.&escape($symb).':'.$item;
7140: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7141: }
7142: my $items='';
7143: my %allitems = ();
1.800 albertel 7144: foreach my $item (keys(%newstorehash)) {
7145: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7146: my $key = $1.':keys:'.$2;
7147: $allitems{$key} .= $3.':';
7148: }
1.800 albertel 7149: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7150: }
1.800 albertel 7151: foreach my $item (keys(%allitems)) {
7152: $allitems{$item} =~ s/\:$//;
7153: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7154: }
7155: $items=~s/\&$//;
7156: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7157: }
7158:
1.47 www 7159: # ------------------------------------------------------ critical put interface
7160:
7161: sub cput {
1.134 albertel 7162: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7163: if (!$udomain) { $udomain=$env{'user.domain'}; }
7164: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7165: my $uhome=&homeserver($uname,$udomain);
1.47 www 7166: my $items='';
1.800 albertel 7167: foreach my $item (keys(%$storehash)) {
7168: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7169: }
1.47 www 7170: $items=~s/\&$//;
1.134 albertel 7171: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7172: }
7173:
7174: # -------------------------------------------------------------- eget interface
7175:
7176: sub eget {
1.133 albertel 7177: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7178: my $items='';
1.800 albertel 7179: foreach my $item (@$storearr) {
7180: $items.=&escape($item).'&';
1.191 harris41 7181: }
1.12 www 7182: $items=~s/\&$//;
1.620 albertel 7183: if (!$udomain) { $udomain=$env{'user.domain'}; }
7184: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7185: my $uhome=&homeserver($uname,$udomain);
7186: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7187: my @pairs=split(/\&/,$rep);
7188: my %returnhash=();
1.42 www 7189: my $i=0;
1.800 albertel 7190: foreach my $item (@$storearr) {
7191: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7192: $i++;
1.191 harris41 7193: }
1.12 www 7194: return %returnhash;
7195: }
7196:
1.667 albertel 7197: # ------------------------------------------------------------ tmpput interface
7198: sub tmpput {
1.802 raeburn 7199: my ($storehash,$server,$context)=@_;
1.667 albertel 7200: my $items='';
1.800 albertel 7201: foreach my $item (keys(%$storehash)) {
7202: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7203: }
7204: $items=~s/\&$//;
1.802 raeburn 7205: if (defined($context)) {
7206: $items .= ':'.&escape($context);
7207: }
1.667 albertel 7208: return &reply("tmpput:$items",$server);
7209: }
7210:
7211: # ------------------------------------------------------------ tmpget interface
7212: sub tmpget {
1.688 albertel 7213: my ($token,$server)=@_;
7214: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7215: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7216: my %returnhash;
1.1172.2.85 raeburn 7217: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7218: return %returnhash;
7219: }
1.667 albertel 7220: foreach my $item (split(/\&/,$rep)) {
7221: my ($key,$value)=split(/=/,$item);
7222: $returnhash{&unescape($key)}=&thaw_unescape($value);
7223: }
7224: return %returnhash;
7225: }
7226:
1.1113 raeburn 7227: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7228: sub tmpdel {
7229: my ($token,$server)=@_;
7230: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7231: return &reply("tmpdel:$token",$server);
7232: }
7233:
1.1172.2.13 raeburn 7234: # ------------------------------------------------------------ get_timebased_id
7235:
7236: sub get_timebased_id {
7237: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7238: $maxtries) = @_;
7239: my ($newid,$error,$dellock);
7240: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7241: return ('','ok','invalid call to get suffix');
7242: }
7243:
7244: # set defaults for any optional args for which values were not supplied
7245: if ($who eq '') {
7246: $who = $env{'user.name'}.':'.$env{'user.domain'};
7247: }
7248: if (!$locktries) {
7249: $locktries = 3;
7250: }
7251: if (!$maxtries) {
7252: $maxtries = 10;
7253: }
7254:
7255: if (($cdom eq '') || ($cnum eq '')) {
7256: if ($env{'request.course.id'}) {
7257: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7258: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7259: }
7260: if (($cdom eq '') || ($cnum eq '')) {
7261: return ('','ok','call to get suffix not in course context');
7262: }
7263: }
7264:
7265: # construct locking item
7266: my $lockhash = {
7267: $prefix."\0".'locked_'.$keyid => $who,
7268: };
7269: my $tries = 0;
7270:
7271: # attempt to get lock on nohist_$namespace file
7272: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7273: while (($gotlock ne 'ok') && $tries <$locktries) {
7274: $tries ++;
7275: sleep 1;
7276: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7277: }
7278:
7279: # attempt to get unique identifier, based on current timestamp
7280: if ($gotlock eq 'ok') {
7281: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7282: my $id = time;
7283: $newid = $id;
1.1172.2.56 raeburn 7284: if ($idtype eq 'addcode') {
7285: $newid .= &sixnum_code();
7286: }
1.1172.2.13 raeburn 7287: my $idtries = 0;
7288: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7289: if ($idtype eq 'concat') {
7290: $newid = $id.$idtries;
1.1172.2.56 raeburn 7291: } elsif ($idtype eq 'addcode') {
7292: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7293: } else {
7294: $newid ++;
7295: }
7296: $idtries ++;
7297: }
7298: if (!exists($inuse{$prefix."\0".$newid})) {
7299: my %new_item = (
7300: $prefix."\0".$newid => $who,
7301: );
7302: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7303: $cdom,$cnum);
7304: if ($putresult ne 'ok') {
7305: undef($newid);
7306: $error = 'error saving new item: '.$putresult;
7307: }
7308: } else {
1.1172.2.56 raeburn 7309: undef($newid);
1.1172.2.13 raeburn 7310: $error = ('error: no unique suffix available for the new item ');
7311: }
7312: # remove lock
7313: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7314: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7315: } else {
7316: $error = "error: could not obtain lockfile\n";
7317: $dellock = 'ok';
1.1172.2.58 raeburn 7318: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7319: $dellock = 'nolock';
7320: }
1.1172.2.13 raeburn 7321: }
7322: return ($newid,$dellock,$error);
7323: }
7324:
1.1172.2.56 raeburn 7325: sub sixnum_code {
7326: my $code;
7327: for (0..6) {
7328: $code .= int( rand(9) );
7329: }
7330: return $code;
7331: }
7332:
1.765 albertel 7333: # -------------------------------------------------- portfolio access checking
7334:
7335: sub portfolio_access {
1.1172.2.77 raeburn 7336: my ($requrl,$clientip) = @_;
1.765 albertel 7337: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7338: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7339: if ($result) {
7340: my %setters;
7341: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142 raeburn 7342: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7343: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7344: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7345: return 'B';
7346: }
7347: } else {
1.1172.2.142 raeburn 7348: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
7349: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7350: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7351: return 'B';
7352: }
7353: }
7354: }
1.765 albertel 7355: if ($result eq 'ok') {
1.766 albertel 7356: return 'F';
1.765 albertel 7357: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7358: return 'A';
1.765 albertel 7359: }
1.766 albertel 7360: return '';
1.765 albertel 7361: }
7362:
7363: sub get_portfolio_access {
1.1172.2.77 raeburn 7364: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7365:
7366: if (!ref($access_hash)) {
7367: my $current_perms = &get_portfile_permissions($udom,$unum);
7368: my %access_controls = &get_access_controls($current_perms,$group,
7369: $file_name);
7370: $access_hash = $access_controls{$file_name};
7371: }
7372:
1.1172.2.77 raeburn 7373: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7374: my $now = time;
7375: if (ref($access_hash) eq 'HASH') {
7376: foreach my $key (keys(%{$access_hash})) {
7377: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7378: if ($start > $now) {
7379: next;
7380: }
7381: if ($end && $end<$now) {
7382: next;
7383: }
7384: if ($scope eq 'public') {
7385: $public = $key;
7386: last;
7387: } elsif ($scope eq 'guest') {
7388: $guest = $key;
7389: } elsif ($scope eq 'domains') {
7390: push(@domains,$key);
7391: } elsif ($scope eq 'users') {
7392: push(@users,$key);
7393: } elsif ($scope eq 'course') {
7394: push(@courses,$key);
7395: } elsif ($scope eq 'group') {
7396: push(@groups,$key);
1.1172.2.77 raeburn 7397: } elsif ($scope eq 'ip') {
7398: push(@ips,$key);
1.765 albertel 7399: }
7400: }
7401: if ($public) {
7402: return 'ok';
1.1172.2.77 raeburn 7403: } elsif (@ips > 0) {
7404: my $allowed;
7405: foreach my $ipkey (@ips) {
7406: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7407: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7408: $allowed = 1;
7409: last;
7410: }
7411: }
7412: }
7413: if ($allowed) {
7414: return 'ok';
7415: }
1.765 albertel 7416: }
7417: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7418: if ($guest) {
7419: return $guest;
7420: }
7421: } else {
7422: if (@domains > 0) {
7423: foreach my $domkey (@domains) {
7424: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7425: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7426: return 'ok';
7427: }
7428: }
7429: }
7430: }
7431: if (@users > 0) {
7432: foreach my $userkey (@users) {
1.865 raeburn 7433: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7434: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7435: if (ref($item) eq 'HASH') {
7436: if (($item->{'uname'} eq $env{'user.name'}) &&
7437: ($item->{'udom'} eq $env{'user.domain'})) {
7438: return 'ok';
7439: }
7440: }
7441: }
7442: }
1.765 albertel 7443: }
7444: }
7445: my %roleshash;
7446: my @courses_and_groups = @courses;
7447: push(@courses_and_groups,@groups);
7448: if (@courses_and_groups > 0) {
7449: my (%allgroups,%allroles);
7450: my ($start,$end,$role,$sec,$group);
7451: foreach my $envkey (%env) {
1.1060 raeburn 7452: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7453: my $cid = $2.'_'.$3;
7454: if ($1 eq 'gr') {
7455: $group = $4;
7456: $allgroups{$cid}{$group} = $env{$envkey};
7457: } else {
7458: if ($4 eq '') {
7459: $sec = 'none';
7460: } else {
7461: $sec = $4;
7462: }
7463: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7464: }
1.811 albertel 7465: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7466: my $cid = $2.'_'.$3;
7467: if ($4 eq '') {
7468: $sec = 'none';
7469: } else {
7470: $sec = $4;
7471: }
7472: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7473: }
7474: }
7475: if (keys(%allroles) == 0) {
7476: return;
7477: }
7478: foreach my $key (@courses_and_groups) {
7479: my %content = %{$$access_hash{$key}};
7480: my $cnum = $content{'number'};
7481: my $cdom = $content{'domain'};
7482: my $cid = $cdom.'_'.$cnum;
7483: if (!exists($allroles{$cid})) {
7484: next;
7485: }
7486: foreach my $role_id (keys(%{$content{'roles'}})) {
7487: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7488: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7489: my @status = @{$content{'roles'}{$role_id}{'access'}};
7490: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7491: foreach my $role (keys(%{$allroles{$cid}})) {
7492: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7493: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7494: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7495: if (grep/^all$/,@sections) {
7496: return 'ok';
7497: } else {
7498: if (grep/^$sec$/,@sections) {
7499: return 'ok';
7500: }
7501: }
7502: }
7503: }
7504: if (keys(%{$allgroups{$cid}}) == 0) {
7505: if (grep/^none$/,@groups) {
7506: return 'ok';
7507: }
7508: } else {
7509: if (grep/^all$/,@groups) {
7510: return 'ok';
7511: }
7512: foreach my $group (keys(%{$allgroups{$cid}})) {
7513: if (grep/^$group$/,@groups) {
7514: return 'ok';
7515: }
7516: }
7517: }
7518: }
7519: }
7520: }
7521: }
7522: }
7523: if ($guest) {
7524: return $guest;
7525: }
7526: }
7527: }
7528: return;
7529: }
7530:
7531: sub course_group_datechecker {
7532: my ($dates,$now,$status) = @_;
7533: my ($start,$end) = split(/\./,$dates);
7534: if (!$start && !$end) {
7535: return 'ok';
7536: }
7537: if (grep/^active$/,@{$status}) {
7538: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7539: return 'ok';
7540: }
7541: }
7542: if (grep/^previous$/,@{$status}) {
7543: if ($end > $now ) {
7544: return 'ok';
7545: }
7546: }
7547: if (grep/^future$/,@{$status}) {
7548: if ($start > $now) {
7549: return 'ok';
7550: }
7551: }
7552: return;
7553: }
7554:
7555: sub parse_portfolio_url {
7556: my ($url) = @_;
7557:
7558: my ($type,$udom,$unum,$group,$file_name);
7559:
1.823 albertel 7560: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7561: $type = 1;
7562: $udom = $1;
7563: $unum = $2;
7564: $file_name = $3;
1.823 albertel 7565: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7566: $type = 2;
7567: $udom = $1;
7568: $unum = $2;
7569: $group = $3;
7570: $file_name = $3.'/'.$4;
7571: }
7572: if (wantarray) {
7573: return ($type,$udom,$unum,$file_name,$group);
7574: }
7575: return $type;
7576: }
7577:
7578: sub is_portfolio_url {
7579: my ($url) = @_;
7580: return scalar(&parse_portfolio_url($url));
7581: }
7582:
1.798 raeburn 7583: sub is_portfolio_file {
7584: my ($file) = @_;
1.820 raeburn 7585: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7586: return 1;
7587: }
7588: return;
7589: }
7590:
1.976 raeburn 7591: sub usertools_access {
1.1084 raeburn 7592: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7593: my ($access,%tools);
7594: if ($context eq '') {
7595: $context = 'tools';
7596: }
7597: if ($context eq 'requestcourses') {
7598: %tools = (
7599: official => 1,
7600: unofficial => 1,
1.1006 raeburn 7601: community => 1,
1.1172.2.37 raeburn 7602: textbook => 1,
1.985 raeburn 7603: );
1.1172.2.9 raeburn 7604: } elsif ($context eq 'requestauthor') {
7605: %tools = (
7606: requestauthor => 1,
7607: );
1.985 raeburn 7608: } else {
7609: %tools = (
7610: aboutme => 1,
7611: blog => 1,
1.1172.2.6 raeburn 7612: webdav => 1,
1.985 raeburn 7613: portfolio => 1,
7614: );
7615: }
1.976 raeburn 7616: return if (!defined($tools{$tool}));
7617:
1.1172.2.35 raeburn 7618: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7619: $udom = $env{'user.domain'};
7620: $uname = $env{'user.name'};
7621: }
7622:
1.978 raeburn 7623: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7624: if ($action ne 'reload') {
1.985 raeburn 7625: if ($context eq 'requestcourses') {
7626: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7627: } elsif ($context eq 'requestauthor') {
7628: return $env{'environment.canrequest.author'};
1.985 raeburn 7629: } else {
7630: return $env{'environment.availabletools.'.$tool};
7631: }
7632: }
1.976 raeburn 7633: }
7634:
1.1172.2.9 raeburn 7635: my ($toolstatus,$inststatus,$envkey);
7636: if ($context eq 'requestauthor') {
7637: $envkey = $context;
7638: } else {
7639: $envkey = $context.'.'.$tool;
7640: }
1.976 raeburn 7641:
1.985 raeburn 7642: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7643: ($action ne 'reload')) {
1.1172.2.9 raeburn 7644: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7645: $inststatus = $env{'environment.inststatus'};
7646: } else {
1.1084 raeburn 7647: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7648: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7649: $inststatus = $userenvref->{'inststatus'};
7650: } else {
1.1172.2.9 raeburn 7651: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7652: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7653: $inststatus = $userenv{'inststatus'};
7654: }
1.976 raeburn 7655: }
7656:
7657: if ($toolstatus ne '') {
7658: if ($toolstatus) {
7659: $access = 1;
7660: } else {
7661: $access = 0;
7662: }
7663: return $access;
7664: }
7665:
1.1084 raeburn 7666: my ($is_adv,%domdef);
7667: if (ref($is_advref) eq 'HASH') {
7668: $is_adv = $is_advref->{'is_adv'};
7669: } else {
7670: $is_adv = &is_advanced_user($udom,$uname);
7671: }
7672: if (ref($domdefref) eq 'HASH') {
7673: %domdef = %{$domdefref};
7674: } else {
7675: %domdef = &get_domain_defaults($udom);
7676: }
1.976 raeburn 7677: if (ref($domdef{$tool}) eq 'HASH') {
7678: if ($is_adv) {
7679: if ($domdef{$tool}{'_LC_adv'} ne '') {
7680: if ($domdef{$tool}{'_LC_adv'}) {
7681: $access = 1;
7682: } else {
7683: $access = 0;
7684: }
7685: return $access;
7686: }
7687: }
7688: if ($inststatus ne '') {
7689: my ($hasaccess,$hasnoaccess);
7690: foreach my $affiliation (split(/:/,$inststatus)) {
7691: if ($domdef{$tool}{$affiliation} ne '') {
7692: if ($domdef{$tool}{$affiliation}) {
7693: $hasaccess = 1;
7694: } else {
7695: $hasnoaccess = 1;
7696: }
7697: }
7698: }
7699: if ($hasaccess || $hasnoaccess) {
7700: if ($hasaccess) {
7701: $access = 1;
7702: } elsif ($hasnoaccess) {
7703: $access = 0;
7704: }
7705: return $access;
7706: }
7707: } else {
7708: if ($domdef{$tool}{'default'} ne '') {
7709: if ($domdef{$tool}{'default'}) {
7710: $access = 1;
7711: } elsif ($domdef{$tool}{'default'} == 0) {
7712: $access = 0;
7713: }
7714: return $access;
7715: }
7716: }
7717: } else {
1.1172.2.6 raeburn 7718: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7719: $access = 1;
7720: } else {
7721: $access = 0;
7722: }
1.976 raeburn 7723: return $access;
7724: }
7725: }
7726:
1.1050 raeburn 7727: sub is_course_owner {
7728: my ($cdom,$cnum,$udom,$uname) = @_;
7729: if (($udom eq '') || ($uname eq '')) {
7730: $udom = $env{'user.domain'};
7731: $uname = $env{'user.name'};
7732: }
7733: unless (($udom eq '') || ($uname eq '')) {
7734: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7735: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7736: return 1;
7737: } else {
7738: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7739: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7740: return 1;
7741: }
7742: }
7743: }
7744: }
7745: return;
7746: }
7747:
1.976 raeburn 7748: sub is_advanced_user {
7749: my ($udom,$uname) = @_;
1.1085 raeburn 7750: if ($udom ne '' && $uname ne '') {
7751: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7752: if (wantarray) {
7753: return ($env{'user.adv'},$env{'user.author'});
7754: } else {
7755: return $env{'user.adv'};
7756: }
1.1085 raeburn 7757: }
7758: }
1.976 raeburn 7759: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7760: my %allroles;
1.1128 raeburn 7761: my ($is_adv,$is_author);
1.976 raeburn 7762: foreach my $role (keys(%roleshash)) {
7763: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7764: my $area = '/'.$tdomain.'/'.$trest;
7765: if ($sec ne '') {
7766: $area .= '/'.$sec;
7767: }
7768: if (($area ne '') && ($trole ne '')) {
7769: my $spec=$trole.'.'.$area;
7770: if ($trole =~ /^cr\//) {
7771: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7772: } elsif ($trole ne 'gr') {
7773: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7774: }
1.1128 raeburn 7775: if ($trole eq 'au') {
7776: $is_author = 1;
7777: }
1.976 raeburn 7778: }
7779: }
7780: foreach my $role (keys(%allroles)) {
7781: last if ($is_adv);
7782: foreach my $item (split(/:/,$allroles{$role})) {
7783: if ($item ne '') {
7784: my ($privilege,$restrictions)=split(/&/,$item);
7785: if ($privilege eq 'adv') {
7786: $is_adv = 1;
7787: last;
7788: }
7789: }
7790: }
7791: }
1.1128 raeburn 7792: if (wantarray) {
7793: return ($is_adv,$is_author);
7794: }
1.976 raeburn 7795: return $is_adv;
7796: }
1.798 raeburn 7797:
1.1035 raeburn 7798: sub check_can_request {
1.1036 raeburn 7799: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7800: my $canreq = 0;
7801: my ($types,$typename) = &Apache::loncommon::course_types();
7802: my @options = ('approval','validate','autolimit');
7803: my $optregex = join('|',@options);
7804: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7805: foreach my $type (@{$types}) {
7806: if (&usertools_access($env{'user.name'},
7807: $env{'user.domain'},
7808: $type,undef,'requestcourses')) {
7809: $canreq ++;
1.1036 raeburn 7810: if (ref($request_domains) eq 'HASH') {
7811: push(@{$request_domains->{$type}},$env{'user.domain'});
7812: }
1.1035 raeburn 7813: if ($dom eq $env{'user.domain'}) {
7814: $can_request->{$type} = 1;
7815: }
7816: }
7817: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7818: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7819: if (@curr > 0) {
1.1036 raeburn 7820: foreach my $item (@curr) {
7821: if (ref($request_domains) eq 'HASH') {
7822: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7823: if ($otherdom ne '') {
7824: if (ref($request_domains->{$type}) eq 'ARRAY') {
7825: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7826: push(@{$request_domains->{$type}},$otherdom);
7827: }
7828: } else {
7829: push(@{$request_domains->{$type}},$otherdom);
7830: }
7831: }
7832: }
7833: }
7834: unless($dom eq $env{'user.domain'}) {
7835: $canreq ++;
1.1035 raeburn 7836: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7837: $can_request->{$type} = 1;
7838: }
7839: }
7840: }
7841: }
7842: }
7843: }
7844: return $canreq;
7845: }
7846:
1.341 www 7847: # ---------------------------------------------- Custom access rule evaluation
7848:
7849: sub customaccess {
7850: my ($priv,$uri)=@_;
1.807 albertel 7851: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7852: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7853: $udom = &LONCAPA::clean_domain($udom);
7854: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7855: my $access=0;
1.800 albertel 7856: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7857: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7858: if ($type eq 'user') {
7859: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7860: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7861: if ($tdom) {
7862: if ($tdom ne $env{'user.domain'}) { next; }
7863: }
1.896 albertel 7864: if ($tuname) {
7865: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7866: }
7867: $access=($effect eq 'allow');
7868: last;
7869: }
7870: } else {
7871: if ($role) {
7872: if ($role ne $urole) { next; }
7873: }
7874: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7875: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7876: if ($tdom) {
7877: if ($tdom ne $udom) { next; }
7878: }
7879: if ($tcrs) {
7880: if ($tcrs ne $ucrs) { next; }
7881: }
7882: if ($tsec) {
7883: if ($tsec ne $usec) { next; }
7884: }
7885: $access=($effect eq 'allow');
7886: last;
7887: }
7888: if ($realm eq '' && $role eq '') {
7889: $access=($effect eq 'allow');
7890: }
1.402 bowersj2 7891: }
1.341 www 7892: }
7893: return $access;
7894: }
7895:
1.103 harris41 7896: # ------------------------------------------------- Check for a user privilege
1.12 www 7897:
7898: sub allowed {
1.1172.2.126 raeburn 7899: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7900: my $ver_orguri=$uri;
1.439 www 7901: $uri=&deversion($uri);
1.152 www 7902: my $orguri=$uri;
1.52 www 7903: $uri=&declutter($uri);
1.809 raeburn 7904:
1.810 raeburn 7905: if ($priv eq 'evb') {
7906: # Evade communication block restrictions for specified role in a course
7907: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7908: return $1;
7909: } else {
7910: return;
7911: }
7912: }
7913:
1.620 albertel 7914: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7915: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7916: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7917: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7918: && ($priv eq 'bre')) {
1.14 www 7919: return 'F';
1.159 www 7920: }
7921:
1.545 banghart 7922: # Free bre access to user's own portfolio contents
1.714 raeburn 7923: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7924: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7925: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7926: my %setters;
1.1172.2.142 raeburn 7927: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7928: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7929: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7930: return 'B';
7931: } else {
7932: return 'F';
7933: }
1.545 banghart 7934: }
7935:
1.762 raeburn 7936: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7937: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7938: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7939: if (exists($env{'request.course.id'})) {
7940: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7941: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7942: if (($domain eq $cdom) && ($name eq $cnum)) {
7943: my $courseprivid=$env{'request.course.id'};
7944: $courseprivid=~s/\_/\//;
7945: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7946: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7947: return $1;
1.762 raeburn 7948: } else {
7949: if ($env{'request.course.sec'}) {
7950: $courseprivid.='/'.$env{'request.course.sec'};
7951: }
7952: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7953: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7954: return $2;
7955: }
1.714 raeburn 7956: }
7957: }
7958: }
7959: }
7960:
1.159 www 7961: # Free bre to public access
7962:
7963: if ($priv eq 'bre') {
1.238 www 7964: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7965: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7966: return 'F';
7967: }
1.238 www 7968: if ($copyright eq 'priv') {
7969: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7970: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7971: return '';
7972: }
7973: }
7974: if ($copyright eq 'domain') {
7975: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7976: unless (($env{'user.domain'} eq $1) ||
7977: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7978: return '';
7979: }
1.262 matthew 7980: }
1.620 albertel 7981: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7982: # Library role, so allow browsing of resources in this domain.
7983: return 'F';
1.238 www 7984: }
1.341 www 7985: if ($copyright eq 'custom') {
7986: unless (&customaccess($priv,$uri)) { return ''; }
7987: }
1.14 www 7988: }
1.264 matthew 7989: # Domain coordinator is trying to create a course
1.620 albertel 7990: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7991: # uri is the requested domain in this case.
7992: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7993: # a role of dc for the domain in question.
1.620 albertel 7994: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7995: }
1.29 www 7996:
1.52 www 7997: my $thisallowed='';
7998: my $statecond=0;
7999: my $courseprivid='';
8000:
1.1039 raeburn 8001: my $ownaccess;
1.1043 raeburn 8002: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8003: if (($priv eq 'bro') && ($env{'user.author'})) {
8004: if ($uri eq '') {
8005: $ownaccess = 1;
8006: } else {
8007: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8008: my $udom = $env{'user.domain'};
8009: my $uname = $env{'user.name'};
8010: if ($uri =~ m{^\Q$udom\E/?$}) {
8011: $ownaccess = 1;
1.1040 raeburn 8012: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8013: unless ($uri =~ m{\.\./}) {
8014: $ownaccess = 1;
8015: }
8016: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8017: my $now = time;
8018: if ($uri =~ m{^([^/]+)/?$}) {
8019: my $adom = $1;
8020: foreach my $key (keys(%env)) {
1.1042 raeburn 8021: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142 raeburn 8022: my ($start,$end) = split(/\./,$env{$key});
8023: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8024: $ownaccess = 1;
8025: last;
8026: }
8027: }
8028: }
8029: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8030: my $adom = $1;
8031: my $aname = $2;
1.1042 raeburn 8032: foreach my $role ('ca','aa') {
8033: if ($env{"user.role.$role./$adom/$aname"}) {
8034: my ($start,$end) =
1.1172.2.142 raeburn 8035: split(/\./,$env{"user.role.$role./$adom/$aname"});
8036: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8037: $ownaccess = 1;
8038: last;
8039: }
1.1039 raeburn 8040: }
8041: }
8042: }
8043: }
8044: }
8045: }
8046: }
8047:
1.52 www 8048: # Course
8049:
1.620 albertel 8050: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8051: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8052: $thisallowed.=$1;
8053: }
1.52 www 8054: }
1.29 www 8055:
1.52 www 8056: # Domain
8057:
1.620 albertel 8058: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8059: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8060: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8061: $thisallowed.=$1;
8062: }
1.12 www 8063: }
1.52 www 8064:
1.1141 raeburn 8065: # User who is not author or co-author might still be able to edit
8066: # resource of an author in the domain (e.g., if Domain Coordinator).
8067: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8068: (&allowed('mdc',$env{'request.course.id'}))) {
8069: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8070: $thisallowed.=$1;
8071: }
8072: }
8073:
1.52 www 8074: # Course: uri itself is a course
1.66 www 8075: my $courseuri=$uri;
8076: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8077: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8078:
1.620 albertel 8079: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8080: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8081: if ($priv eq 'mip') {
8082: my $rem = $1;
8083: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8084: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8085: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8086: if ($cdom ne '') {
8087: my %passwdconf = &get_passwdconf($cdom);
8088: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8089: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8090: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8091: my @inststatuses = split(':',$env{'environment.inststatus'});
8092: unless (@inststatuses) {
8093: @inststatuses = ('default');
8094: }
8095: foreach my $status (@inststatuses) {
8096: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8097: $thisallowed.=$rem;
8098: }
8099: }
8100: }
8101: }
8102: }
8103: }
8104: }
8105: } else {
8106: unless (($priv eq 'bro') && (!$ownaccess)) {
8107: $thisallowed.=$1;
8108: }
1.1039 raeburn 8109: }
1.12 www 8110: }
1.29 www 8111:
1.665 albertel 8112: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8113: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8114: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8115: $thisallowed='';
1.671 raeburn 8116: my ($match)=&is_on_map($uri);
8117: if ($match) {
8118: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8119: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8120: my $value = $1;
8121: if ($noblockcheck) {
8122: $thisallowed.=$value;
1.1162 raeburn 8123: } else {
1.1172.2.126 raeburn 8124: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8125: if (@blockers > 0) {
8126: $thisallowed = 'B';
8127: } else {
8128: $thisallowed.=$value;
8129: }
1.1162 raeburn 8130: }
1.671 raeburn 8131: }
8132: } else {
1.705 albertel 8133: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8134: if ($refuri) {
8135: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8136: $thisallowed='F';
1.671 raeburn 8137: } else {
8138: $refuri=&declutter($refuri);
8139: my ($match) = &is_on_map($refuri);
8140: if ($match) {
1.1172.2.65 raeburn 8141: if ($noblockcheck) {
1.1162 raeburn 8142: $thisallowed='F';
1.1172.2.65 raeburn 8143: } else {
1.1172.2.127 raeburn 8144: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8145: if (@blockers > 0) {
8146: $thisallowed = 'B';
8147: } else {
8148: $thisallowed='F';
8149: }
1.1162 raeburn 8150: }
1.671 raeburn 8151: }
1.669 raeburn 8152: }
1.671 raeburn 8153: }
8154: }
1.314 www 8155: }
1.492 albertel 8156:
1.766 albertel 8157: if ($priv eq 'bre'
8158: && $thisallowed ne 'F'
8159: && $thisallowed ne '2'
8160: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8161: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8162: }
8163:
1.52 www 8164: # Full access at system, domain or course-wide level? Exit.
1.29 www 8165: if ($thisallowed=~/F/) {
8166: return 'F';
8167: }
8168:
1.52 www 8169: # If this is generating or modifying users, exit with special codes
1.29 www 8170:
1.643 www 8171: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8172: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8173: my ($audom,$auname)=split('/',$uri);
1.643 www 8174: # no author name given, so this just checks on the general right to make a co-author in this domain
8175: unless ($auname) { return $thisallowed; }
8176: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8177: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8178: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8179: ($audom ne $env{'request.role.domain'}))) { return ''; }
8180: }
1.52 www 8181: return $thisallowed;
8182: }
8183: #
1.103 harris41 8184: # Gathered so far: system, domain and course wide privileges
1.52 www 8185: #
8186: # Course: See if uri or referer is an individual resource that is part of
8187: # the course
8188:
1.620 albertel 8189: if ($env{'request.course.id'}) {
1.232 www 8190:
1.1172.2.115 raeburn 8191: # If this is modifying password (internal auth) domains must match for user and user's role.
8192:
8193: if ($priv eq 'mip') {
8194: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8195: return $thisallowed;
8196: } else {
8197: return '';
8198: }
8199: }
8200:
1.620 albertel 8201: $courseprivid=$env{'request.course.id'};
8202: if ($env{'request.course.sec'}) {
8203: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8204: }
8205: $courseprivid=~s/\_/\//;
8206: my $checkreferer=1;
1.232 www 8207: my ($match,$cond)=&is_on_map($uri);
8208: if ($match) {
8209: $statecond=$cond;
1.620 albertel 8210: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8211: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8212: my $value = $1;
8213: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8214: if ($noblockcheck) {
1.1162 raeburn 8215: $thisallowed.=$value;
1.1172.2.65 raeburn 8216: } else {
1.1172.2.126 raeburn 8217: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8218: if (@blockers > 0) {
8219: $thisallowed = 'B';
8220: } else {
8221: $thisallowed.=$value;
8222: }
1.1162 raeburn 8223: }
8224: } else {
8225: $thisallowed.=$value;
8226: }
1.52 www 8227: $checkreferer=0;
8228: }
1.29 www 8229: }
1.1172.2.126 raeburn 8230:
1.148 www 8231: if ($checkreferer) {
1.620 albertel 8232: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8233: unless ($refuri) {
1.800 albertel 8234: foreach my $key (keys(%env)) {
8235: if ($key=~/^httpref\..*\*/) {
8236: my $pattern=$key;
1.156 www 8237: $pattern=~s/^httpref\.\/res\///;
1.148 www 8238: $pattern=~s/\*/\[\^\/\]\+/g;
8239: $pattern=~s/\//\\\//g;
1.152 www 8240: if ($orguri=~/$pattern/) {
1.800 albertel 8241: $refuri=$env{$key};
1.148 www 8242: }
8243: }
1.191 harris41 8244: }
1.148 www 8245: }
1.232 www 8246:
1.148 www 8247: if ($refuri) {
1.152 www 8248: $refuri=&declutter($refuri);
1.232 www 8249: my ($match,$cond)=&is_on_map($refuri);
8250: if ($match) {
8251: my $refstatecond=$cond;
1.620 albertel 8252: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8253: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8254: my $value = $1;
8255: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8256: if ($noblockcheck) {
1.1162 raeburn 8257: $thisallowed.=$value;
1.1172.2.65 raeburn 8258: } else {
1.1172.2.127 raeburn 8259: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8260: if (@blockers > 0) {
8261: $thisallowed = 'B';
8262: } else {
8263: $thisallowed.=$value;
8264: }
1.1162 raeburn 8265: }
8266: } else {
8267: $thisallowed.=$value;
8268: }
1.53 www 8269: $uri=$refuri;
8270: $statecond=$refstatecond;
1.52 www 8271: }
8272: }
1.148 www 8273: }
1.29 www 8274: }
1.52 www 8275: }
1.29 www 8276:
1.52 www 8277: #
1.103 harris41 8278: # Gathered now: all privileges that could apply, and condition number
1.52 www 8279: #
8280: #
8281: # Full or no access?
8282: #
1.29 www 8283:
1.52 www 8284: if ($thisallowed=~/F/) {
8285: return 'F';
8286: }
1.29 www 8287:
1.52 www 8288: unless ($thisallowed) {
8289: return '';
8290: }
1.29 www 8291:
1.52 www 8292: # Restrictions exist, deal with them
8293: #
8294: # C:according to course preferences
8295: # R:according to resource settings
8296: # L:unless locked
8297: # X:according to user session state
8298: #
8299:
8300: # Possibly locked functionality, check all courses
1.1172.2.142 raeburn 8301: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8302: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142 raeburn 8303: # courses, and 2 minutes for current course, in which user has st or ta role
8304: # which is neither expired nor a future role (unless current course).
1.52 www 8305:
1.1172.2.142 raeburn 8306: my ($needlockcheck,$now,$crsonly);
1.52 www 8307: if ($thisallowed=~/L/) {
1.1172.2.142 raeburn 8308: $now = time;
8309: if ($priv eq 'bre') {
8310: if ($uri ne '') {
8311: if ($orguri =~ m{^/+res/}) {
8312: if ($uri =~ m{^lib/templates/}) {
8313: if ($env{'request.course.id'}) {
8314: $crsonly = 1;
8315: $needlockcheck = 1;
8316: }
8317: } else {
8318: $needlockcheck = 1;
8319: }
8320: } elsif ($env{'request.course.id'}) {
8321: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8322: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8323: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8324: $crsonly = 1;
8325: }
8326: $needlockcheck = 1;
8327: }
8328: }
8329: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8330: $needlockcheck = 1;
8331: }
8332: }
8333: if ($needlockcheck) {
8334: foreach my $envkey (keys(%env)) {
1.54 www 8335: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8336: my $courseid=$2;
8337: my $roleid=$1.'.'.$2;
1.92 www 8338: $courseid=~s/^\///;
1.1172.2.142 raeburn 8339: unless ($env{'request.role'} eq $roleid) {
8340: my ($start,$end) = split(/\./,$env{$envkey});
8341: next unless (($now >= $start) && (!$end || $end > $now));
8342: }
1.54 www 8343: my $expiretime=600;
1.620 albertel 8344: if ($env{'request.role'} eq $roleid) {
1.54 www 8345: $expiretime=120;
8346: }
8347: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8348: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8349: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8350: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8351: }
1.620 albertel 8352: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8353: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8354: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8355: &log($env{'user.domain'},$env{'user.name'},
8356: $env{'user.home'},
1.57 www 8357: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8358: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8359: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8360: return '';
8361: }
8362: }
1.620 albertel 8363: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8364: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142 raeburn 8365: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8366: &log($env{'user.domain'},$env{'user.name'},
8367: $env{'user.home'},
1.57 www 8368: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8369: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8370: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8371: return '';
8372: }
8373: }
8374: }
1.29 www 8375: }
1.52 www 8376: }
1.1172.2.126 raeburn 8377:
1.52 www 8378: #
8379: # Rest of the restrictions depend on selected course
8380: #
8381:
1.620 albertel 8382: unless ($env{'request.course.id'}) {
1.766 albertel 8383: if ($thisallowed eq 'A') {
8384: return 'A';
1.814 raeburn 8385: } elsif ($thisallowed eq 'B') {
8386: return 'B';
1.766 albertel 8387: } else {
8388: return '1';
8389: }
1.52 www 8390: }
1.29 www 8391:
1.52 www 8392: #
8393: # Now user is definitely in a course
8394: #
1.53 www 8395:
8396:
8397: # Course preferences
8398:
8399: if ($thisallowed=~/C/) {
1.620 albertel 8400: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8401: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8402: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8403: =~/\Q$rolecode\E/) {
1.1103 raeburn 8404: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8405: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8406: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8407: $env{'request.course.id'});
8408: }
1.237 www 8409: return '';
8410: }
8411:
1.620 albertel 8412: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8413: =~/\Q$unamedom\E/) {
1.1103 raeburn 8414: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8415: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8416: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8417: $env{'request.course.id'});
8418: }
1.54 www 8419: return '';
8420: }
1.53 www 8421: }
8422:
8423: # Resource preferences
8424:
8425: if ($thisallowed=~/R/) {
1.620 albertel 8426: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8427: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8428: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8429: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8430: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8431: }
8432: return '';
1.54 www 8433: }
1.53 www 8434: }
1.30 www 8435:
1.246 www 8436: # Restricted by state or randomout?
1.30 www 8437:
1.52 www 8438: if ($thisallowed=~/X/) {
1.620 albertel 8439: if ($env{'acc.randomout'}) {
1.579 albertel 8440: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8441: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8442: return '';
8443: }
1.247 www 8444: }
8445: if (&condval($statecond)) {
1.52 www 8446: return '2';
8447: } else {
8448: return '';
8449: }
8450: }
1.30 www 8451:
1.766 albertel 8452: if ($thisallowed eq 'A') {
8453: return 'A';
1.814 raeburn 8454: } elsif ($thisallowed eq 'B') {
8455: return 'B';
1.766 albertel 8456: }
1.52 www 8457: return 'F';
1.232 www 8458: }
1.1162 raeburn 8459:
1.1172.2.13 raeburn 8460: # ------------------------------------------- Check construction space access
8461:
8462: sub constructaccess {
8463: my ($url,$setpriv)=@_;
8464:
8465: # We do not allow editing of previous versions of files
8466: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8467:
8468: # Get username and domain from URL
8469: my ($ownername,$ownerdomain,$ownerhome);
8470:
8471: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8472: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8473:
8474: # The URL does not really point to any authorspace, forget it
8475: unless (($ownername) && ($ownerdomain)) { return ''; }
8476:
8477: # Now we need to see if the user has access to the authorspace of
8478: # $ownername at $ownerdomain
8479:
8480: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8481: # Real author for this?
8482: $ownerhome = $env{'user.home'};
8483: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8484: return ($ownername,$ownerdomain,$ownerhome);
8485: }
8486: } else {
8487: # Co-author for this?
8488: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8489: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8490: $ownerhome = &homeserver($ownername,$ownerdomain);
8491: return ($ownername,$ownerdomain,$ownerhome);
8492: }
8493: }
8494:
8495: # We don't have any access right now. If we are not possibly going to do anything about this,
8496: # we might as well leave
8497: unless ($setpriv) { return ''; }
8498:
8499: # Backdoor access?
8500: my $allowed=&allowed('eco',$ownerdomain);
8501: # Nope
8502: unless ($allowed) { return ''; }
8503: # Looks like we may have access, but could be locked by the owner of the construction space
8504: if ($allowed eq 'U') {
8505: my %blocked=&get('environment',['domcoord.author'],
8506: $ownerdomain,$ownername);
8507: # Is blocked by owner
8508: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8509: }
8510: if (($allowed eq 'F') || ($allowed eq 'U')) {
8511: # Grant temporary access
8512: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8513: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8514: if (!$update) { $update = $then; }
8515: my $refresh=$env{'user.refresh.time'};
8516: if (!$refresh) { $refresh = $update; }
8517: my $now = time;
8518: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8519: $now,'ca','constructaccess');
8520: $ownerhome = &homeserver($ownername,$ownerdomain);
8521: return($ownername,$ownerdomain,$ownerhome);
8522: }
8523: # No business here
8524: return '';
8525: }
8526:
1.1172.2.66 raeburn 8527: # ----------------------------------------------------------- Content Blocking
8528:
8529: {
8530: # Caches for faster Course Contents display where content blocking
8531: # is in operation (i.e., interval param set) for timed quiz.
8532: #
8533: # User for whom data are being temporarily cached.
8534: my $cacheduser='';
1.1172.2.126 raeburn 8535: # Course for which data are being temporarily cached.
8536: my $cachedcid='';
1.1172.2.66 raeburn 8537: # Cached blockers for this user (a hash of blocking items).
8538: my %cachedblockers=();
8539: # When the data were last cached.
8540: my $cachedlast='';
8541:
8542: sub load_all_blockers {
1.1172.2.128 raeburn 8543: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8544: if (($uname ne '') && ($udom ne '')) {
8545: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8546: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8547: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8548: return;
8549: }
8550: }
8551: $cachedlast=time;
8552: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8553: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8554: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8555: return;
1.1172.2.66 raeburn 8556: }
8557:
1.1162 raeburn 8558: sub get_comm_blocks {
8559: my ($cdom,$cnum) = @_;
8560: if ($cdom eq '' || $cnum eq '') {
8561: return unless ($env{'request.course.id'});
8562: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8563: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8564: }
8565: my %commblocks;
8566: my $hashid=$cdom.'_'.$cnum;
8567: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8568: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8569: %commblocks = %{$blocksref};
8570: } else {
8571: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8572: my $cachetime = 600;
8573: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8574: }
8575: return %commblocks;
8576: }
8577:
1.1172.2.66 raeburn 8578: sub get_commblock_resources {
8579: my ($blocks) = @_;
8580: my %blockers = ();
8581: return %blockers unless ($env{'request.course.id'});
1.1172.2.142 raeburn 8582: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8583: if ($env{'request.course.sec'}) {
8584: $courseurl .= '/'.$env{'request.course.sec'};
8585: }
8586: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8587: my %commblocks;
8588: if (ref($blocks) eq 'HASH') {
8589: %commblocks = %{$blocks};
8590: } else {
8591: %commblocks = &get_comm_blocks();
8592: }
1.1172.2.66 raeburn 8593: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8594: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8595: return %blockers unless (ref($navmap));
8596: my $now = time;
1.1162 raeburn 8597: foreach my $block (keys(%commblocks)) {
8598: if ($block =~ /^(\d+)____(\d+)$/) {
8599: my ($start,$end) = ($1,$2);
8600: if ($start <= $now && $end >= $now) {
8601: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8602: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8603: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8604: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8605: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8606: }
8607: }
8608: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8609: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8610: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8611: }
8612: }
8613: }
8614: }
8615: }
8616: } elsif ($block =~ /^firstaccess____(.+)$/) {
8617: my $item = $1;
8618: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8619: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142 raeburn 8620: my (@interval,$mapname);
1.1172.2.66 raeburn 8621: my $type = 'map';
8622: if ($item eq 'course') {
8623: $type = 'course';
8624: @interval=&EXT("resource.0.interval");
8625: } else {
8626: if ($item =~ /___\d+___/) {
8627: $type = 'resource';
8628: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 8629: } else {
1.1172.2.142 raeburn 8630: $mapname = &deversion($item);
8631: if (ref($navmap)) {
8632: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
8633: @interval = ($timelimit,'map');
1.1162 raeburn 8634: }
8635: }
1.1172.2.66 raeburn 8636: }
1.1172.2.147. .1(raebu 8637:22): if ($interval[0] =~ /^(\d+)/) {
8638:22): my $timelimit = $1;
1.1172.2.66 raeburn 8639: my $first_access;
8640: if ($type eq 'resource') {
8641: $first_access=&get_first_access($interval[1],$item);
8642: } elsif ($type eq 'map') {
8643: $first_access=&get_first_access($interval[1],undef,$item);
8644: } else {
8645: $first_access=&get_first_access($interval[1]);
8646: }
8647: if ($first_access) {
1.1172.2.147. .1(raebu 8648:22): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 8649: if ($timesup > $now) {
8650: my $activeblock;
1.1172.2.142 raeburn 8651: if ($type eq 'resource') {
8652: if (ref($navmap)) {
8653: my $res = $navmap->getBySymb($item);
8654: if ($res->answerable()) {
8655: $activeblock = 1;
8656: }
8657: }
8658: } elsif ($type eq 'map') {
8659: my $mapsymb = &symbread($mapname,1);
8660: if (($mapsymb) && (ref($navmap))) {
8661: my $mapres = $navmap->getBySymb($mapsymb);
8662: if (ref($mapres)) {
8663: my $first = $mapres->map_start();
8664: my $finish = $mapres->map_finish();
8665: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8666: if (ref($it)) {
8667: my $res;
8668: while ($res = $it->next(undef,1)) {
8669: next unless (ref($res));
8670: my $symb = $res->symb();
8671: next if (($symb eq $mapsymb) || ($symb eq ''));
8672: @interval=&EXT("resource.0.interval",$symb);
8673: if ($interval[1] eq 'map') {
8674: if ($res->answerable()) {
8675: $activeblock = 1;
8676: last;
8677: }
8678: }
8679: }
8680: }
8681: }
1.1172.2.66 raeburn 8682: }
8683: }
8684: if ($activeblock) {
8685: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8686: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8687: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8688: }
8689: }
8690: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8691: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8692: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8693: }
1.1162 raeburn 8694: }
8695: }
8696: }
8697: }
8698: }
8699: }
8700: }
8701: }
8702: }
1.1172.2.66 raeburn 8703: return %blockers;
1.1162 raeburn 8704: }
8705:
1.1172.2.66 raeburn 8706: sub has_comm_blocking {
1.1172.2.128 raeburn 8707: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8708: my @blockers;
8709: return unless ($env{'request.course.id'});
8710: return unless ($priv eq 'bre');
8711: return if ($env{'request.state'} eq 'construct');
1.1172.2.142 raeburn 8712: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8713: if ($env{'request.course.sec'}) {
8714: $courseurl .= '/'.$env{'request.course.sec'};
8715: }
8716: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128 raeburn 8717: my %blockinfo;
8718: if (ref($blocks) eq 'HASH') {
8719: %blockinfo = &get_commblock_resources($blocks);
8720: } else {
8721: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8722: %blockinfo = %cachedblockers;
8723: }
8724: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8725: my (%possibles,@symbs);
8726: if (!$symb) {
1.1172.2.128 raeburn 8727: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8728: }
1.1172.2.66 raeburn 8729: if ($symb) {
8730: @symbs = ($symb);
8731: } elsif (keys(%possibles)) {
8732: @symbs = keys(%possibles);
8733: }
8734: my $noblock;
8735: foreach my $symb (@symbs) {
8736: last if ($noblock);
8737: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8738: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8739: if ($block =~ /^firstaccess____(.+)$/) {
8740: my $item = $1;
1.1172.2.126 raeburn 8741: unless ($blocked) {
8742: if (($item eq $map) || ($item eq $symb)) {
8743: $noblock = 1;
8744: last;
8745: }
1.1172.2.66 raeburn 8746: }
1.1162 raeburn 8747: }
1.1172.2.128 raeburn 8748: if (ref($blockinfo{$block}) eq 'HASH') {
8749: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8750: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8751: unless (grep(/^\Q$block\E$/,@blockers)) {
8752: push(@blockers,$block);
8753: }
8754: }
8755: }
1.1172.2.128 raeburn 8756: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8757: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8758: unless (grep(/^\Q$block\E$/,@blockers)) {
8759: push(@blockers,$block);
8760: }
1.1172.2.66 raeburn 8761: }
8762: }
1.1162 raeburn 8763: }
8764: }
8765: }
1.1172.2.126 raeburn 8766: unless ($noblock) {
8767: return @blockers;
8768: }
8769: return;
1.1172.2.66 raeburn 8770: }
1.1162 raeburn 8771: }
8772:
1.1172.2.66 raeburn 8773: # -------------------------------- Deversion and split uri into path an filename
8774:
1.1133 foxr 8775: #
1.1172.2.66 raeburn 8776: # Removes the version from a URI and
1.1133 foxr 8777: # splits it in to its filename and path to the filename.
8778: # Seems like File::Basename could have done this more clearly.
8779: # Parameters:
8780: # $uri - input URI
8781: # Returns:
8782: # Two element list consisting of
8783: # $pathname - the URI up to and excluding the trailing /
8784: # $filename - The part of the URI following the last /
8785: # NOTE:
8786: # Another realization of this is simply:
8787: # use File::Basename;
8788: # ...
8789: # $uri = shift;
8790: # $filename = basename($uri);
8791: # $path = dirname($uri);
8792: # return ($filename, $path);
8793: #
8794: # The implementation below is probably faster however.
8795: #
1.710 albertel 8796: sub split_uri_for_cond {
8797: my $uri=&deversion(&declutter(shift));
8798: my @uriparts=split(/\//,$uri);
8799: my $filename=pop(@uriparts);
8800: my $pathname=join('/',@uriparts);
8801: return ($pathname,$filename);
8802: }
1.232 www 8803: # --------------------------------------------------- Is a resource on the map?
8804:
8805: sub is_on_map {
1.710 albertel 8806: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8807: #Trying to find the conditional for the file
1.620 albertel 8808: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8809: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8810: if ($match) {
1.289 bowersj2 8811: return (1,$1);
8812: } else {
1.434 www 8813: return (0,0);
1.289 bowersj2 8814: }
1.12 www 8815: }
8816:
1.427 www 8817: # --------------------------------------------------------- Get symb from alias
8818:
8819: sub get_symb_from_alias {
8820: my $symb=shift;
8821: my ($map,$resid,$url)=&decode_symb($symb);
8822: # Already is a symb
8823: if ($url) { return $symb; }
8824: # Must be an alias
8825: my $aliassymb='';
8826: my %bighash;
1.620 albertel 8827: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8828: &GDBM_READER(),0640)) {
8829: my $rid=$bighash{'mapalias_'.$symb};
8830: if ($rid) {
8831: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8832: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8833: $resid,$bighash{'src_'.$rid});
1.427 www 8834: }
8835: untie %bighash;
8836: }
8837: return $aliassymb;
8838: }
8839:
1.12 www 8840: # ----------------------------------------------------------------- Define Role
8841:
8842: sub definerole {
8843: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8844: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8845: foreach my $role (split(':',$sysrole)) {
8846: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8847: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8848: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8849: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8850: return "refused:s:$crole&$cqual";
8851: }
8852: }
1.191 harris41 8853: }
1.800 albertel 8854: foreach my $role (split(':',$domrole)) {
8855: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8856: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8857: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8858: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8859: return "refused:d:$crole&$cqual";
8860: }
8861: }
1.191 harris41 8862: }
1.800 albertel 8863: foreach my $role (split(':',$courole)) {
8864: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8865: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8866: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8867: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8868: return "refused:c:$crole&$cqual";
8869: }
8870: }
1.191 harris41 8871: }
1.1172.2.84 raeburn 8872: my $uhome;
8873: if (($uname ne '') && ($udom ne '')) {
8874: $uhome = &homeserver($uname,$udom);
8875: return $uhome if ($uhome eq 'no_host');
8876: } else {
8877: $uname = $env{'user.name'};
8878: $udom = $env{'user.domain'};
8879: $uhome = $env{'user.home'};
8880: }
1.620 albertel 8881: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8882: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8883: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8884: return reply($command,$uhome);
1.12 www 8885: } else {
8886: return 'refused';
8887: }
1.105 harris41 8888: }
8889:
8890: # ---------------- Make a metadata query against the network of library servers
8891:
8892: sub metadata_query {
1.1172.2.33 raeburn 8893: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8894: my %rhash;
1.845 albertel 8895: my %libserv = &all_library();
1.244 matthew 8896: my @server_list = (defined($server_array) ? @$server_array
8897: : keys(%libserv) );
8898: for my $server (@server_list) {
1.1172.2.33 raeburn 8899: my $domains = '';
8900: if (ref($domains_hash) eq 'HASH') {
8901: $domains = $domains_hash->{$server};
8902: }
1.118 harris41 8903: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8904: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8905: $rhash{$server}=$reply;
8906: }
8907: else {
8908: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8909: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8910: $server);
8911: $rhash{$server}=$reply;
8912: }
1.112 harris41 8913: }
1.118 harris41 8914: return \%rhash;
1.240 www 8915: }
8916:
8917: # ----------------------------------------- Send log queries and wait for reply
8918:
8919: sub log_query {
8920: my ($uname,$udom,$query,%filters)=@_;
8921: my $uhome=&homeserver($uname,$udom);
8922: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8923: my $uhost=&hostname($uhome);
1.800 albertel 8924: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8925: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8926: $uhome);
1.479 albertel 8927: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8928: return get_query_reply($queryid);
8929: }
8930:
1.818 raeburn 8931: # -------------------------- Update MySQL table for portfolio file
8932:
8933: sub update_portfolio_table {
1.821 raeburn 8934: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8935: if ($group ne '') {
8936: $file_name =~s /^\Q$group\E//;
8937: }
1.818 raeburn 8938: my $homeserver = &homeserver($uname,$udom);
8939: my $queryid=
1.821 raeburn 8940: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8941: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8942: my $reply = &get_query_reply($queryid);
8943: return $reply;
8944: }
8945:
1.899 raeburn 8946: # -------------------------- Update MySQL allusers table
8947:
8948: sub update_allusers_table {
8949: my ($uname,$udom,$names) = @_;
8950: my $homeserver = &homeserver($uname,$udom);
8951: my $queryid=
8952: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8953: 'lastname='.&escape($names->{'lastname'}).'%%'.
8954: 'firstname='.&escape($names->{'firstname'}).'%%'.
8955: 'middlename='.&escape($names->{'middlename'}).'%%'.
8956: 'generation='.&escape($names->{'generation'}).'%%'.
8957: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8958: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8959: return;
1.899 raeburn 8960: }
8961:
1.508 raeburn 8962: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8963:
8964: sub fetch_enrollment_query {
1.511 raeburn 8965: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8966: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8967: my $maxtries = 1;
1.508 raeburn 8968: if ($context eq 'automated') {
8969: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8970: $sleep = 2;
8971: $loopmax = 100;
1.547 raeburn 8972: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8973: } else {
8974: $homeserver = &homeserver($cnum,$dom);
8975: }
1.838 albertel 8976: my $host=&hostname($homeserver);
1.506 raeburn 8977: my $cmd = '';
1.1000 raeburn 8978: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8979: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8980: }
8981: $cmd =~ s/%%$//;
8982: $cmd = &escape($cmd);
8983: my $query = 'fetchenrollment';
1.620 albertel 8984: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8985: unless ($queryid=~/^\Q$host\E\_/) {
8986: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8987: return 'error: '.$queryid;
8988: }
1.1172.2.93 raeburn 8989: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8990: my $tries = 1;
8991: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8992: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8993: $tries ++;
8994: }
1.526 raeburn 8995: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8996: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8997: } else {
1.901 albertel 8998: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8999: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9000: foreach my $line (@responses) {
9001: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9002: $$replyref{$key} = $value;
9003: }
9004: } else {
1.1117 foxr 9005: my $pathname = LONCAPA::tempdir();
1.800 albertel 9006: foreach my $line (@responses) {
9007: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9008: $$replyref{$key} = $value;
9009: if ($value > 0) {
1.800 albertel 9010: foreach my $item (@{$$affiliatesref{$key}}) {
9011: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9012: my $destname = $pathname.'/'.$filename;
9013: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9014: if ($xml_classlist =~ /^error/) {
9015: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9016: } else {
1.1172.2.96 raeburn 9017: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9018: print FILE &unescape($xml_classlist);
9019: close(FILE);
1.526 raeburn 9020: } else {
9021: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9022: }
9023: }
9024: }
9025: }
9026: }
9027: }
9028: return 'ok';
9029: }
9030: return 'error';
9031: }
9032:
1.242 www 9033: sub get_query_reply {
1.1172.2.79 raeburn 9034: my ($queryid,$sleep,$loopmax) = @_;
9035: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9036: $sleep = 0.2;
9037: }
9038: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9039: $loopmax = 100;
9040: }
1.1117 foxr 9041: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9042: my $reply='';
1.1172.2.79 raeburn 9043: for (1..$loopmax) {
9044: sleep($sleep);
1.240 www 9045: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 9046: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9047: $reply = join('',<$fh>);
9048: close($fh);
1.240 www 9049: } else { return 'error: reply_file_error'; }
1.242 www 9050: return &unescape($reply);
9051: }
1.240 www 9052: }
1.242 www 9053: return 'timeout:'.$queryid;
1.240 www 9054: }
9055:
9056: sub courselog_query {
1.241 www 9057: #
9058: # possible filters:
9059: # url: url or symb
9060: # username
9061: # domain
9062: # action: view, submit, grade
9063: # start: timestamp
9064: # end: timestamp
9065: #
1.240 www 9066: my (%filters)=@_;
1.620 albertel 9067: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9068: if ($filters{'url'}) {
9069: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9070: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9071: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9072: }
1.620 albertel 9073: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9074: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9075: return &log_query($cname,$cdom,'courselog',%filters);
9076: }
9077:
9078: sub userlog_query {
1.858 raeburn 9079: #
9080: # possible filters:
9081: # action: log check role
9082: # start: timestamp
9083: # end: timestamp
9084: #
1.240 www 9085: my ($uname,$udom,%filters)=@_;
9086: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9087: }
9088:
1.506 raeburn 9089: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9090:
9091: sub auto_run {
1.508 raeburn 9092: my ($cnum,$cdom) = @_;
1.876 raeburn 9093: my $response = 0;
9094: my $settings;
9095: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9096: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9097: $settings = $domconfig{'autoenroll'};
9098: if ($settings->{'run'} eq '1') {
9099: $response = 1;
9100: }
9101: } else {
1.934 raeburn 9102: my $homeserver;
9103: if (&is_course($cdom,$cnum)) {
9104: $homeserver = &homeserver($cnum,$cdom);
9105: } else {
9106: $homeserver = &domain($cdom,'primary');
9107: }
9108: if ($homeserver ne 'no_host') {
9109: $response = &reply('autorun:'.$cdom,$homeserver);
9110: }
1.876 raeburn 9111: }
1.506 raeburn 9112: return $response;
9113: }
1.776 albertel 9114:
1.506 raeburn 9115: sub auto_get_sections {
1.508 raeburn 9116: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9117: my $homeserver;
9118: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9119: $homeserver = &homeserver($cnum,$cdom);
9120: }
9121: if (!defined($homeserver)) {
9122: if ($cdom =~ /^$match_domain$/) {
9123: $homeserver = &domain($cdom,'primary');
9124: }
9125: }
9126: my @secs;
9127: if (defined($homeserver)) {
9128: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9129: unless ($response eq 'refused') {
9130: @secs = split(/:/,$response);
9131: }
1.506 raeburn 9132: }
9133: return @secs;
9134: }
1.776 albertel 9135:
1.506 raeburn 9136: sub auto_new_course {
1.1099 raeburn 9137: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9138: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9139: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9140: return $response;
9141: }
1.776 albertel 9142:
1.506 raeburn 9143: sub auto_validate_courseID {
1.508 raeburn 9144: my ($cnum,$cdom,$inst_course_id) = @_;
9145: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9146: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9147: return $response;
9148: }
1.776 albertel 9149:
1.1007 raeburn 9150: sub auto_validate_instcode {
1.1020 raeburn 9151: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9152: my ($homeserver,$response);
9153: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9154: $homeserver = &homeserver($cnum,$cdom);
9155: }
9156: if (!defined($homeserver)) {
9157: if ($cdom =~ /^$match_domain$/) {
9158: $homeserver = &domain($cdom,'primary');
9159: }
9160: }
1.1065 raeburn 9161: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9162: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9163: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9164: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9165: }
9166:
1.1172.2.141 raeburn 9167: sub auto_validate_inst_crosslist {
9168: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9169: my ($homeserver,$response);
9170: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9171: $homeserver = &homeserver($cnum,$cdom);
9172: }
9173: if (!defined($homeserver)) {
9174: if ($cdom =~ /^$match_domain$/) {
9175: $homeserver = &domain($cdom,'primary');
9176: }
9177: }
9178: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9179: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9180: &escape($instcode).':'.&escape($inst_xlist).':'.
9181: &escape($coowner),$homeserver);
9182: }
9183: return $response;
9184: }
9185:
1.506 raeburn 9186: sub auto_create_password {
1.873 raeburn 9187: my ($cnum,$cdom,$authparam,$udom) = @_;
9188: my ($homeserver,$response);
1.506 raeburn 9189: my $create_passwd = 0;
9190: my $authchk = '';
1.873 raeburn 9191: if ($udom =~ /^$match_domain$/) {
9192: $homeserver = &domain($udom,'primary');
9193: }
9194: if ($homeserver eq '') {
9195: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9196: $homeserver = &homeserver($cnum,$cdom);
9197: }
9198: }
9199: if ($homeserver eq '') {
9200: $authchk = 'nodomain';
1.506 raeburn 9201: } else {
1.873 raeburn 9202: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9203: if ($response eq 'refused') {
9204: $authchk = 'refused';
9205: } else {
1.901 albertel 9206: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9207: }
1.506 raeburn 9208: }
9209: return ($authparam,$create_passwd,$authchk);
9210: }
9211:
1.706 raeburn 9212: sub auto_photo_permission {
9213: my ($cnum,$cdom,$students) = @_;
9214: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9215: my ($outcome,$perm_reqd,$conditions) =
9216: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9217: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9218: return (undef,undef);
9219: }
1.706 raeburn 9220: return ($outcome,$perm_reqd,$conditions);
9221: }
9222:
9223: sub auto_checkphotos {
9224: my ($uname,$udom,$pid) = @_;
9225: my $homeserver = &homeserver($uname,$udom);
9226: my ($result,$resulttype);
9227: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9228: &escape($uname).':'.&escape($pid),
9229: $homeserver));
1.709 albertel 9230: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9231: return (undef,undef);
9232: }
1.706 raeburn 9233: if ($outcome) {
9234: ($result,$resulttype) = split(/:/,$outcome);
9235: }
9236: return ($result,$resulttype);
9237: }
9238:
9239: sub auto_photochoice {
9240: my ($cnum,$cdom) = @_;
9241: my $homeserver = &homeserver($cnum,$cdom);
9242: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9243: &escape($cdom),
9244: $homeserver)));
1.709 albertel 9245: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9246: return (undef,undef);
9247: }
1.706 raeburn 9248: return ($update,$comment);
9249: }
9250:
9251: sub auto_photoupdate {
9252: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9253: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9254: my $host=&hostname($homeserver);
1.706 raeburn 9255: my $cmd = '';
9256: my $maxtries = 1;
1.800 albertel 9257: foreach my $affiliate (keys(%{$affiliatesref})) {
9258: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9259: }
9260: $cmd =~ s/%%$//;
9261: $cmd = &escape($cmd);
9262: my $query = 'institutionalphotos';
9263: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9264: unless ($queryid=~/^\Q$host\E\_/) {
9265: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9266: return 'error: '.$queryid;
9267: }
9268: my $reply = &get_query_reply($queryid);
9269: my $tries = 1;
9270: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9271: $reply = &get_query_reply($queryid);
9272: $tries ++;
9273: }
9274: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9275: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9276: } else {
9277: my @responses = split(/:/,$reply);
9278: my $outcome = shift(@responses);
9279: foreach my $item (@responses) {
9280: my ($key,$value) = split(/=/,$item);
9281: $$photo{$key} = $value;
9282: }
9283: return $outcome;
9284: }
9285: return 'error';
9286: }
9287:
1.521 raeburn 9288: sub auto_instcode_format {
1.793 albertel 9289: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9290: $cat_order) = @_;
1.521 raeburn 9291: my $courses = '';
1.772 raeburn 9292: my @homeservers;
1.521 raeburn 9293: if ($caller eq 'global') {
1.841 albertel 9294: my %servers = &get_servers($codedom,'library');
9295: foreach my $tryserver (keys(%servers)) {
9296: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9297: push(@homeservers,$tryserver);
9298: }
1.584 raeburn 9299: }
1.1022 raeburn 9300: } elsif ($caller eq 'requests') {
9301: if ($codedom =~ /^$match_domain$/) {
9302: my $chome = &domain($codedom,'primary');
9303: unless ($chome eq 'no_host') {
9304: push(@homeservers,$chome);
9305: }
9306: }
1.521 raeburn 9307: } else {
1.772 raeburn 9308: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9309: }
1.793 albertel 9310: foreach my $code (keys(%{$instcodes})) {
9311: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9312: }
9313: chop($courses);
1.772 raeburn 9314: my $ok_response = 0;
9315: my $response;
9316: while (@homeservers > 0 && $ok_response == 0) {
9317: my $server = shift(@homeservers);
9318: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9319: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9320: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9321: split(/:/,$response);
1.772 raeburn 9322: %{$codes} = (%{$codes},&str2hash($codes_str));
9323: push(@{$codetitles},&str2array($codetitles_str));
9324: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9325: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9326: $ok_response = 1;
9327: }
9328: }
9329: if ($ok_response) {
1.521 raeburn 9330: return 'ok';
1.772 raeburn 9331: } else {
9332: return $response;
1.521 raeburn 9333: }
9334: }
9335:
1.792 raeburn 9336: sub auto_instcode_defaults {
9337: my ($domain,$returnhash,$code_order) = @_;
9338: my @homeservers;
1.841 albertel 9339:
9340: my %servers = &get_servers($domain,'library');
9341: foreach my $tryserver (keys(%servers)) {
9342: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9343: push(@homeservers,$tryserver);
9344: }
1.792 raeburn 9345: }
1.841 albertel 9346:
1.792 raeburn 9347: my $response;
1.841 albertel 9348: foreach my $server (@homeservers) {
1.792 raeburn 9349: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9350: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9351:
9352: foreach my $pair (split(/\&/,$response)) {
9353: my ($name,$value)=split(/\=/,$pair);
9354: if ($name eq 'code_order') {
9355: @{$code_order} = split(/\&/,&unescape($value));
9356: } else {
9357: $returnhash->{&unescape($name)}=&unescape($value);
9358: }
9359: }
9360: return 'ok';
1.792 raeburn 9361: }
1.841 albertel 9362:
9363: return $response;
1.1003 raeburn 9364: }
9365:
9366: sub auto_possible_instcodes {
1.1007 raeburn 9367: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9368: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9369: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9370: return;
9371: }
1.1003 raeburn 9372: my (@homeservers,$uhome);
9373: if (defined(&domain($domain,'primary'))) {
9374: $uhome=&domain($domain,'primary');
9375: push(@homeservers,&domain($domain,'primary'));
9376: } else {
9377: my %servers = &get_servers($domain,'library');
9378: foreach my $tryserver (keys(%servers)) {
9379: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9380: push(@homeservers,$tryserver);
9381: }
9382: }
9383: }
9384: my $response;
9385: foreach my $server (@homeservers) {
9386: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9387: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9388: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9389: split(':',$response);
9390: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9391: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9392: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9393: my ($name,$value)=split('=',$item);
9394: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9395: }
9396: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9397: my ($name,$value)=split('=',$item);
9398: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9399: }
9400: return 'ok';
9401: }
9402: return $response;
9403: }
1.792 raeburn 9404:
1.1010 raeburn 9405: sub auto_courserequest_checks {
9406: my ($dom) = @_;
1.1020 raeburn 9407: my ($homeserver,%validations);
9408: if ($dom =~ /^$match_domain$/) {
9409: $homeserver = &domain($dom,'primary');
9410: }
9411: unless ($homeserver eq 'no_host') {
9412: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9413: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9414: my @items = split(/&/,$response);
9415: foreach my $item (@items) {
9416: my ($key,$value) = split('=',$item);
9417: $validations{&unescape($key)} = &thaw_unescape($value);
9418: }
9419: }
9420: }
1.1010 raeburn 9421: return %validations;
9422: }
9423:
1.1020 raeburn 9424: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9425: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9426: my ($homeserver,$response);
9427: if ($dom =~ /^$match_domain$/) {
9428: $homeserver = &domain($dom,'primary');
9429: }
1.1172.2.43 raeburn 9430: unless ($homeserver eq 'no_host') {
9431: my $customdata;
9432: if (ref($custominfo) eq 'HASH') {
9433: $customdata = &freeze_escape($custominfo);
9434: }
1.1020 raeburn 9435: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9436: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9437: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9438: $customdata,$homeserver));
1.1020 raeburn 9439: }
9440: return $response;
9441: }
9442:
1.777 albertel 9443: sub auto_validate_class_sec {
1.918 raeburn 9444: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9445: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9446: my $ownerlist;
9447: if (ref($owners) eq 'ARRAY') {
9448: $ownerlist = join(',',@{$owners});
9449: } else {
9450: $ownerlist = $owners;
9451: }
1.773 raeburn 9452: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9453: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9454: return $response;
9455: }
9456:
1.1172.2.141 raeburn 9457: sub auto_instsec_reformat {
9458: my ($cdom,$action,$instsecref) = @_;
9459: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9460: my @homeservers;
9461: if (defined(&domain($cdom,'primary'))) {
9462: push(@homeservers,&domain($cdom,'primary'));
9463: } else {
9464: my %servers = &get_servers($cdom,'library');
9465: foreach my $tryserver (keys(%servers)) {
9466: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9467: push(@homeservers,$tryserver);
9468: }
9469: }
9470: }
9471: my $response;
9472: my %reformatted = %{$instsecref};
9473: foreach my $server (@homeservers) {
9474: if (ref($instsecref) eq 'HASH') {
9475: my $info = &freeze_escape($instsecref);
9476: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9477: $action.':'.$info,$server);
9478: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9479: my @items = split(/&/,$response);
9480: foreach my $item (@items) {
9481: my ($key,$value) = split(/=/,$item);
9482: $reformatted{&unescape($key)} = &thaw_unescape($value);
9483: }
9484: }
9485: }
9486: return %reformatted;
9487: }
9488:
1.1172.2.94 raeburn 9489: sub auto_validate_instclasses {
9490: my ($cdom,$cnum,$owners,$classesref) = @_;
9491: my ($homeserver,%validations);
9492: $homeserver = &homeserver($cnum,$cdom);
9493: unless ($homeserver eq 'no_host') {
9494: my $ownerlist;
9495: if (ref($owners) eq 'ARRAY') {
9496: $ownerlist = join(',',@{$owners});
9497: } else {
9498: $ownerlist = $owners;
9499: }
9500: if (ref($classesref) eq 'HASH') {
9501: my $classes = &freeze_escape($classesref);
9502: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9503: ':'.$cdom.':'.$classes,$homeserver);
9504: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9505: my @items = split(/&/,$response);
9506: foreach my $item (@items) {
9507: my ($key,$value) = split('=',$item);
9508: $validations{&unescape($key)} = &thaw_unescape($value);
9509: }
9510: }
9511: }
9512: }
9513: return %validations;
9514: }
9515:
1.1172.2.38 raeburn 9516: sub auto_crsreq_update {
9517: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9518: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9519: my ($homeserver,%crsreqresponse);
9520: if ($cdom =~ /^$match_domain$/) {
9521: $homeserver = &domain($cdom,'primary');
9522: }
9523: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9524: my $info;
9525: if (ref($inbound) eq 'HASH') {
9526: $info = &freeze_escape($inbound);
9527: }
9528: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9529: ':'.&escape($action).':'.&escape($ownername).':'.
9530: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9531: &escape($title).':'.&escape($code).':'.
9532: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9533: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9534: my @items = split(/&/,$response);
9535: foreach my $item (@items) {
9536: my ($key,$value) = split('=',$item);
9537: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9538: }
9539: }
9540: }
9541: return \%crsreqresponse;
9542: }
9543:
1.1172.2.78 raeburn 9544: sub auto_export_grades {
9545: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9546: my ($homeserver,%exportresponse);
9547: if ($cdom =~ /^$match_domain$/) {
9548: $homeserver = &domain($cdom,'primary');
9549: }
9550: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9551: my $info;
9552: if (ref($inforef) eq 'HASH') {
9553: $info = &freeze_escape($inforef);
9554: }
9555: if (ref($gradesref) eq 'HASH') {
9556: my $grades = &freeze_escape($gradesref);
9557: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9558: $info.':'.$grades,$homeserver);
9559: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9560: my @items = split(/&/,$response);
9561: foreach my $item (@items) {
9562: my ($key,$value) = split('=',$item);
9563: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9564: }
9565: }
9566: }
9567: }
9568: return \%exportresponse;
9569: }
9570:
1.1172.2.68 raeburn 9571: sub check_instcode_cloning {
9572: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9573: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9574: return;
9575: }
9576: my $canclone;
9577: if (@{$code_order} > 0) {
9578: my $instcoderegexp ='^';
9579: my @clonecodes = split(/\&/,$cloner);
9580: foreach my $item (@{$code_order}) {
9581: if (grep(/^\Q$item\E=/,@clonecodes)) {
9582: foreach my $pair (@clonecodes) {
9583: my ($key,$val) = split(/\=/,$pair,2);
9584: $val = &unescape($val);
9585: if ($key eq $item) {
9586: $instcoderegexp .= '('.$val.')';
9587: last;
9588: }
9589: }
9590: } else {
9591: $instcoderegexp .= $codedefaults->{$item};
9592: }
9593: }
9594: $instcoderegexp .= '$';
9595: my (@from,@to);
9596: eval {
9597: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9598: (@to) = ($clonetocode =~ /$instcoderegexp/);
9599: };
9600: if ((@from > 0) && (@to > 0)) {
9601: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9602: if (!@diffs) {
9603: $canclone = 1;
9604: }
9605: }
9606: }
9607: return $canclone;
9608: }
9609:
9610: sub default_instcode_cloning {
9611: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9612: my (%codedefaults,@code_order,$canclone);
9613: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9614: %codedefaults = %{$codedefaultsref};
9615: @code_order = @{$codeorderref};
9616: } elsif ($clonedom) {
9617: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9618: }
9619: if (($domdefclone) && (@code_order)) {
9620: my @clonecodes = split(/\+/,$domdefclone);
9621: my $instcoderegexp ='^';
9622: foreach my $item (@code_order) {
9623: if (grep(/^\Q$item\E$/,@clonecodes)) {
9624: $instcoderegexp .= '('.$codedefaults{$item}.')';
9625: } else {
9626: $instcoderegexp .= $codedefaults{$item};
9627: }
9628: }
9629: $instcoderegexp .= '$';
9630: my (@from,@to);
9631: eval {
9632: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9633: (@to) = ($clonetocode =~ /$instcoderegexp/);
9634: };
9635: if ((@from > 0) && (@to > 0)) {
9636: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9637: if (!@diffs) {
9638: $canclone = 1;
9639: }
9640: }
9641: }
9642: return $canclone;
9643: }
9644:
1.679 raeburn 9645: # ------------------------------------------------------- Course Group routines
9646:
9647: sub get_coursegroups {
1.809 raeburn 9648: my ($cdom,$cnum,$group,$namespace) = @_;
9649: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9650: }
9651:
1.679 raeburn 9652: sub modify_coursegroup {
9653: my ($cdom,$cnum,$groupsettings) = @_;
9654: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9655: }
9656:
1.809 raeburn 9657: sub toggle_coursegroup_status {
9658: my ($cdom,$cnum,$group,$action) = @_;
9659: my ($from_namespace,$to_namespace);
9660: if ($action eq 'delete') {
9661: $from_namespace = 'coursegroups';
9662: $to_namespace = 'deleted_groups';
9663: } else {
9664: $from_namespace = 'deleted_groups';
9665: $to_namespace = 'coursegroups';
9666: }
9667: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9668: if (my $tmp = &error(%curr_group)) {
9669: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9670: return ('read error',$tmp);
9671: } else {
9672: my %savedsettings = %curr_group;
1.809 raeburn 9673: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9674: my $deloutcome;
9675: if ($result eq 'ok') {
1.809 raeburn 9676: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9677: } else {
9678: return ('write error',$result);
9679: }
9680: if ($deloutcome eq 'ok') {
9681: return 'ok';
9682: } else {
9683: return ('delete error',$deloutcome);
9684: }
9685: }
9686: }
9687:
1.679 raeburn 9688: sub modify_group_roles {
1.957 raeburn 9689: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9690: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9691: my $role = 'gr/'.&escape($userprivs);
9692: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9693: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9694: if ($result eq 'ok') {
9695: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9696: }
1.679 raeburn 9697: return $result;
9698: }
9699:
9700: sub modify_coursegroup_membership {
9701: my ($cdom,$cnum,$membership) = @_;
9702: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9703: return $result;
9704: }
9705:
1.682 raeburn 9706: sub get_active_groups {
9707: my ($udom,$uname,$cdom,$cnum) = @_;
9708: my $now = time;
9709: my %groups = ();
9710: foreach my $key (keys(%env)) {
1.811 albertel 9711: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9712: my ($start,$end) = split(/\./,$env{$key});
9713: if (($end!=0) && ($end<$now)) { next; }
9714: if (($start!=0) && ($start>$now)) { next; }
9715: if ($1 eq $cdom && $2 eq $cnum) {
9716: $groups{$3} = $env{$key} ;
9717: }
9718: }
9719: }
9720: return %groups;
9721: }
9722:
1.683 raeburn 9723: sub get_group_membership {
9724: my ($cdom,$cnum,$group) = @_;
9725: return(&dump('groupmembership',$cdom,$cnum,$group));
9726: }
9727:
9728: sub get_users_groups {
9729: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9730: my @usersgroups;
1.683 raeburn 9731: my $cachetime=1800;
9732:
9733: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9734: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9735: if (defined($cached)) {
1.734 albertel 9736: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9737: } else {
9738: $grouplist = '';
1.816 raeburn 9739: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9740: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9741: my $access_end = $env{'course.'.$courseid.
9742: '.default_enrollment_end_date'};
9743: my $now = time;
9744: foreach my $key (keys(%roleshash)) {
9745: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9746: my $group = $1;
9747: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9748: my $start = $2;
9749: my $end = $1;
9750: if ($start == -1) { next; } # deleted from group
9751: if (($start!=0) && ($start>$now)) { next; }
9752: if (($end!=0) && ($end<$now)) {
9753: if ($access_end && $access_end < $now) {
9754: if ($access_end - $end < 86400) {
9755: push(@usersgroups,$group);
1.733 raeburn 9756: }
9757: }
1.817 raeburn 9758: next;
1.733 raeburn 9759: }
1.817 raeburn 9760: push(@usersgroups,$group);
1.683 raeburn 9761: }
9762: }
9763: }
1.817 raeburn 9764: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9765: $grouplist = join(':',@usersgroups);
9766: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9767: }
1.733 raeburn 9768: return @usersgroups;
1.683 raeburn 9769: }
9770:
9771: sub devalidate_getgroups_cache {
9772: my ($udom,$uname,$cdom,$cnum)=@_;
9773: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9774:
1.683 raeburn 9775: my $hashid="$udom:$uname:$courseid";
9776: &devalidate_cache_new('getgroups',$hashid);
9777: }
9778:
1.12 www 9779: # ------------------------------------------------------------------ Plain Text
9780:
9781: sub plaintext {
1.988 raeburn 9782: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9783: if ($short =~ m{^cr/}) {
1.758 albertel 9784: return (split('/',$short))[-1];
9785: }
1.742 raeburn 9786: if (!defined($cid)) {
9787: $cid = $env{'request.course.id'};
9788: }
9789: my %rolenames = (
1.1008 raeburn 9790: Course => 'std',
9791: Community => 'alt1',
1.742 raeburn 9792: );
1.1037 raeburn 9793: if ($cid ne '') {
9794: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9795: unless ($forcedefault) {
9796: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9797: &Apache::lonlocal::mt_escape(\$roletext);
9798: return &Apache::lonlocal::mt($roletext);
9799: }
9800: }
9801: }
9802: if ((defined($type)) && (defined($rolenames{$type})) &&
9803: (defined($rolenames{$type})) &&
9804: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9805: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9806: } elsif ($cid ne '') {
9807: my $crstype = $env{'course.'.$cid.'.type'};
9808: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9809: (defined($prp{$short}{$rolenames{$crstype}}))) {
9810: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9811: }
1.742 raeburn 9812: }
1.1037 raeburn 9813: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9814: }
9815:
9816: # ----------------------------------------------------------------- Assign Role
9817:
9818: sub assignrole {
1.957 raeburn 9819: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9820: $context)=@_;
1.21 www 9821: my $mrole;
9822: if ($role =~ /^cr\//) {
1.393 www 9823: my $cwosec=$url;
1.811 albertel 9824: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9825: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9826: my $refused = 1;
9827: if ($context eq 'requestcourses') {
9828: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9829: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9830: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9831: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9832: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9833: if ($crsenv{'internal.courseowner'} eq
9834: $env{'user.name'}.':'.$env{'user.domain'}) {
9835: $refused = '';
9836: }
9837: }
9838: }
9839: }
9840: }
9841: if ($refused) {
9842: &logthis('Refused custom assignrole: '.
9843: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9844: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9845: return 'refused';
9846: }
1.104 www 9847: }
1.21 www 9848: $mrole='cr';
1.678 raeburn 9849: } elsif ($role =~ /^gr\//) {
9850: my $cwogrp=$url;
1.811 albertel 9851: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9852: unless (&allowed('mdg',$cwogrp)) {
9853: &logthis('Refused group assignrole: '.
9854: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9855: $env{'user.name'}.' at '.$env{'user.domain'});
9856: return 'refused';
9857: }
9858: $mrole='gr';
1.21 www 9859: } else {
1.82 www 9860: my $cwosec=$url;
1.811 albertel 9861: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9862: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9863: my $refused;
9864: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9865: if (!(&allowed('c'.$role,$url))) {
9866: $refused = 1;
9867: }
9868: } else {
9869: $refused = 1;
9870: }
1.947 raeburn 9871: if ($refused) {
1.1045 raeburn 9872: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9873: if (!$selfenroll && $context eq 'course') {
9874: my %crsenv;
9875: if ($role eq 'cc' || $role eq 'co') {
9876: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9877: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9878: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9879: if ($crsenv{'internal.courseowner'} eq
9880: $env{'user.name'}.':'.$env{'user.domain'}) {
9881: $refused = '';
9882: }
9883: }
9884: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9885: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9886: if ($crsenv{'internal.courseowner'} eq
9887: $env{'user.name'}.':'.$env{'user.domain'}) {
9888: $refused = '';
9889: }
9890: }
9891: }
9892: }
9893: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9894: $refused = '';
1.1017 raeburn 9895: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9896: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9897: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9898: my $wrongcc;
9899: if ($cnum =~ /^$match_community$/) {
9900: $wrongcc = 1 if ($role eq 'cc');
9901: } else {
9902: $wrongcc = 1 if ($role eq 'co');
9903: }
9904: unless ($wrongcc) {
9905: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9906: if ($crsenv{'internal.courseowner'} eq
9907: $env{'user.name'}.':'.$env{'user.domain'}) {
9908: $refused = '';
9909: }
1.1017 raeburn 9910: }
9911: }
1.1172.2.9 raeburn 9912: } elsif ($context eq 'requestauthor') {
9913: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9914: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9915: if ($env{'environment.requestauthor'} eq 'automatic') {
9916: $refused = '';
9917: } else {
9918: my %domdefaults = &get_domain_defaults($udom);
9919: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9920: my $checkbystatus;
9921: if ($env{'user.adv'}) {
9922: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9923: if ($disposition eq 'automatic') {
9924: $refused = '';
9925: } elsif ($disposition eq '') {
9926: $checkbystatus = 1;
9927: }
9928: } else {
9929: $checkbystatus = 1;
9930: }
9931: if ($checkbystatus) {
9932: if ($env{'environment.inststatus'}) {
9933: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9934: foreach my $type (@inststatuses) {
9935: if (($type ne '') &&
9936: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9937: $refused = '';
9938: }
9939: }
9940: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9941: $refused = '';
9942: }
9943: }
9944: }
9945: }
9946: }
1.1017 raeburn 9947: }
9948: if ($refused) {
1.947 raeburn 9949: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9950: ' '.$role.' '.$end.' '.$start.' by '.
9951: $env{'user.name'}.' at '.$env{'user.domain'});
9952: return 'refused';
9953: }
1.932 raeburn 9954: }
1.1131 raeburn 9955: } elsif ($role eq 'au') {
9956: if ($url ne '/'.$udom.'/') {
9957: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9958: ' to assign author role for '.$uname.':'.$udom.
9959: ' in domain: '.$url.' refused (wrong domain).');
9960: return 'refused';
9961: }
1.104 www 9962: }
1.21 www 9963: $mrole=$role;
9964: }
1.620 albertel 9965: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9966: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9967: if ($end) { $command.='_'.$end; }
1.21 www 9968: if ($start) {
9969: if ($end) {
1.81 www 9970: $command.='_'.$start;
1.21 www 9971: } else {
1.81 www 9972: $command.='_0_'.$start;
1.21 www 9973: }
9974: }
1.739 raeburn 9975: my $origstart = $start;
9976: my $origend = $end;
1.957 raeburn 9977: my $delflag;
1.357 www 9978: # actually delete
9979: if ($deleteflag) {
1.373 www 9980: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9981: # modify command to delete the role
1.620 albertel 9982: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9983: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9984: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9985: # set start and finish to negative values for userrolelog
9986: $start=-1;
9987: $end=-1;
1.957 raeburn 9988: $delflag = 1;
1.357 www 9989: }
9990: }
9991: # send command
1.349 www 9992: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9993: # log new user role if status is ok
1.349 www 9994: if ($answer eq 'ok') {
1.663 raeburn 9995: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9996: if (($role eq 'cc') || ($role eq 'in') ||
9997: ($role eq 'ep') || ($role eq 'ad') ||
9998: ($role eq 'ta') || ($role eq 'st') ||
9999: ($role=~/^cr/) || ($role eq 'gr') ||
10000: ($role eq 'co')) {
1.1172.2.13 raeburn 10001: # for course roles, perform group memberships changes triggered by role change.
10002: unless ($role =~ /^gr/) {
10003: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10004: $origstart,$selfenroll,$context);
10005: }
1.1172.2.9 raeburn 10006: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10007: $selfenroll,$context);
10008: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 10009: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10010: ($role eq 'da')) {
1.1172.2.9 raeburn 10011: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10012: $context);
10013: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10014: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10015: $context);
10016: }
1.1053 raeburn 10017: if ($role eq 'cc') {
10018: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10019: }
1.349 www 10020: }
10021: return $answer;
1.169 harris41 10022: }
10023:
1.1053 raeburn 10024: sub autoupdate_coowners {
10025: my ($url,$end,$start,$uname,$udom) = @_;
10026: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10027: if (($cdom ne '') && ($cnum ne '')) {
10028: my $now = time;
10029: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10030: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10031: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10032: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141 raeburn 10033: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10034: if ($instcode ne '') {
1.1056 raeburn 10035: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10036: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10037: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10038: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141 raeburn 10039: unless ($result eq 'valid') {
10040: if ($xlists ne '') {
10041: foreach my $xlist (split(',',$xlists)) {
10042: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10043: $result =
10044: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10045: $inst_crosslist,$uname.':'.$udom);
10046: last if ($result eq 'valid');
10047: }
10048: }
10049: }
1.1056 raeburn 10050: if ($result eq 'valid') {
10051: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10052: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10053: push(@newcoowners,$coowner);
10054: }
10055: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10056: push(@newcoowners,$uname.':'.$udom);
10057: }
10058: @newcoowners = sort(@newcoowners);
10059: } else {
10060: push(@newcoowners,$uname.':'.$udom);
10061: }
1.1172.2.141 raeburn 10062: } elsif ($coursehash{'internal.co-owners'}) {
10063: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10064: unless ($coowner eq $uname.':'.$udom) {
10065: push(@newcoowners,$coowner);
1.1053 raeburn 10066: }
10067: }
1.1172.2.141 raeburn 10068: unless (@newcoowners > 0) {
10069: $delcoowners = 1;
10070: $coowners = '';
10071: }
1.1053 raeburn 10072: }
10073: if (@newcoowners || $delcoowners) {
10074: &store_coowners($cdom,$cnum,$coursehash{'home'},
10075: $delcoowners,@newcoowners);
10076: }
10077: }
10078: }
10079: }
10080: }
10081: }
10082: }
10083:
10084: sub store_coowners {
10085: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10086: my $cid = $cdom.'_'.$cnum;
10087: my ($coowners,$delresult,$putresult);
10088: if (@newcoowners) {
10089: $coowners = join(',',@newcoowners);
10090: my %coownershash = (
10091: 'internal.co-owners' => $coowners,
10092: );
10093: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10094: if ($putresult eq 'ok') {
10095: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10096: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10097: }
10098: }
10099: }
10100: if ($delcoowners) {
10101: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10102: if ($delresult eq 'ok') {
10103: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10104: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10105: }
10106: }
10107: }
10108: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10109: my %crsinfo =
10110: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10111: if (ref($crsinfo{$cid}) eq 'HASH') {
10112: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10113: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10114: }
10115: }
10116: }
10117:
1.169 harris41 10118: # -------------------------------------------------- Modify user authentication
1.197 www 10119: # Overrides without validation
10120:
1.169 harris41 10121: sub modifyuserauth {
10122: my ($udom,$uname,$umode,$upass)=@_;
10123: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10124: my $allowed;
10125: if (&allowed('mau',$udom)) {
10126: $allowed = 1;
10127: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10128: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10129: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10130: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10131: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10132: if (($cdom ne '') && ($cnum ne '')) {
10133: my $is_owner = &is_course_owner($cdom,$cnum);
10134: if ($is_owner) {
10135: $allowed = 1;
10136: }
10137: }
10138: }
10139: unless ($allowed) { return 'refused'; }
1.197 www 10140: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10141: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10142: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10143: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10144: &escape($upass),$uhome);
1.1172.2.134 raeburn 10145: my $ip = &get_requestor_ip();
1.620 albertel 10146: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10147: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10148: '(Remote '.$ip.'): '.$reply);
1.197 www 10149: &log($udom,,$uname,$uhome,
1.620 albertel 10150: 'Authentication changed by '.$env{'user.domain'}.', '.
10151: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10152: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10153: unless ($reply eq 'ok') {
1.197 www 10154: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10155: return 'error: '.$reply;
10156: }
1.170 harris41 10157: return 'ok';
1.80 www 10158: }
10159:
1.81 www 10160: # --------------------------------------------------------------- Modify a user
1.80 www 10161:
1.81 www 10162: sub modifyuser {
1.206 matthew 10163: my ($udom, $uname, $uid,
10164: $umode, $upass, $first,
10165: $middle, $last, $gene,
1.1058 raeburn 10166: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10167: $udom= &LONCAPA::clean_domain($udom);
10168: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10169: my $showcandelete = 'none';
10170: if (ref($candelete) eq 'ARRAY') {
10171: if (@{$candelete} > 0) {
10172: $showcandelete = join(', ',@{$candelete});
10173: }
10174: }
1.81 www 10175: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10176: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10177: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10178: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10179: ' desiredhome not specified').
1.620 albertel 10180: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10181: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10182: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10183: my $newuser;
10184: if ($uhome eq 'no_host') {
10185: $newuser = 1;
10186: }
1.80 www 10187: # ----------------------------------------------------------------- Create User
1.406 albertel 10188: if (($uhome eq 'no_host') &&
10189: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10190: my $unhome='';
1.844 albertel 10191: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10192: $unhome = $desiredhome;
1.620 albertel 10193: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10194: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10195: } else { # load balancing routine for determining $unhome
1.81 www 10196: my $loadm=10000000;
1.841 albertel 10197: my %servers = &get_servers($udom,'library');
10198: foreach my $tryserver (keys(%servers)) {
10199: my $answer=reply('load',$tryserver);
10200: if (($answer=~/\d+/) && ($answer<$loadm)) {
10201: $loadm=$answer;
10202: $unhome=$tryserver;
10203: }
1.80 www 10204: }
10205: }
10206: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10207: return 'error: unable to find a home server for '.$uname.
10208: ' in domain '.$udom;
1.80 www 10209: }
10210: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10211: &escape($upass),$unhome);
10212: unless ($reply eq 'ok') {
10213: return 'error: '.$reply;
10214: }
1.230 stredwic 10215: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10216: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10217: return 'error: unable verify users home machine.';
1.80 www 10218: }
1.209 matthew 10219: } # End of creation of new user
1.80 www 10220: # ---------------------------------------------------------------------- Add ID
10221: if ($uid) {
10222: $uid=~tr/A-Z/a-z/;
10223: my %uidhash=&idrget($udom,$uname);
1.196 www 10224: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10225: && (!$forceid)) {
1.80 www 10226: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10227: return 'error: user id "'.$uid.'" does not match '.
10228: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10229: }
10230: } else {
10231: &idput($udom,($uname => $uid));
10232: }
10233: }
10234: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10235: my @tmp=&get('environment',
1.899 raeburn 10236: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10237: 'permanentemail','inststatus'],
1.134 albertel 10238: $udom,$uname);
1.1075 raeburn 10239: my (%names,%oldnames);
1.313 matthew 10240: if ($tmp[0] =~ m/^error:.*/) {
10241: %names=();
10242: } else {
10243: %names = @tmp;
1.1075 raeburn 10244: %oldnames = %names;
1.313 matthew 10245: }
1.388 www 10246: #
1.1058 raeburn 10247: # If name, email and/or uid are blank (e.g., because an uploaded file
10248: # of users did not contain them), do not overwrite existing values
10249: # unless field is in $candelete array ref.
10250: #
10251:
10252: my @fields = ('firstname','middlename','lastname','generation',
10253: 'permanentemail','id');
10254: my %newvalues;
10255: if (ref($candelete) eq 'ARRAY') {
10256: foreach my $field (@fields) {
10257: if (grep(/^\Q$field\E$/,@{$candelete})) {
10258: if ($field eq 'firstname') {
10259: $names{$field} = $first;
10260: } elsif ($field eq 'middlename') {
10261: $names{$field} = $middle;
10262: } elsif ($field eq 'lastname') {
10263: $names{$field} = $last;
10264: } elsif ($field eq 'generation') {
10265: $names{$field} = $gene;
10266: } elsif ($field eq 'permanentemail') {
10267: $names{$field} = $email;
10268: } elsif ($field eq 'id') {
10269: $names{$field} = $uid;
10270: }
10271: }
10272: }
10273: }
1.388 www 10274: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10275: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10276: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10277: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10278: if ($email) {
10279: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10280: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10281: }
1.899 raeburn 10282: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10283: if (defined($inststatus)) {
10284: $names{'inststatus'} = '';
10285: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10286: if (ref($usertypes) eq 'HASH') {
10287: my @okstatuses;
10288: foreach my $item (split(/:/,$inststatus)) {
10289: if (defined($usertypes->{$item})) {
10290: push(@okstatuses,$item);
10291: }
10292: }
10293: if (@okstatuses) {
10294: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10295: }
10296: }
10297: }
1.1075 raeburn 10298: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10299: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10300: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10301: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10302: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10303: } else {
10304: $logmsg .= ' during self creation';
10305: }
1.1075 raeburn 10306: my $changed;
10307: if ($newuser) {
10308: $changed = 1;
10309: } else {
10310: foreach my $field (@fields) {
10311: if ($names{$field} ne $oldnames{$field}) {
10312: $changed = 1;
10313: last;
10314: }
10315: }
10316: }
10317: unless ($changed) {
10318: $logmsg = 'No changes in user information needed for: '.$logmsg;
10319: &logthis($logmsg);
10320: return 'ok';
10321: }
10322: my $reply = &put('environment', \%names, $udom,$uname);
10323: if ($reply ne 'ok') {
10324: return 'error: '.$reply;
10325: }
1.1087 raeburn 10326: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10327: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10328: }
1.1075 raeburn 10329: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10330: &devalidate_cache_new('namescache',$uname.':'.$udom);
10331: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10332: &logthis($logmsg);
1.134 albertel 10333: return 'ok';
1.80 www 10334: }
10335:
1.81 www 10336: # -------------------------------------------------------------- Modify student
1.80 www 10337:
1.81 www 10338: sub modifystudent {
10339: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10340: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10341: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10342: if (!$cid) {
1.620 albertel 10343: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10344: return 'not_in_class';
10345: }
1.80 www 10346: }
10347: # --------------------------------------------------------------- Make the user
1.81 www 10348: my $reply=&modifyuser
1.209 matthew 10349: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10350: $desiredhome,$email,$inststatus);
1.80 www 10351: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10352: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10353: # student's environment
1.297 matthew 10354: $uid = undef if (!$forceid);
1.455 albertel 10355: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10356: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10357: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10358: return $reply;
10359: }
10360:
10361: sub modify_student_enrollment {
1.1172.2.23 raeburn 10362: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10363: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10364: my ($cdom,$cnum,$chome);
10365: if (!$cid) {
1.620 albertel 10366: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10367: return 'not_in_class';
10368: }
1.620 albertel 10369: $cdom=$env{'course.'.$cid.'.domain'};
10370: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10371: } else {
10372: ($cdom,$cnum)=split(/_/,$cid);
10373: }
1.620 albertel 10374: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10375: if (!$chome) {
1.457 raeburn 10376: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10377: }
1.455 albertel 10378: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10379: # Make sure the user exists
1.81 www 10380: my $uhome=&homeserver($uname,$udom);
10381: if (($uhome eq '') || ($uhome eq 'no_host')) {
10382: return 'error: no such user';
10383: }
1.297 matthew 10384: # Get student data if we were not given enough information
10385: if (!defined($first) || $first eq '' ||
10386: !defined($last) || $last eq '' ||
10387: !defined($uid) || $uid eq '' ||
10388: !defined($middle) || $middle eq '' ||
10389: !defined($gene) || $gene eq '') {
1.294 matthew 10390: # They did not supply us with enough data to enroll the student, so
10391: # we need to pick up more information.
1.297 matthew 10392: my %tmp = &get('environment',
1.294 matthew 10393: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10394: ,$udom,$uname);
10395:
1.800 albertel 10396: #foreach my $key (keys(%tmp)) {
10397: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10398: #}
1.294 matthew 10399: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10400: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10401: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10402: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10403: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10404: }
1.556 albertel 10405: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10406: my $user = "$uname:$udom";
10407: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10408: my $reply=cput('classlist',
1.1148 raeburn 10409: {$user =>
1.1172.2.76 raeburn 10410: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10411: $cdom,$cnum);
1.1148 raeburn 10412: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10413: &devalidate_getsection_cache($udom,$uname,$cid);
10414: } else {
1.81 www 10415: return 'error: '.$reply;
10416: }
1.297 matthew 10417: # Add student role to user
1.83 www 10418: my $uurl='/'.$cid;
1.81 www 10419: $uurl=~s/\_/\//g;
10420: if ($usec) {
10421: $uurl.='/'.$usec;
10422: }
1.1148 raeburn 10423: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10424: $selfenroll,$context);
10425: if ($result ne 'ok') {
10426: if ($old_entry{$user} ne '') {
10427: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10428: } else {
10429: $reply = &del('classlist',[$user],$cdom,$cnum);
10430: }
10431: }
10432: return $result;
1.21 www 10433: }
10434:
1.556 albertel 10435: sub format_name {
10436: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10437: my $name;
10438: if ($first ne 'lastname') {
10439: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10440: } else {
10441: if ($lastname=~/\S/) {
10442: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10443: $name=~s/\s+,/,/;
10444: } else {
10445: $name.= $firstname.' '.$middlename.' '.$generation;
10446: }
10447: }
10448: $name=~s/^\s+//;
10449: $name=~s/\s+$//;
10450: $name=~s/\s+/ /g;
10451: return $name;
10452: }
10453:
1.84 www 10454: # ------------------------------------------------- Write to course preferences
10455:
10456: sub writecoursepref {
10457: my ($courseid,%prefs)=@_;
10458: $courseid=~s/^\///;
10459: $courseid=~s/\_/\//g;
10460: my ($cdomain,$cnum)=split(/\//,$courseid);
10461: my $chome=homeserver($cnum,$cdomain);
10462: if (($chome eq '') || ($chome eq 'no_host')) {
10463: return 'error: no such course';
10464: }
10465: my $cstring='';
1.800 albertel 10466: foreach my $pref (keys(%prefs)) {
10467: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10468: }
1.84 www 10469: $cstring=~s/\&$//;
10470: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10471: }
10472:
10473: # ---------------------------------------------------------- Make/modify course
10474:
10475: sub createcourse {
1.741 raeburn 10476: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10477: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10478: $url=&declutter($url);
10479: my $cid='';
1.1028 raeburn 10480: if ($context eq 'requestcourses') {
10481: my $can_create = 0;
10482: my ($ownername,$ownerdom) = split(':',$course_owner);
10483: if ($udom eq $ownerdom) {
10484: if (&usertools_access($ownername,$ownerdom,$category,undef,
10485: $context)) {
10486: $can_create = 1;
10487: }
10488: } else {
10489: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10490: $category);
10491: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10492: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10493: if (@curr > 0) {
10494: my @options = qw(approval validate autolimit);
10495: my $optregex = join('|',@options);
10496: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10497: $can_create = 1;
10498: }
10499: }
10500: }
10501: }
10502: if ($can_create) {
10503: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10504: unless (&allowed('ccc',$udom)) {
10505: return 'refused';
10506: }
1.1017 raeburn 10507: }
10508: } else {
10509: return 'refused';
10510: }
1.1028 raeburn 10511: } elsif (!&allowed('ccc',$udom)) {
10512: return 'refused';
1.84 www 10513: }
1.1011 raeburn 10514: # --------------------------------------------------------------- Get Unique ID
10515: my $uname;
10516: if ($cnum =~ /^$match_courseid$/) {
10517: my $chome=&homeserver($cnum,$udom,'true');
10518: if (($chome eq '') || ($chome eq 'no_host')) {
10519: $uname = $cnum;
10520: } else {
1.1038 raeburn 10521: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10522: }
10523: } else {
1.1038 raeburn 10524: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10525: }
10526: return $uname if ($uname =~ /^error/);
10527: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10528: if (!defined($course_server)) {
10529: if (defined(&domain($udom,'primary'))) {
10530: $course_server = &domain($udom,'primary');
10531: } else {
10532: $course_server = $env{'user.home'};
10533: }
10534: }
10535: my %host_servers =
10536: &Apache::lonnet::get_servers($udom,'library');
10537: unless ($host_servers{$course_server}) {
10538: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10539: }
1.84 www 10540: # ------------------------------------------------------------- Make the course
10541: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10542: $course_server);
1.84 www 10543: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10544: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10545: if (($uhome eq '') || ($uhome eq 'no_host')) {
10546: return 'error: no such course';
10547: }
1.271 www 10548: # ----------------------------------------------------------------- Course made
1.516 raeburn 10549: # log existence
1.1029 raeburn 10550: my $now = time;
1.918 raeburn 10551: my $newcourse = {
10552: $udom.'_'.$uname => {
1.921 raeburn 10553: description => $description,
10554: inst_code => $inst_code,
10555: owner => $course_owner,
10556: type => $crstype,
1.1029 raeburn 10557: creator => $env{'user.name'}.':'.
10558: $env{'user.domain'},
10559: created => $now,
10560: context => $context,
1.918 raeburn 10561: },
10562: };
1.921 raeburn 10563: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10564: # set toplevel url
1.271 www 10565: my $topurl=$url;
10566: unless ($nonstandard) {
10567: # ------------------------------------------ For standard courses, make top url
10568: my $mapurl=&clutter($url);
1.278 www 10569: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10570: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10571: <map>
10572: <resource id="1" type="start"></resource>
10573: <resource id="2" src="$mapurl"></resource>
10574: <resource id="3" type="finish"></resource>
10575: <link index="1" from="1" to="2"></link>
10576: <link index="2" from="2" to="3"></link>
10577: </map>
10578: ENDINITMAP
10579: $topurl=&declutter(
1.638 albertel 10580: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10581: );
10582: }
10583: # ----------------------------------------------------------- Write preferences
1.84 www 10584: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10585: ('description' => $description,
10586: 'url' => $topurl,
10587: 'internal.creator' => $env{'user.name'}.':'.
10588: $env{'user.domain'},
10589: 'internal.created' => $now,
10590: 'internal.creationcontext' => $context)
10591: );
1.84 www 10592: return '/'.$udom.'/'.$uname;
10593: }
10594:
1.1011 raeburn 10595: # ------------------------------------------------------------------- Create ID
10596: sub generate_coursenum {
1.1038 raeburn 10597: my ($udom,$crstype) = @_;
1.1011 raeburn 10598: my $domdesc = &domain($udom);
10599: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10600: my $first;
10601: if ($crstype eq 'Community') {
10602: $first = '0';
10603: } else {
10604: $first = int(1+rand(9));
10605: }
10606: my $uname=$first.
1.1011 raeburn 10607: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10608: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10609: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10610: # ----------------------------------------------- Make sure that does not exist
10611: my $uhome=&homeserver($uname,$udom,'true');
10612: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10613: if ($crstype eq 'Community') {
10614: $first = '0';
10615: } else {
10616: $first = int(1+rand(9));
10617: }
10618: $uname=$first.
1.1011 raeburn 10619: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10620: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10621: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10622: $uhome=&homeserver($uname,$udom,'true');
10623: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10624: return 'error: unable to generate unique course-ID';
10625: }
10626: }
10627: return $uname;
10628: }
10629:
1.813 albertel 10630: sub is_course {
1.1167 droeschl 10631: my ($cdom, $cnum) = scalar(@_) == 1 ?
10632: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10633: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10634: my $uhome=&homeserver($cnum,$cdom);
10635: my $iscourse;
10636: if (grep { $_ eq $uhome } current_machine_ids()) {
10637: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10638: } else {
10639: my $hashid = $cdom.':'.$cnum;
10640: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10641: unless (defined($cached)) {
10642: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10643: $cnum,undef,undef,'.');
10644: $iscourse = 0;
10645: if (exists($courses{$cdom.'_'.$cnum})) {
10646: $iscourse = 1;
10647: }
10648: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10649: }
10650: }
10651: return unless($iscourse);
1.1167 droeschl 10652: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10653: }
10654:
1.1015 raeburn 10655: sub store_userdata {
10656: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10657: my $result;
1.1016 raeburn 10658: if ($datakey ne '') {
1.1013 raeburn 10659: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10660: if ($udom eq '' || $uname eq '') {
10661: $udom = $env{'user.domain'};
10662: $uname = $env{'user.name'};
10663: }
10664: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10665: if (($uhome eq '') || ($uhome eq 'no_host')) {
10666: $result = 'error: no_host';
10667: } else {
1.1172.2.138 raeburn 10668: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10669: $storehash->{'host'} = $perlvar{'lonHostID'};
10670:
10671: my $namevalue='';
10672: foreach my $key (keys(%{$storehash})) {
10673: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10674: }
10675: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10676: unless ($namespace eq 'courserequests') {
10677: $datakey = &escape($datakey);
10678: }
1.1105 raeburn 10679: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10680: $namevalue,$uhome);
1.1013 raeburn 10681: }
10682: } else {
10683: $result = 'error: data to store was not a hash reference';
10684: }
10685: } else {
10686: $result= 'error: invalid requestkey';
10687: }
10688: return $result;
10689: }
10690:
1.21 www 10691: # ---------------------------------------------------------- Assign Custom Role
10692:
10693: sub assigncustomrole {
1.957 raeburn 10694: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10695: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10696: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10697: }
10698:
10699: # ----------------------------------------------------------------- Revoke Role
10700:
10701: sub revokerole {
1.957 raeburn 10702: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10703: my $now=time;
1.965 raeburn 10704: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10705: }
10706:
10707: # ---------------------------------------------------------- Revoke Custom Role
10708:
10709: sub revokecustomrole {
1.957 raeburn 10710: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10711: my $now=time;
1.357 www 10712: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10713: $deleteflag,$selfenroll,$context);
1.17 www 10714: }
10715:
1.533 banghart 10716: # ------------------------------------------------------------ Disk usage
1.535 albertel 10717: sub diskusage {
1.955 raeburn 10718: my ($udom,$uname,$directorypath,$getpropath)=@_;
10719: $directorypath =~ s/\/$//;
10720: my $listing=&reply('du2:'.&escape($directorypath).':'
10721: .&escape($getpropath).':'.&escape($uname).':'
10722: .&escape($udom),homeserver($uname,$udom));
10723: if ($listing eq 'unknown_cmd') {
10724: if ($getpropath) {
10725: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10726: }
10727: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10728: }
1.514 albertel 10729: return $listing;
1.512 banghart 10730: }
10731:
1.566 banghart 10732: sub is_locked {
1.1096 raeburn 10733: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10734: my @check;
10735: my $is_locked;
1.1093 raeburn 10736: push (@check,$file_name);
1.613 albertel 10737: my %locked = &get('file_permissions',\@check,
1.620 albertel 10738: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10739: my ($tmp)=keys(%locked);
10740: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10741:
1.566 banghart 10742: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10743: $is_locked = 'false';
10744: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10745: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10746: $is_locked = 'true';
1.1096 raeburn 10747: if (ref($which) eq 'ARRAY') {
10748: push(@{$which},$entry);
10749: } else {
10750: last;
10751: }
1.745 raeburn 10752: }
10753: }
1.566 banghart 10754: } else {
10755: $is_locked = 'false';
10756: }
1.1093 raeburn 10757: return $is_locked;
1.566 banghart 10758: }
10759:
1.759 albertel 10760: sub declutter_portfile {
10761: my ($file) = @_;
1.833 albertel 10762: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10763: return $file;
10764: }
10765:
1.559 banghart 10766: # ------------------------------------------------------------- Mark as Read Only
10767:
10768: sub mark_as_readonly {
10769: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10770: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10771: my ($tmp)=keys(%current_permissions);
10772: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10773: foreach my $file (@{$files}) {
1.759 albertel 10774: $file = &declutter_portfile($file);
1.561 banghart 10775: push(@{$current_permissions{$file}},$what);
1.559 banghart 10776: }
1.613 albertel 10777: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10778: return;
10779: }
10780:
1.572 banghart 10781: # ------------------------------------------------------------Save Selected Files
10782:
10783: sub save_selected_files {
10784: my ($user, $path, @files) = @_;
10785: my $filename = $user."savedfiles";
1.573 banghart 10786: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10787: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10788: foreach my $file (@files) {
1.620 albertel 10789: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10790: }
10791: foreach my $file (@other_files) {
1.574 banghart 10792: print (OUT $file."\n");
1.572 banghart 10793: }
1.574 banghart 10794: close (OUT);
1.572 banghart 10795: return 'ok';
10796: }
10797:
1.574 banghart 10798: sub clear_selected_files {
10799: my ($user) = @_;
10800: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10801: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10802: print (OUT undef);
10803: close (OUT);
10804: return ("ok");
10805: }
10806:
1.572 banghart 10807: sub files_in_path {
10808: my ($user, $path) = @_;
10809: my $filename = $user."savedfiles";
10810: my %return_files;
1.1172.2.96 raeburn 10811: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10812: while (my $line_in = <IN>) {
1.574 banghart 10813: chomp ($line_in);
10814: my @paths_and_file = split (m!/!, $line_in);
10815: my $file_part = pop (@paths_and_file);
10816: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10817: $path_part.='/';
10818: my $path_and_file = $path_part.$file_part;
10819: if ($path_part eq $path) {
10820: $return_files{$file_part}= 'selected';
10821: }
10822: }
1.574 banghart 10823: close (IN);
10824: return (\%return_files);
1.572 banghart 10825: }
10826:
10827: # called in portfolio select mode, to show files selected NOT in current directory
10828: sub files_not_in_path {
10829: my ($user, $path) = @_;
10830: my $filename = $user."savedfiles";
10831: my @return_files;
10832: my $path_part;
1.1172.2.96 raeburn 10833: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10834: while (my $line = <IN>) {
1.572 banghart 10835: #ok, I know it's clunky, but I want it to work
1.800 albertel 10836: my @paths_and_file = split(m|/|, $line);
10837: my $file_part = pop(@paths_and_file);
10838: chomp($file_part);
10839: my $path_part = join('/', @paths_and_file);
1.572 banghart 10840: $path_part .= '/';
10841: my $path_and_file = $path_part.$file_part;
10842: if ($path_part ne $path) {
1.800 albertel 10843: push(@return_files, ($path_and_file));
1.572 banghart 10844: }
10845: }
1.800 albertel 10846: close(OUT);
1.574 banghart 10847: return (@return_files);
1.572 banghart 10848: }
10849:
1.745 raeburn 10850: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10851:
1.745 raeburn 10852: sub get_portfile_permissions {
10853: my ($domain,$user) = @_;
1.613 albertel 10854: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10855: my ($tmp)=keys(%current_permissions);
10856: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10857: return \%current_permissions;
10858: }
10859:
10860: #---------------------------------------------Get portfolio file access controls
10861:
1.749 raeburn 10862: sub get_access_controls {
1.745 raeburn 10863: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10864: my %access;
10865: my $real_file = $file;
10866: $file =~ s/\.meta$//;
1.745 raeburn 10867: if (defined($file)) {
1.749 raeburn 10868: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10869: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10870: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10871: }
10872: }
1.745 raeburn 10873: } else {
1.749 raeburn 10874: foreach my $key (keys(%{$current_permissions})) {
10875: if ($key =~ /\0accesscontrol$/) {
10876: if (defined($group)) {
10877: if ($key !~ m-^\Q$group\E/-) {
10878: next;
10879: }
10880: }
10881: my ($fullpath) = split(/\0/,$key);
10882: if (ref($$current_permissions{$key}) eq 'HASH') {
10883: foreach my $control (keys(%{$$current_permissions{$key}})) {
10884: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10885: }
10886: }
10887: }
10888: }
10889: }
10890: return %access;
10891: }
10892:
10893: sub modify_access_controls {
10894: my ($file_name,$changes,$domain,$user)=@_;
10895: my ($outcome,$deloutcome);
10896: my %store_permissions;
10897: my %new_values;
10898: my %new_control;
10899: my %translation;
10900: my @deletions = ();
10901: my $now = time;
10902: if (exists($$changes{'activate'})) {
10903: if (ref($$changes{'activate'}) eq 'HASH') {
10904: my @newitems = sort(keys(%{$$changes{'activate'}}));
10905: my $numnew = scalar(@newitems);
10906: for (my $i=0; $i<$numnew; $i++) {
10907: my $newkey = $newitems[$i];
10908: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10909: if ($newkey =~ /^\d+:/) {
10910: $newkey =~ s/^(\d+)/$newid/;
10911: $translation{$1} = $newid;
10912: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10913: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10914: $translation{$1} = $newid;
10915: }
1.749 raeburn 10916: $new_values{$file_name."\0".$newkey} =
10917: $$changes{'activate'}{$newitems[$i]};
10918: $new_control{$newkey} = $now;
10919: }
10920: }
10921: }
10922: my %todelete;
10923: my %changed_items;
10924: foreach my $action ('delete','update') {
10925: if (exists($$changes{$action})) {
10926: if (ref($$changes{$action}) eq 'HASH') {
10927: foreach my $key (keys(%{$$changes{$action}})) {
10928: my ($itemnum) = ($key =~ /^([^:]+):/);
10929: if ($action eq 'delete') {
10930: $todelete{$itemnum} = 1;
10931: } else {
10932: $changed_items{$itemnum} = $key;
10933: }
10934: }
1.745 raeburn 10935: }
10936: }
1.749 raeburn 10937: }
10938: # get lock on access controls for file.
10939: my $lockhash = {
10940: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10941: ':'.$env{'user.domain'},
10942: };
10943: my $tries = 0;
10944: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10945:
1.1172.2.79 raeburn 10946: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10947: $tries ++;
1.1172.2.79 raeburn 10948: sleep(0.1);
1.749 raeburn 10949: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10950: }
10951: if ($gotlock eq 'ok') {
10952: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10953: my ($tmp)=keys(%curr_permissions);
10954: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10955: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10956: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10957: if (ref($curr_controls) eq 'HASH') {
10958: foreach my $control_item (keys(%{$curr_controls})) {
10959: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10960: if (defined($todelete{$itemnum})) {
10961: push(@deletions,$file_name."\0".$control_item);
10962: } else {
10963: if (defined($changed_items{$itemnum})) {
10964: $new_control{$changed_items{$itemnum}} = $now;
10965: push(@deletions,$file_name."\0".$control_item);
10966: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10967: } else {
10968: $new_control{$control_item} = $$curr_controls{$control_item};
10969: }
10970: }
1.745 raeburn 10971: }
10972: }
10973: }
1.970 raeburn 10974: my ($group);
10975: if (&is_course($domain,$user)) {
10976: ($group,my $file) = split(/\//,$file_name,2);
10977: }
1.749 raeburn 10978: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10979: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10980: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10981: # remove lock
10982: my @del_lock = ($file_name."\0".'locked_access_records');
10983: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10984: my $sqlresult =
1.970 raeburn 10985: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10986: $group);
1.749 raeburn 10987: } else {
10988: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10989: }
1.749 raeburn 10990: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10991: }
10992:
1.827 raeburn 10993: sub make_public_indefinitely {
10994: my ($requrl) = @_;
10995: my $now = time;
10996: my $action = 'activate';
10997: my $aclnum = 0;
10998: if (&is_portfolio_url($requrl)) {
10999: my (undef,$udom,$unum,$file_name,$group) =
11000: &parse_portfolio_url($requrl);
11001: my $current_perms = &get_portfile_permissions($udom,$unum);
11002: my %access_controls = &get_access_controls($current_perms,
11003: $group,$file_name);
11004: foreach my $key (keys(%{$access_controls{$file_name}})) {
11005: my ($num,$scope,$end,$start) =
11006: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11007: if ($scope eq 'public') {
11008: if ($start <= $now && $end == 0) {
11009: $action = 'none';
11010: } else {
11011: $action = 'update';
11012: $aclnum = $num;
11013: }
11014: last;
11015: }
11016: }
11017: if ($action eq 'none') {
11018: return 'ok';
11019: } else {
11020: my %changes;
11021: my $newend = 0;
11022: my $newstart = $now;
11023: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
11024: $changes{$action}{$newkey} = {
11025: type => 'public',
11026: time => {
11027: start => $newstart,
11028: end => $newend,
11029: },
11030: };
11031: my ($outcome,$deloutcome,$new_values,$translation) =
11032: &modify_access_controls($file_name,\%changes,$udom,$unum);
11033: return $outcome;
11034: }
11035: } else {
11036: return 'invalid';
11037: }
11038: }
11039:
1.745 raeburn 11040: #------------------------------------------------------Get Marked as Read Only
11041:
11042: sub get_marked_as_readonly {
11043: my ($domain,$user,$what,$group) = @_;
11044: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11045: my @readonly_files;
1.629 banghart 11046: my $cmp1=$what;
11047: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11048: while (my ($file_name,$value) = each(%{$current_permissions})) {
11049: if (defined($group)) {
11050: if ($file_name !~ m-^\Q$group\E/-) {
11051: next;
11052: }
11053: }
1.561 banghart 11054: if (ref($value) eq "ARRAY"){
11055: foreach my $stored_what (@{$value}) {
1.629 banghart 11056: my $cmp2=$stored_what;
1.759 albertel 11057: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11058: $cmp2=join('',@{$stored_what});
1.745 raeburn 11059: }
1.629 banghart 11060: if ($cmp1 eq $cmp2) {
1.561 banghart 11061: push(@readonly_files, $file_name);
1.745 raeburn 11062: last;
1.563 banghart 11063: } elsif (!defined($what)) {
11064: push(@readonly_files, $file_name);
1.745 raeburn 11065: last;
1.561 banghart 11066: }
11067: }
1.745 raeburn 11068: }
1.561 banghart 11069: }
11070: return @readonly_files;
11071: }
1.577 banghart 11072: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11073:
1.577 banghart 11074: sub get_marked_as_readonly_hash {
1.745 raeburn 11075: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11076: my %readonly_files;
1.745 raeburn 11077: while (my ($file_name,$value) = each(%{$current_permissions})) {
11078: if (defined($group)) {
11079: if ($file_name !~ m-^\Q$group\E/-) {
11080: next;
11081: }
11082: }
1.577 banghart 11083: if (ref($value) eq "ARRAY"){
11084: foreach my $stored_what (@{$value}) {
1.745 raeburn 11085: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11086: foreach my $lock_descriptor(@{$stored_what}) {
11087: if ($lock_descriptor eq 'graded') {
11088: $readonly_files{$file_name} = 'graded';
11089: } elsif ($lock_descriptor eq 'handback') {
11090: $readonly_files{$file_name} = 'handback';
11091: } else {
11092: if (!exists($readonly_files{$file_name})) {
11093: $readonly_files{$file_name} = 'locked';
11094: }
11095: }
1.745 raeburn 11096: }
1.750 banghart 11097: }
1.577 banghart 11098: }
11099: }
11100: }
11101: return %readonly_files;
11102: }
1.559 banghart 11103: # ------------------------------------------------------------ Unmark as Read Only
11104:
11105: sub unmark_as_readonly {
1.629 banghart 11106: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11107: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11108: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11109: $file_name = &declutter_portfile($file_name);
1.634 albertel 11110: my $symb_crs = $what;
11111: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11112: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11113: my ($tmp)=keys(%current_permissions);
11114: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11115: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11116: foreach my $file (@readonly_files) {
1.759 albertel 11117: my $clean_file = &declutter_portfile($file);
11118: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11119: my $current_locks = $current_permissions{$file};
1.563 banghart 11120: my @new_locks;
11121: my @del_keys;
11122: if (ref($current_locks) eq "ARRAY"){
11123: foreach my $locker (@{$current_locks}) {
1.632 albertel 11124: my $compare=$locker;
1.749 raeburn 11125: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11126: $compare=join('',@{$locker});
1.746 raeburn 11127: if ($compare ne $symb_crs) {
11128: push(@new_locks, $locker);
11129: }
1.563 banghart 11130: }
11131: }
1.650 albertel 11132: if (scalar(@new_locks) > 0) {
1.563 banghart 11133: $current_permissions{$file} = \@new_locks;
11134: } else {
11135: push(@del_keys, $file);
1.613 albertel 11136: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11137: delete($current_permissions{$file});
1.563 banghart 11138: }
11139: }
1.561 banghart 11140: }
1.613 albertel 11141: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11142: return;
11143: }
1.512 banghart 11144:
1.17 www 11145: # ------------------------------------------------------------ Directory lister
11146:
11147: sub dirlist {
1.955 raeburn 11148: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11149: $uri=~s/^\///;
11150: $uri=~s/\/$//;
1.253 stredwic 11151: my ($udom, $uname);
1.955 raeburn 11152: if ($getuserdir) {
1.253 stredwic 11153: $udom = $userdomain;
11154: $uname = $username;
1.955 raeburn 11155: } else {
11156: (undef,$udom,$uname)=split(/\//,$uri);
11157: if(defined($userdomain)) {
11158: $udom = $userdomain;
11159: }
11160: if(defined($username)) {
11161: $uname = $username;
11162: }
1.253 stredwic 11163: }
1.955 raeburn 11164: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11165:
1.955 raeburn 11166: $dirRoot = $perlvar{'lonDocRoot'};
11167: if (defined($getpropath)) {
11168: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11169: $dirRoot =~ s/\/$//;
1.955 raeburn 11170: } elsif (defined($getuserdir)) {
11171: my $subdir=$uname.'__';
11172: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11173: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11174: ."/$udom/$subdir/$uname";
11175: } elsif (defined($alternateRoot)) {
11176: $dirRoot = $alternateRoot;
1.751 banghart 11177: }
1.253 stredwic 11178:
11179: if($udom) {
11180: if($uname) {
1.1135 raeburn 11181: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11182: if ($uhome eq 'no_host') {
11183: return ([],'no_host');
11184: }
1.955 raeburn 11185: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11186: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11187: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11188: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11189: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11190: } else {
11191: @listing_results = map { &unescape($_); } split(/:/,$listing);
11192: }
1.605 matthew 11193: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11194: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11195: @listing_results = split(/:/,$listing);
11196: } else {
11197: @listing_results = map { &unescape($_); } split(/:/,$listing);
11198: }
1.1135 raeburn 11199: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11200: ($listing eq 'rejected') || ($listing eq 'refused') ||
11201: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11202: return ([],$listing);
11203: } else {
11204: return (\@listing_results);
1.1135 raeburn 11205: }
1.955 raeburn 11206: } elsif(!$alternateRoot) {
1.1136 raeburn 11207: my (%allusers,%listerror);
1.841 albertel 11208: my %servers = &get_servers($udom,'library');
1.955 raeburn 11209: foreach my $tryserver (keys(%servers)) {
11210: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11211: &escape($udom),$tryserver);
11212: if ($listing eq 'unknown_cmd') {
11213: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11214: $udom, $tryserver);
11215: } else {
11216: @listing_results = map { &unescape($_); } split(/:/,$listing);
11217: }
1.841 albertel 11218: if ($listing eq 'unknown_cmd') {
11219: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11220: $udom, $tryserver);
11221: @listing_results = split(/:/,$listing);
11222: } else {
11223: @listing_results =
11224: map { &unescape($_); } split(/:/,$listing);
11225: }
1.1136 raeburn 11226: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11227: ($listing eq 'rejected') || ($listing eq 'refused') ||
11228: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11229: $listerror{$tryserver} = $listing;
11230: } else {
1.841 albertel 11231: foreach my $line (@listing_results) {
11232: my ($entry) = split(/&/,$line,2);
11233: $allusers{$entry} = 1;
11234: }
11235: }
1.253 stredwic 11236: }
1.1136 raeburn 11237: my @alluserslist=();
1.800 albertel 11238: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11239: push(@alluserslist,$user.'&user');
1.253 stredwic 11240: }
1.1172.2.80 raeburn 11241: if (!%listerror) {
11242: # no errors
11243: return (\@alluserslist);
11244: } elsif (scalar(keys(%servers)) == 1) {
11245: # one library server, one error
11246: my ($key) = keys(%listerror);
11247: return (\@alluserslist, $listerror{$key});
11248: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11249: # con_lost indicates that we might miss data from at least one
11250: # library server
11251: return (\@alluserslist, 'con_lost');
11252: } else {
11253: # multiple library servers and no con_lost -> data should be
11254: # complete.
11255: return (\@alluserslist);
11256: }
11257:
1.253 stredwic 11258: } else {
1.1136 raeburn 11259: return ([],'missing username');
1.253 stredwic 11260: }
1.955 raeburn 11261: } elsif(!defined($getpropath)) {
1.1136 raeburn 11262: my $path = $perlvar{'lonDocRoot'}.'/res/';
11263: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11264: return (\@all_domains);
1.955 raeburn 11265: } else {
1.1136 raeburn 11266: return ([],'missing domain');
1.275 stredwic 11267: }
11268: }
11269:
11270: # --------------------------------------------- GetFileTimestamp
11271: # This function utilizes dirlist and returns the date stamp for
11272: # when it was last modified. It will also return an error of -1
11273: # if an error occurs
11274:
11275: sub GetFileTimestamp {
1.955 raeburn 11276: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11277: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11278: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11279: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11280: undef,$getuserdir);
11281: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11282: return -1;
11283: }
11284: if (ref($fileref) eq 'ARRAY') {
11285: my @stats = split('&',$fileref->[0]);
1.375 matthew 11286: # @stats contains first the filename, then the stat output
11287: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11288: } else {
11289: return -1;
1.253 stredwic 11290: }
1.26 www 11291: }
11292:
1.712 albertel 11293: sub stat_file {
11294: my ($uri) = @_;
1.787 albertel 11295: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11296:
1.955 raeburn 11297: my ($udom,$uname,$file);
1.712 albertel 11298: if ($uri =~ m-^/(uploaded|editupload)/-) {
11299: ($udom,$uname,$file) =
1.811 albertel 11300: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11301: $file = 'userfiles/'.$file;
11302: }
11303: if ($uri =~ m-^/res/-) {
11304: ($udom,$uname) =
1.807 albertel 11305: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11306: $file = $uri;
11307: }
11308:
11309: if (!$udom || !$uname || !$file) {
11310: # unable to handle the uri
11311: return ();
11312: }
1.956 raeburn 11313: my $getpropath;
11314: if ($file =~ /^userfiles\//) {
11315: $getpropath = 1;
11316: }
1.1136 raeburn 11317: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11318: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11319: return ();
11320: } else {
11321: if (ref($listref) eq 'ARRAY') {
11322: my @stats = split('&',$listref->[0]);
11323: shift(@stats); #filename is first
11324: return @stats;
11325: }
1.712 albertel 11326: }
11327: return ();
11328: }
11329:
1.26 www 11330: # -------------------------------------------------------- Value of a Condition
11331:
1.713 albertel 11332: # gets the value of a specific preevaluated condition
11333: # stored in the string $env{user.state.<cid>}
11334: # or looks up a condition reference in the bighash and if if hasn't
11335: # already been evaluated recurses into docondval to get the value of
11336: # the condition, then memoizing it to
11337: # $env{user.state.<cid>.<condition>}
1.40 www 11338: sub directcondval {
11339: my $number=shift;
1.620 albertel 11340: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11341: &Apache::lonuserstate::evalstate();
11342: }
1.713 albertel 11343: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11344: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11345: } elsif ($number =~ /^_/) {
11346: my $sub_condition;
11347: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11348: &GDBM_READER(),0640)) {
11349: $sub_condition=$bighash{'conditions'.$number};
11350: untie(%bighash);
11351: }
11352: my $value = &docondval($sub_condition);
1.949 raeburn 11353: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11354: return $value;
11355: }
1.620 albertel 11356: if ($env{'user.state.'.$env{'request.course.id'}}) {
11357: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11358: } else {
11359: return 2;
11360: }
11361: }
11362:
1.713 albertel 11363: # get the collection of conditions for this resource
1.26 www 11364: sub condval {
11365: my $condidx=shift;
1.54 www 11366: my $allpathcond='';
1.713 albertel 11367: foreach my $cond (split(/\|/,$condidx)) {
11368: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11369: $allpathcond.=
11370: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11371: }
1.191 harris41 11372: }
1.54 www 11373: $allpathcond=~s/\|$//;
1.713 albertel 11374: return &docondval($allpathcond);
11375: }
11376:
11377: #evaluates an expression of conditions
11378: sub docondval {
11379: my ($allpathcond) = @_;
11380: my $result=0;
11381: if ($env{'request.course.id'}
11382: && defined($allpathcond)) {
11383: my $operand='|';
11384: my @stack;
11385: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11386: if ($chunk eq '(') {
11387: push @stack,($operand,$result);
11388: } elsif ($chunk eq ')') {
11389: my $before=pop @stack;
11390: if (pop @stack eq '&') {
11391: $result=$result>$before?$before:$result;
11392: } else {
11393: $result=$result>$before?$result:$before;
11394: }
11395: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11396: $operand=$chunk;
11397: } else {
11398: my $new=directcondval($chunk);
11399: if ($operand eq '&') {
11400: $result=$result>$new?$new:$result;
11401: } else {
11402: $result=$result>$new?$result:$new;
11403: }
11404: }
11405: }
1.26 www 11406: }
11407: return $result;
1.421 albertel 11408: }
11409:
11410: # ---------------------------------------------------- Devalidate courseresdata
11411:
11412: sub devalidatecourseresdata {
11413: my ($coursenum,$coursedomain)=@_;
11414: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11415: &devalidate_cache_new('courseres',$hashid);
1.28 www 11416: }
11417:
1.763 www 11418:
1.200 www 11419: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11420: #
11421: # Parameters:
11422: # $coursenum - Number of the course.
11423: # $coursedomain - Domain at which the course was created.
11424: # Returns:
11425: # A hash of the course parameters along (I think) with timestamps
11426: # and version info.
1.877 foxr 11427:
1.624 albertel 11428: sub get_courseresdata {
11429: my ($coursenum,$coursedomain)=@_;
1.200 www 11430: my $coursehom=&homeserver($coursenum,$coursedomain);
11431: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11432: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11433: my %dumpreply;
1.417 albertel 11434: unless (defined($cached)) {
1.624 albertel 11435: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11436: $result=\%dumpreply;
1.251 albertel 11437: my ($tmp) = keys(%dumpreply);
11438: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11439: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11440: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11441: return $tmp;
1.416 albertel 11442: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11443: $result=undef;
1.599 albertel 11444: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11445: }
11446: }
1.624 albertel 11447: return $result;
11448: }
11449:
1.633 albertel 11450: sub devalidateuserresdata {
11451: my ($uname,$udom)=@_;
11452: my $hashid="$udom:$uname";
11453: &devalidate_cache_new('userres',$hashid);
11454: }
11455:
1.624 albertel 11456: sub get_userresdata {
11457: my ($uname,$udom)=@_;
11458: #most student don\'t have any data set, check if there is some data
11459: if (&EXT_cache_status($udom,$uname)) { return undef; }
11460:
11461: my $hashid="$udom:$uname";
11462: my ($result,$cached)=&is_cached_new('userres',$hashid);
11463: if (!defined($cached)) {
11464: my %resourcedata=&dump('resourcedata',$udom,$uname);
11465: $result=\%resourcedata;
11466: &do_cache_new('userres',$hashid,$result,600);
11467: }
11468: my ($tmp)=keys(%$result);
11469: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11470: return $result;
11471: }
11472: #error 2 occurs when the .db doesn't exist
11473: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11474: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11475: &logthis("<font color=\"blue\">WARNING:".
11476: " Trying to get resource data for ".
11477: $uname." at ".$udom.": ".
11478: $tmp."</font>");
11479: }
1.624 albertel 11480: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11481: #&EXT_cache_set($udom,$uname);
11482: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11483: undef($tmp); # not really an error so don't send it back
1.624 albertel 11484: }
11485: return $tmp;
11486: }
1.879 foxr 11487: #----------------------------------------------- resdata - return resource data
11488: # Purpose:
11489: # Return resource data for either users or for a course.
11490: # Parameters:
11491: # $name - Course/user name.
11492: # $domain - Name of the domain the user/course is registered on.
11493: # $type - Type of thing $name is (must be 'course' or 'user'
11494: # @which - Array of names of resources desired.
11495: # Returns:
11496: # The value of the first reasource in @which that is found in the
11497: # resource hash.
11498: # Exceptional Conditions:
11499: # If the $type passed in is not valid (not the string 'course' or
11500: # 'user', an undefined reference is returned.
11501: # If none of the resources are found, an undef is returned
1.624 albertel 11502: sub resdata {
11503: my ($name,$domain,$type,@which)=@_;
11504: my $result;
11505: if ($type eq 'course') {
11506: $result=&get_courseresdata($name,$domain);
11507: } elsif ($type eq 'user') {
11508: $result=&get_userresdata($name,$domain);
11509: }
11510: if (!ref($result)) { return $result; }
1.251 albertel 11511: foreach my $item (@which) {
1.927 albertel 11512: if (defined($result->{$item->[0]})) {
11513: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11514: }
1.250 albertel 11515: }
1.291 albertel 11516: return undef;
1.200 www 11517: }
11518:
1.1172.2.31 raeburn 11519: sub get_numsuppfiles {
11520: my ($cnum,$cdom,$ignorecache)=@_;
11521: my $hashid=$cnum.':'.$cdom;
11522: my ($suppcount,$cached);
11523: unless ($ignorecache) {
11524: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11525: }
11526: unless (defined($cached)) {
11527: my $chome=&homeserver($cnum,$cdom);
11528: unless ($chome eq 'no_host') {
11529: ($suppcount,my $errors) = (0,0);
11530: my $suppmap = 'supplemental.sequence';
11531: ($suppcount,$errors) =
11532: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11533: }
11534: &do_cache_new('suppcount',$hashid,$suppcount,600);
11535: }
11536: return $suppcount;
11537: }
11538:
1.379 matthew 11539: #
11540: # EXT resource caching routines
11541: #
11542:
11543: sub clear_EXT_cache_status {
1.383 albertel 11544: &delenv('cache.EXT.');
1.379 matthew 11545: }
11546:
11547: sub EXT_cache_status {
11548: my ($target_domain,$target_user) = @_;
1.383 albertel 11549: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11550: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11551: # We know already the user has no data
11552: return 1;
11553: } else {
11554: return 0;
11555: }
11556: }
11557:
11558: sub EXT_cache_set {
11559: my ($target_domain,$target_user) = @_;
1.383 albertel 11560: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11561: #&appenv({$cachename => time});
1.379 matthew 11562: }
11563:
1.28 www 11564: # --------------------------------------------------------- Value of a Variable
1.58 www 11565: sub EXT {
1.715 albertel 11566:
1.1172.2.28 raeburn 11567: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11568: unless ($varname) { return ''; }
1.218 albertel 11569: #get real user name/domain, courseid and symb
11570: my $courseid;
1.359 albertel 11571: my $publicuser;
1.427 www 11572: if ($symbparm) {
11573: $symbparm=&get_symb_from_alias($symbparm);
11574: }
1.218 albertel 11575: if (!($uname && $udom)) {
1.790 albertel 11576: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11577: if (!$symbparm) { $symbparm=$cursymb; }
11578: } else {
1.620 albertel 11579: $courseid=$env{'request.course.id'};
1.218 albertel 11580: }
1.48 www 11581: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11582: my $rest;
1.320 albertel 11583: if (defined($therest[0])) {
1.48 www 11584: $rest=join('.',@therest);
11585: } else {
11586: $rest='';
11587: }
1.320 albertel 11588:
1.57 www 11589: my $qualifierrest=$qualifier;
11590: if ($rest) { $qualifierrest.='.'.$rest; }
11591: my $spacequalifierrest=$space;
11592: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11593: if ($realm eq 'user') {
1.48 www 11594: # --------------------------------------------------------------- user.resource
11595: if ($space eq 'resource') {
1.651 albertel 11596: if ( (defined($Apache::lonhomework::parsing_a_problem)
11597: || defined($Apache::lonhomework::parsing_a_task))
11598: &&
1.1172.2.142 raeburn 11599: ($symbparm eq &symbread()) ) {
1.744 albertel 11600: # if we are in the middle of processing the resource the
11601: # get the value we are planning on committing
11602: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11603: return $Apache::lonhomework::results{$qualifierrest};
11604: } else {
11605: return $Apache::lonhomework::history{$qualifierrest};
11606: }
1.335 albertel 11607: } else {
1.359 albertel 11608: my %restored;
1.620 albertel 11609: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11610: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11611: } else {
11612: %restored=&restore($symbparm,$courseid,$udom,$uname);
11613: }
1.335 albertel 11614: return $restored{$qualifierrest};
11615: }
1.48 www 11616: # ----------------------------------------------------------------- user.access
11617: } elsif ($space eq 'access') {
1.218 albertel 11618: # FIXME - not supporting calls for a specific user
1.48 www 11619: return &allowed($qualifier,$rest);
11620: # ------------------------------------------ user.preferences, user.environment
11621: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11622: if (($uname eq $env{'user.name'}) &&
11623: ($udom eq $env{'user.domain'})) {
11624: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11625: } else {
1.359 albertel 11626: my %returnhash;
11627: if (!$publicuser) {
11628: %returnhash=&userenvironment($udom,$uname,
11629: $qualifierrest);
11630: }
1.218 albertel 11631: return $returnhash{$qualifierrest};
11632: }
1.48 www 11633: # ----------------------------------------------------------------- user.course
11634: } elsif ($space eq 'course') {
1.218 albertel 11635: # FIXME - not supporting calls for a specific user
1.620 albertel 11636: return $env{join('.',('request.course',$qualifier))};
1.48 www 11637: # ------------------------------------------------------------------- user.role
11638: } elsif ($space eq 'role') {
1.218 albertel 11639: # FIXME - not supporting calls for a specific user
1.620 albertel 11640: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11641: if ($qualifier eq 'value') {
11642: return $role;
11643: } elsif ($qualifier eq 'extent') {
11644: return $where;
11645: }
11646: # ----------------------------------------------------------------- user.domain
11647: } elsif ($space eq 'domain') {
1.218 albertel 11648: return $udom;
1.48 www 11649: # ------------------------------------------------------------------- user.name
11650: } elsif ($space eq 'name') {
1.218 albertel 11651: return $uname;
1.48 www 11652: # ---------------------------------------------------- Any other user namespace
1.29 www 11653: } else {
1.359 albertel 11654: my %reply;
11655: if (!$publicuser) {
11656: %reply=&get($space,[$qualifierrest],$udom,$uname);
11657: }
11658: return $reply{$qualifierrest};
1.48 www 11659: }
1.236 www 11660: } elsif ($realm eq 'query') {
11661: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11662: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11663: [$spacequalifierrest]);
1.620 albertel 11664: return $env{'form.'.$spacequalifierrest};
1.236 www 11665: } elsif ($realm eq 'request') {
1.48 www 11666: # ------------------------------------------------------------- request.browser
11667: if ($space eq 'browser') {
1.1145 bisitz 11668: return $env{'browser.'.$qualifier};
1.57 www 11669: # ------------------------------------------------------------ request.filename
11670: } else {
1.620 albertel 11671: return $env{'request.'.$spacequalifierrest};
1.29 www 11672: }
1.28 www 11673: } elsif ($realm eq 'course') {
1.48 www 11674: # ---------------------------------------------------------- course.description
1.620 albertel 11675: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11676: } elsif ($realm eq 'resource') {
1.165 www 11677:
1.620 albertel 11678: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11679: if (!$symbparm) { $symbparm=&symbread(); }
11680: }
1.693 albertel 11681:
1.1172.2.30 raeburn 11682: if ($qualifier eq '') {
11683: if ($space eq 'title') {
11684: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11685: return &gettitle($symbparm);
11686: }
1.693 albertel 11687:
1.1172.2.30 raeburn 11688: if ($space eq 'map') {
11689: my ($map) = &decode_symb($symbparm);
11690: return &symbread($map);
11691: }
11692: if ($space eq 'maptitle') {
11693: my ($map) = &decode_symb($symbparm);
11694: return &gettitle($map);
11695: }
11696: if ($space eq 'filename') {
11697: if ($symbparm) {
11698: return &clutter((&decode_symb($symbparm))[2]);
11699: }
11700: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11701: }
1.1172.2.30 raeburn 11702:
11703: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11704: if ($space eq 'visibleparts') {
11705: my $navmap = Apache::lonnavmaps::navmap->new();
11706: my $item;
11707: if (ref($navmap)) {
11708: my $res = $navmap->getBySymb($symbparm);
11709: my $parts = $res->parts();
11710: if (ref($parts) eq 'ARRAY') {
11711: $item = join(',',@{$parts});
11712: }
11713: undef($navmap);
11714: }
11715: return $item;
11716: }
11717: }
11718: }
1.693 albertel 11719:
11720: my ($section, $group, @groups);
1.593 albertel 11721: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11722: if (($courseid eq '') && ($cid)) {
11723: $courseid = $cid;
11724: }
11725: if (($symbparm && $courseid) &&
11726: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11727:
1.218 albertel 11728: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11729:
1.60 www 11730: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11731: my $symbp=$symbparm;
1.735 albertel 11732: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11733:
11734: my $symbparm=$symbp.'.'.$spacequalifierrest;
11735: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11736:
1.620 albertel 11737: if (($env{'user.name'} eq $uname) &&
11738: ($env{'user.domain'} eq $udom)) {
11739: $section=$env{'request.course.sec'};
1.733 raeburn 11740: @groups = split(/:/,$env{'request.course.groups'});
11741: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11742: } else {
1.539 albertel 11743: if (! defined($usection)) {
1.551 albertel 11744: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11745: } else {
11746: $section = $usection;
11747: }
1.733 raeburn 11748: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11749: }
11750:
11751: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11752: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11753: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11754:
1.593 albertel 11755: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11756: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11757: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11758:
1.60 www 11759: # ----------------------------------------------------------- first, check user
1.624 albertel 11760:
11761: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11762: ([$courselevelr,'resource'],
11763: [$courselevelm,'map' ],
11764: [$courselevel, 'course' ]));
1.931 albertel 11765: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11766:
1.594 albertel 11767: # ------------------------------------------------ second, check some of course
1.684 raeburn 11768: my $coursereply;
1.691 raeburn 11769: if (@groups > 0) {
11770: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11771: $mapparm,$spacequalifierrest);
1.927 albertel 11772: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11773: }
1.96 www 11774:
1.684 raeburn 11775: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11776: $env{'course.'.$courseid.'.domain'},
11777: 'course',
11778: ([$seclevelr, 'resource'],
11779: [$seclevelm, 'map' ],
11780: [$seclevel, 'course' ],
11781: [$courselevelr,'resource']));
11782: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11783:
1.60 www 11784: # ------------------------------------------------------ third, check map parms
1.218 albertel 11785: my %parmhash=();
11786: my $thisparm='';
11787: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11788: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11789: &GDBM_READER(),0640)) {
1.218 albertel 11790: $thisparm=$parmhash{$symbparm};
11791: untie(%parmhash);
11792: }
1.927 albertel 11793: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11794: }
1.594 albertel 11795: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11796:
1.218 albertel 11797: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11798: my $filename;
11799: if (!$symbparm) { $symbparm=&symbread(); }
11800: if ($symbparm) {
1.409 www 11801: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11802: } else {
1.620 albertel 11803: $filename=$env{'request.filename'};
1.282 albertel 11804: }
11805: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11806: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11807: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11808: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11809:
1.927 albertel 11810: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11811: if ($symbparm && defined($courseid) &&
1.620 albertel 11812: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11813: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11814: $env{'course.'.$courseid.'.domain'},
11815: 'course',
1.927 albertel 11816: ([$courselevelm,'map' ],
11817: [$courselevel, 'course']));
11818: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11819: }
1.145 www 11820: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11821: unless ($space eq '0') {
1.336 albertel 11822: my @parts=split(/_/,$space);
11823: my $id=pop(@parts);
11824: my $part=join('_',@parts);
11825: if ($part eq '') { $part='0'; }
1.927 albertel 11826: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11827: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11828: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11829: }
1.395 albertel 11830: if ($recurse) { return undef; }
11831: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11832: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11833: # ---------------------------------------------------- Any other user namespace
11834: } elsif ($realm eq 'environment') {
11835: # ----------------------------------------------------------------- environment
1.620 albertel 11836: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11837: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11838: } else {
1.770 albertel 11839: if ($uname eq 'anonymous' && $udom eq '') {
11840: return '';
11841: }
1.219 albertel 11842: my %returnhash=&userenvironment($udom,$uname,
11843: $spacequalifierrest);
11844: return $returnhash{$spacequalifierrest};
11845: }
1.28 www 11846: } elsif ($realm eq 'system') {
1.48 www 11847: # ----------------------------------------------------------------- system.time
11848: if ($space eq 'time') {
11849: return time;
11850: }
1.696 albertel 11851: } elsif ($realm eq 'server') {
11852: # ----------------------------------------------------------------- system.time
11853: if ($space eq 'name') {
11854: return $ENV{'SERVER_NAME'};
11855: }
1.28 www 11856: }
1.48 www 11857: return '';
1.61 www 11858: }
11859:
1.927 albertel 11860: sub get_reply {
11861: my ($reply_value) = @_;
1.940 raeburn 11862: if (ref($reply_value) eq 'ARRAY') {
11863: if (wantarray) {
11864: return @$reply_value;
11865: }
11866: return $reply_value->[0];
11867: } else {
11868: return $reply_value;
1.927 albertel 11869: }
11870: }
11871:
1.691 raeburn 11872: sub check_group_parms {
11873: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11874: my @groupitems = ();
11875: my $resultitem;
1.927 albertel 11876: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11877: foreach my $group (@{$groups}) {
11878: foreach my $level (@levels) {
1.927 albertel 11879: my $item = $courseid.'.['.$group.'].'.$level->[0];
11880: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11881: }
11882: }
11883: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11884: $env{'course.'.$courseid.'.domain'},
11885: 'course',@groupitems);
11886: return $coursereply;
11887: }
11888:
11889: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11890: my ($courseid,@groups) = @_;
11891: @groups = sort(@groups);
1.691 raeburn 11892: return @groups;
11893: }
11894:
1.395 albertel 11895: sub packages_tab_default {
11896: my ($uri,$varname)=@_;
11897: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11898:
11899: my (@extension,@specifics,$do_default);
11900: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11901: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11902: if ($pack_type eq 'default') {
11903: $do_default=1;
11904: } elsif ($pack_type eq 'extension') {
11905: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11906: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11907: # only look at packages defaults for packages that this id is
1.738 albertel 11908: push(@specifics,[$package,$pack_type,$pack_part]);
11909: }
11910: }
11911: # first look for a package that matches the requested part id
11912: foreach my $package (@specifics) {
11913: my (undef,$pack_type,$pack_part)=@{$package};
11914: next if ($pack_part ne $part);
11915: if (defined($packagetab{"$pack_type&$name&default"})) {
11916: return $packagetab{"$pack_type&$name&default"};
11917: }
11918: }
11919: # look for any possible matching non extension_ package
11920: foreach my $package (@specifics) {
11921: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11922: if (defined($packagetab{"$pack_type&$name&default"})) {
11923: return $packagetab{"$pack_type&$name&default"};
11924: }
1.585 albertel 11925: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11926: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11927: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11928: }
11929: }
1.738 albertel 11930: # look for any posible extension_ match
11931: foreach my $package (@extension) {
11932: my ($package,$pack_type)=@{$package};
11933: if (defined($packagetab{"$pack_type&$name&default"})) {
11934: return $packagetab{"$pack_type&$name&default"};
11935: }
11936: if (defined($packagetab{$package."&$name&default"})) {
11937: return $packagetab{$package."&$name&default"};
11938: }
11939: }
11940: # look for a global default setting
11941: if ($do_default && defined($packagetab{"default&$name&default"})) {
11942: return $packagetab{"default&$name&default"};
11943: }
1.395 albertel 11944: return undef;
11945: }
11946:
1.334 albertel 11947: sub add_prefix_and_part {
11948: my ($prefix,$part)=@_;
11949: my $keyroot;
11950: if (defined($prefix) && $prefix !~ /^__/) {
11951: # prefix that has a part already
11952: $keyroot=$prefix;
11953: } elsif (defined($prefix)) {
11954: # prefix that is missing a part
11955: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11956: } else {
11957: # no prefix at all
11958: if (defined($part)) { $keyroot='_'.$part; }
11959: }
11960: return $keyroot;
11961: }
11962:
1.71 www 11963: # ---------------------------------------------------------------- Get metadata
11964:
1.599 albertel 11965: my %metaentry;
1.1070 www 11966: my %importedpartids;
1.1172.2.99 raeburn 11967: my %importedrespids;
1.71 www 11968: sub metadata {
1.176 www 11969: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11970: $uri=&declutter($uri);
1.288 albertel 11971: # if it is a non metadata possible uri return quickly
1.529 albertel 11972: if (($uri eq '') ||
11973: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11974: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11975: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11976: return undef;
11977: }
1.1172.2.49 raeburn 11978: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11979: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11980: return undef;
1.288 albertel 11981: }
1.73 www 11982: my $filename=$uri;
11983: $uri=~s/\.meta$//;
1.172 www 11984: #
11985: # Is the metadata already cached?
1.177 www 11986: # Look at timestamp of caching
1.172 www 11987: # Everything is cached by the main uri, libraries are never directly cached
11988: #
1.428 albertel 11989: if (!defined($liburi)) {
1.599 albertel 11990: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11991: if (defined($cached)) { return $result->{':'.$what}; }
11992: }
11993: {
1.1069 www 11994: # Imported parts would go here
1.1172.2.99 raeburn 11995: my @origfiletagids=();
1.1069 www 11996: my $importedparts=0;
1.1172.2.99 raeburn 11997:
11998: # Imported responseids would go here
11999: my $importedresponses=0;
1.172 www 12000: #
12001: # Is this a recursive call for a library?
12002: #
1.599 albertel 12003: # if (! exists($metacache{$uri})) {
12004: # $metacache{$uri}={};
12005: # }
1.924 albertel 12006: my $cachetime = 60*60;
1.171 www 12007: if ($liburi) {
12008: $liburi=&declutter($liburi);
12009: $filename=$liburi;
1.401 bowersj2 12010: } else {
1.599 albertel 12011: &devalidate_cache_new('meta',$uri);
12012: undef(%metaentry);
1.401 bowersj2 12013: }
1.140 www 12014: my %metathesekeys=();
1.73 www 12015: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12016: my $metastring;
1.1140 www 12017: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12018: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12019: $metastring =
1.929 albertel 12020: &Apache::lonnet::ssi_body($which,
1.924 albertel 12021: ('grade_target' => 'meta'));
12022: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12023: } elsif (($uri !~ m -^(editupload)/-) &&
12024: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12025: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12026: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12027: $metastring=&getfile($file);
1.489 albertel 12028: }
1.208 albertel 12029: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12030: my $token;
1.140 www 12031: undef %metathesekeys;
1.71 www 12032: while ($token=$parser->get_token) {
1.339 albertel 12033: if ($token->[0] eq 'S') {
12034: if (defined($token->[2]->{'package'})) {
1.172 www 12035: #
12036: # This is a package - get package info
12037: #
1.339 albertel 12038: my $package=$token->[2]->{'package'};
12039: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12040: if (defined($token->[2]->{'id'})) {
12041: $keyroot.='_'.$token->[2]->{'id'};
12042: }
1.599 albertel 12043: if ($metaentry{':packages'}) {
12044: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12045: } else {
1.599 albertel 12046: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12047: }
1.736 albertel 12048: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12049: my $part=$keyroot;
12050: $part=~s/^\_//;
1.736 albertel 12051: if ($pack_entry=~/^\Q$package\E\&/ ||
12052: $pack_entry=~/^\Q$package\E_0\&/) {
12053: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12054: # ignore package.tab specified default values
12055: # here &package_tab_default() will fetch those
12056: if ($subp eq 'default') { next; }
1.736 albertel 12057: my $value=$packagetab{$pack_entry};
1.432 albertel 12058: my $unikey;
12059: if ($pack =~ /_0$/) {
12060: $unikey='parameter_0_'.$name;
12061: $part=0;
12062: } else {
12063: $unikey='parameter'.$keyroot.'_'.$name;
12064: }
1.339 albertel 12065: if ($subp eq 'display') {
12066: $value.=' [Part: '.$part.']';
12067: }
1.599 albertel 12068: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12069: $metathesekeys{$unikey}=1;
1.599 albertel 12070: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12071: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12072: }
1.599 albertel 12073: if (defined($metaentry{':'.$unikey.'.default'})) {
12074: $metaentry{':'.$unikey}=
12075: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12076: }
1.339 albertel 12077: }
12078: }
12079: } else {
1.172 www 12080: #
12081: # This is not a package - some other kind of start tag
1.339 albertel 12082: #
12083: my $entry=$token->[1];
1.1068 www 12084: my $unikey='';
1.175 www 12085:
1.339 albertel 12086: if ($entry eq 'import') {
1.175 www 12087: #
12088: # Importing a library here
1.339 albertel 12089: #
1.1067 www 12090: my $location=$parser->get_text('/import');
12091: my $dir=$filename;
12092: $dir=~s|[^/]*$||;
12093: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 12094:
12095: my $importid=$token->[2]->{'id'};
1.1068 www 12096: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 12097: #
12098: # Check metadata for imported file to
12099: # see if it contained response items
12100: #
12101: my %currmetaentry = %metaentry;
12102: my $libresponseorder = &metadata($location,'responseorder');
12103: my $origfile;
12104: if ($libresponseorder ne '') {
12105: if ($#origfiletagids<0) {
12106: undef(%importedrespids);
12107: undef(%importedpartids);
12108: }
12109: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12110: if (@{$importedrespids{$importid}} > 0) {
12111: $importedresponses = 1;
12112: # We need to get the original file and the imported file to get the response order correct
12113: # Load and inspect original file
12114: if ($#origfiletagids<0) {
12115: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12116: $origfile=&getfile($origfilelocation);
12117: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12118: }
12119: }
12120: }
12121: # Do not overwrite contents of %metaentry hash for resource itself with
12122: # hash populated for imported library file
12123: %metaentry = %currmetaentry;
12124: undef(%currmetaentry);
1.1068 www 12125: if ($importmode eq 'problem') {
1.1069 www 12126: # Import as problem/response
1.1068 www 12127: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12128: } elsif ($importmode eq 'part') {
12129: # Import as part(s)
1.1069 www 12130: $importedparts=1;
12131: # We need to get the original file and the imported file to get the part order correct
12132: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12133: # Load and inspect original file if we didn't do that already
12134: if ($#origfiletagids<0) {
12135: undef(%importedrespids);
12136: undef(%importedpartids);
12137: if ($origfile eq '') {
12138: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12139: $origfile=&getfile($origfilelocation);
12140: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12141: }
1.1070 www 12142: }
12143:
1.1069 www 12144: # Load and inspect imported file
12145: my $impfile=&getfile($location);
12146: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12147: if ($#impfilepartids>=0) {
12148: # This problem had parts
1.1070 www 12149: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12150: } else {
12151: # Importing by turning a single problem into a problem part
12152: # It gets the import-tags ID as part-ID
12153: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12154: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12155: }
1.1068 www 12156: } else {
12157: # Normal import
12158: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12159: if (defined($token->[2]->{'id'})) {
12160: $unikey.='_'.$token->[2]->{'id'};
12161: }
1.1067 www 12162: }
12163:
1.339 albertel 12164: if ($depthcount<20) {
1.736 albertel 12165: my $metadata =
12166: &metadata($uri,'keys', $location,$unikey,
12167: $depthcount+1);
12168: foreach my $meta (split(',',$metadata)) {
12169: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12170: $metathesekeys{$meta}=1;
1.339 albertel 12171: }
1.1068 www 12172:
12173: }
1.1067 www 12174: } else {
12175: #
12176: # Not importing, some other kind of non-package, non-library start tag
12177: #
12178: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12179: if (defined($token->[2]->{'id'})) {
12180: $unikey.='_'.$token->[2]->{'id'};
12181: }
1.339 albertel 12182: if (defined($token->[2]->{'name'})) {
12183: $unikey.='_'.$token->[2]->{'name'};
12184: }
12185: $metathesekeys{$unikey}=1;
1.736 albertel 12186: foreach my $param (@{$token->[3]}) {
12187: $metaentry{':'.$unikey.'.'.$param} =
12188: $token->[2]->{$param};
1.339 albertel 12189: }
12190: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12191: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12192: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12193: # only ws inside the tag, and not in default, so use default
12194: # as value
1.599 albertel 12195: $metaentry{':'.$unikey}=$default;
1.908 albertel 12196: } elsif ( $internaltext =~ /\S/ ) {
12197: # something interesting inside the tag
12198: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12199: } else {
1.908 albertel 12200: # no interesting values, don't set a default
1.339 albertel 12201: }
1.172 www 12202: # end of not-a-package not-a-library import
1.339 albertel 12203: }
1.172 www 12204: # end of not-a-package start tag
1.339 albertel 12205: }
1.172 www 12206: # the next is the end of "start tag"
1.339 albertel 12207: }
12208: }
1.483 albertel 12209: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12210: $extension = lc($extension);
12211: if ($extension eq 'htm') { $extension='html'; }
12212:
1.737 albertel 12213: foreach my $key (keys(%packagetab)) {
1.483 albertel 12214: #no specific packages #how's our extension
12215: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12216: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12217: \%metathesekeys);
12218: }
1.883 albertel 12219:
12220: if (!exists($metaentry{':packages'})
12221: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12222: foreach my $key (keys(%packagetab)) {
1.483 albertel 12223: #no specific packages well let's get default then
12224: if ($key!~/^default&/) { next; }
1.488 albertel 12225: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12226: \%metathesekeys);
12227: }
12228: }
1.338 www 12229: # are there custom rights to evaluate
1.599 albertel 12230: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12231:
1.338 www 12232: #
12233: # Importing a rights file here
1.339 albertel 12234: #
12235: unless ($depthcount) {
1.599 albertel 12236: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12237: my $dir=$filename;
12238: $dir=~s|[^/]*$||;
12239: $location=&filelocation($dir,$location);
1.736 albertel 12240: my $rights_metadata =
12241: &metadata($uri,'keys',$location,'_rights',
12242: $depthcount+1);
12243: foreach my $rights (split(',',$rights_metadata)) {
12244: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12245: $metathesekeys{$rights}=1;
1.339 albertel 12246: }
12247: }
12248: }
1.737 albertel 12249: # uniqifiy package listing
12250: my %seen;
12251: my @uniq_packages =
12252: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12253: $metaentry{':packages'} = join(',',@uniq_packages);
12254:
1.1172.2.99 raeburn 12255: if (($importedresponses) || ($importedparts)) {
12256: if ($importedparts) {
1.1070 www 12257: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12258: $metaentry{':partorder'}='';
12259: $metathesekeys{'partorder'}=1;
12260: }
12261: if ($importedresponses) {
12262: # We had imported responses and need to rebuild responseorder
12263: $metaentry{':responseorder'}='';
12264: $metathesekeys{'responseorder'}=1;
12265: }
12266: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12267: my $origid = $origfiletagids[$index+1];
12268: if ($origfiletagids[$index] eq 'part') {
12269: # Original part, part of the problem
12270: if ($importedparts) {
12271: $metaentry{':partorder'}.=','.$origid;
12272: }
12273: } elsif ($origfiletagids[$index] eq 'import') {
12274: if ($importedparts) {
12275: # We have imported parts at this position
12276: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12277: }
12278: if ($importedresponses) {
12279: # We have imported responses at this position
12280: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12281: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12282: }
12283: }
12284: } else {
12285: # Original response item, part of the problem
12286: if ($importedresponses) {
12287: $metaentry{':responseorder'}.=','.$origid;
12288: }
12289: }
12290: }
12291: if ($importedparts) {
12292: $metaentry{':partorder'}=~s/^\,//;
12293: }
12294: if ($importedresponses) {
12295: $metaentry{':responseorder'}=~s/^\,//;
12296: }
1.1070 www 12297: }
12298:
1.737 albertel 12299: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12300: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12301: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12302: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12303: # this is the end of "was not already recently cached
1.71 www 12304: }
1.599 albertel 12305: return $metaentry{':'.$what};
1.261 albertel 12306: }
12307:
1.488 albertel 12308: sub metadata_create_package_def {
1.483 albertel 12309: my ($uri,$key,$package,$metathesekeys)=@_;
12310: my ($pack,$name,$subp)=split(/\&/,$key);
12311: if ($subp eq 'default') { next; }
12312:
1.599 albertel 12313: if (defined($metaentry{':packages'})) {
12314: $metaentry{':packages'}.=','.$package;
1.483 albertel 12315: } else {
1.599 albertel 12316: $metaentry{':packages'}=$package;
1.483 albertel 12317: }
12318: my $value=$packagetab{$key};
12319: my $unikey;
12320: $unikey='parameter_0_'.$name;
1.599 albertel 12321: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12322: $$metathesekeys{$unikey}=1;
1.599 albertel 12323: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12324: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12325: }
1.599 albertel 12326: if (defined($metaentry{':'.$unikey.'.default'})) {
12327: $metaentry{':'.$unikey}=
12328: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12329: }
12330: }
12331:
1.261 albertel 12332: sub metadata_generate_part0 {
12333: my ($metadata,$metacache,$uri) = @_;
12334: my %allnames;
1.737 albertel 12335: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12336: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12337: my $part=$$metacache{':'.$metakey.'.part'};
12338: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12339: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12340: $allnames{$name}=$part;
12341: }
12342: }
12343: }
12344: foreach my $name (keys(%allnames)) {
12345: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12346: my $key=":parameter_0_$name";
1.261 albertel 12347: $$metacache{"$key.part"}='0';
12348: $$metacache{"$key.name"}=$name;
1.428 albertel 12349: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12350: $allnames{$name}.'_'.$name.
12351: '.type'};
1.428 albertel 12352: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12353: '.display'};
1.644 www 12354: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12355: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12356: $$metacache{"$key.display"}=$olddis;
12357: }
1.71 www 12358: }
12359:
1.764 albertel 12360: # ------------------------------------------------------ Devalidate title cache
12361:
12362: sub devalidate_title_cache {
12363: my ($url)=@_;
12364: if (!$env{'request.course.id'}) { return; }
12365: my $symb=&symbread($url);
12366: if (!$symb) { return; }
12367: my $key=$env{'request.course.id'}."\0".$symb;
12368: &devalidate_cache_new('title',$key);
12369: }
12370:
1.1014 droeschl 12371: # ------------------------------------------------- Get the title of a course
12372:
12373: sub current_course_title {
12374: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12375: }
1.301 www 12376: # ------------------------------------------------- Get the title of a resource
12377:
12378: sub gettitle {
12379: my $urlsymb=shift;
12380: my $symb=&symbread($urlsymb);
1.534 albertel 12381: if ($symb) {
1.620 albertel 12382: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12383: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12384: if (defined($cached)) {
12385: return $result;
12386: }
1.534 albertel 12387: my ($map,$resid,$url)=&decode_symb($symb);
12388: my $title='';
1.907 albertel 12389: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12390: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12391: } else {
12392: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12393: &GDBM_READER(),0640)) {
12394: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12395: $title=$bighash{'title_'.$mapid.'.'.$resid};
12396: untie(%bighash);
12397: }
1.534 albertel 12398: }
12399: $title=~s/\&colon\;/\:/gs;
12400: if ($title) {
1.1159 www 12401: # Remember both $symb and $title for dynamic metadata
12402: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12403: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12404: # Cache this title and then return it
1.599 albertel 12405: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12406: }
12407: $urlsymb=$url;
12408: }
12409: my $title=&metadata($urlsymb,'title');
12410: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12411: return $title;
1.301 www 12412: }
1.613 albertel 12413:
1.614 albertel 12414: sub get_slot {
12415: my ($which,$cnum,$cdom)=@_;
12416: if (!$cnum || !$cdom) {
1.790 albertel 12417: (undef,my $courseid)=&whichuser();
1.620 albertel 12418: $cdom=$env{'course.'.$courseid.'.domain'};
12419: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12420: }
1.703 albertel 12421: my $key=join("\0",'slots',$cdom,$cnum,$which);
12422: my %slotinfo;
12423: if (exists($remembered{$key})) {
12424: $slotinfo{$which} = $remembered{$key};
12425: } else {
12426: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12427: &Apache::lonhomework::showhash(%slotinfo);
12428: my ($tmp)=keys(%slotinfo);
12429: if ($tmp=~/^error:/) { return (); }
12430: $remembered{$key} = $slotinfo{$which};
12431: }
1.616 albertel 12432: if (ref($slotinfo{$which}) eq 'HASH') {
12433: return %{$slotinfo{$which}};
12434: }
12435: return $slotinfo{$which};
1.614 albertel 12436: }
1.1150 raeburn 12437:
12438: sub get_reservable_slots {
12439: my ($cnum,$cdom,$uname,$udom) = @_;
12440: my $now = time;
12441: my $reservable_info;
12442: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12443: if (exists($remembered{$key})) {
12444: $reservable_info = $remembered{$key};
12445: } else {
12446: my %resv;
12447: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12448: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12449: $reservable_info = \%resv;
12450: $remembered{$key} = $reservable_info;
12451: }
12452: return $reservable_info;
12453: }
12454:
12455: sub get_course_slots {
12456: my ($cnum,$cdom) = @_;
12457: my $hashid=$cnum.':'.$cdom;
12458: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12459: if (defined($cached)) {
12460: if (ref($result) eq 'HASH') {
12461: return %{$result};
12462: }
12463: } else {
12464: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12465: my ($tmp) = keys(%slots);
12466: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12467: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12468: return %slots;
12469: }
12470: }
12471: return;
12472: }
12473:
12474: sub devalidate_slots_cache {
12475: my ($cnum,$cdom)=@_;
12476: my $hashid=$cnum.':'.$cdom;
12477: &devalidate_cache_new('allslots',$hashid);
12478: }
12479:
1.1172.2.8 raeburn 12480: sub get_coursechange {
12481: my ($cdom,$cnum) = @_;
12482: if ($cdom eq '' || $cnum eq '') {
12483: return unless ($env{'request.course.id'});
12484: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12485: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12486: }
12487: my $hashid=$cdom.'_'.$cnum;
12488: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12489: if ((defined($cached)) && ($change ne '')) {
12490: return $change;
12491: } else {
12492: my %crshash;
12493: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12494: if ($crshash{'internal.contentchange'} eq '') {
12495: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12496: if ($change eq '') {
12497: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12498: $change = $crshash{'internal.created'};
12499: }
12500: } else {
12501: $change = $crshash{'internal.contentchange'};
12502: }
12503: my $cachetime = 600;
12504: &do_cache_new('crschange',$hashid,$change,$cachetime);
12505: }
12506: return $change;
12507: }
12508:
12509: sub devalidate_coursechange_cache {
12510: my ($cnum,$cdom)=@_;
12511: my $hashid=$cnum.':'.$cdom;
12512: &devalidate_cache_new('crschange',$hashid);
12513: }
12514:
1.31 www 12515: # ------------------------------------------------- Update symbolic store links
12516:
12517: sub symblist {
12518: my ($mapname,%newhash)=@_;
1.438 www 12519: $mapname=&deversion(&declutter($mapname));
1.31 www 12520: my %hash;
1.620 albertel 12521: if (($env{'request.course.fn'}) && (%newhash)) {
12522: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12523: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12524: foreach my $url (keys(%newhash)) {
1.711 albertel 12525: next if ($url eq 'last_known'
12526: && $env{'form.no_update_last_known'});
12527: $hash{declutter($url)}=&encode_symb($mapname,
12528: $newhash{$url}->[1],
12529: $newhash{$url}->[0]);
1.191 harris41 12530: }
1.31 www 12531: if (untie(%hash)) {
12532: return 'ok';
12533: }
12534: }
12535: }
12536: return 'error';
1.212 www 12537: }
12538:
12539: # --------------------------------------------------------------- Verify a symb
12540:
12541: sub symbverify {
1.1172.2.11 raeburn 12542: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12543: my $thisfn=$thisurl;
1.439 www 12544: $thisfn=&declutter($thisfn);
1.215 www 12545: # direct jump to resource in page or to a sequence - will construct own symbs
12546: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12547: # check URL part
1.409 www 12548: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12549:
1.431 www 12550: unless ($url eq $thisfn) { return 0; }
1.213 www 12551:
1.216 www 12552: $symb=&symbclean($symb);
1.510 www 12553: $thisurl=&deversion($thisurl);
1.439 www 12554: $thisfn=&deversion($thisfn);
1.213 www 12555:
12556: my %bighash;
12557: my $okay=0;
1.431 www 12558:
1.620 albertel 12559: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12560: &GDBM_READER(),0640)) {
1.1032 raeburn 12561: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12562: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12563: if ($map =~ m{^uploaded/.+\.page$}) {
12564: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12565: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12566: }
12567: }
12568: my $ids;
1.1172.2.122 raeburn 12569: if ($map =~ m{^uploaded/.+\.page$}) {
12570: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12571: } else {
12572: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12573: }
1.1102 raeburn 12574: unless ($ids) {
1.1172.2.13 raeburn 12575: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12576: $ids=$bighash{$idkey};
1.216 www 12577: }
12578: if ($ids) {
12579: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12580: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12581: $symb =~ s/\?.+$//;
12582: }
1.800 albertel 12583: foreach my $id (split(/\,/,$ids)) {
12584: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12585: if (
12586: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12587: eq $symb) {
1.1172.2.11 raeburn 12588: if (ref($encstate)) {
12589: $$encstate = $bighash{'encrypted_'.$id};
12590: }
1.1172.2.13 raeburn 12591: if (($env{'request.role.adv'}) ||
12592: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12593: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12594: $okay=1;
12595: last;
12596: }
12597: }
12598: }
1.216 www 12599: }
1.213 www 12600: untie(%bighash);
12601: }
12602: return $okay;
1.31 www 12603: }
12604:
1.210 www 12605: # --------------------------------------------------------------- Clean-up symb
12606:
12607: sub symbclean {
12608: my $symb=shift;
1.568 albertel 12609: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12610: # remove version from map
12611: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12612:
1.210 www 12613: # remove version from URL
12614: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12615:
1.507 www 12616: # remove wrapper
12617:
1.510 www 12618: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12619: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12620: return $symb;
1.409 www 12621: }
12622:
12623: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12624:
12625: sub encode_symb {
12626: my ($map,$resid,$url)=@_;
12627: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12628: }
1.409 www 12629:
12630: sub decode_symb {
1.568 albertel 12631: my $symb=shift;
12632: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12633: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12634: return (&fixversion($map),$resid,&fixversion($url));
12635: }
12636:
12637: sub fixversion {
12638: my $fn=shift;
1.609 banghart 12639: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12640: my %bighash;
12641: my $uri=&clutter($fn);
1.620 albertel 12642: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12643: # is this cached?
1.599 albertel 12644: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12645: if (defined($cached)) { return $result; }
12646: # unfortunately not cached, or expired
1.620 albertel 12647: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12648: &GDBM_READER(),0640)) {
12649: if ($bighash{'version_'.$uri}) {
12650: my $version=$bighash{'version_'.$uri};
1.444 www 12651: unless (($version eq 'mostrecent') ||
12652: ($version==&getversion($uri))) {
1.440 www 12653: $uri=~s/\.(\w+)$/\.$version\.$1/;
12654: }
12655: }
12656: untie %bighash;
1.413 www 12657: }
1.599 albertel 12658: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12659: }
12660:
12661: sub deversion {
12662: my $url=shift;
12663: $url=~s/\.\d+\.(\w+)$/\.$1/;
12664: return $url;
1.210 www 12665: }
12666:
1.31 www 12667: # ------------------------------------------------------ Return symb list entry
12668:
12669: sub symbread {
1.1172.2.126 raeburn 12670: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12671: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12672: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12673: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12674: unless (ref($possibles) eq 'HASH') {
12675: if ($ignorecachednull) {
12676: return $env{$cache_str} unless ($env{$cache_str} eq '');
12677: } else {
12678: return $env{$cache_str};
12679: }
1.1172.2.66 raeburn 12680: }
12681: }
1.242 www 12682: # no filename provided? try from environment
1.1172.2.54 raeburn 12683: unless ($thisfn) {
1.620 albertel 12684: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12685: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12686: }
12687: $thisfn=$env{'request.filename'};
1.44 www 12688: }
1.569 albertel 12689: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12690: # is that filename actually a symb? Verify, clean, and return
12691: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12692: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12693: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12694: }
1.242 www 12695: }
1.44 www 12696: $thisfn=declutter($thisfn);
1.31 www 12697: my %hash;
1.37 www 12698: my %bighash;
12699: my $syval='';
1.620 albertel 12700: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12701: my $targetfn = $thisfn;
1.609 banghart 12702: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12703: $targetfn = 'adm/wrapper/'.$thisfn;
12704: }
1.687 albertel 12705: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12706: $targetfn=$1;
12707: }
1.1172.2.128 raeburn 12708: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12709: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12710: &GDBM_READER(),0640)) {
12711: $syval=$hash{$targetfn};
12712: untie(%hash);
12713: }
1.1172.2.128 raeburn 12714: if ($syval && $checkforblock) {
12715: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12716: if (@blockers) {
12717: $syval='';
12718: }
12719: }
1.37 www 12720: }
12721: # ---------------------------------------------------------- There was an entry
12722: if ($syval) {
1.601 albertel 12723: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12724: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12725: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12726: #return $env{$cache_str}='';
1.601 albertel 12727: #}
12728: #$syval.=$1;
12729: #}
1.37 www 12730: } else {
12731: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12732: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12733: &GDBM_READER(),0640)) {
1.37 www 12734: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12735: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12736: unless ($ids) {
12737: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12738: }
12739: unless ($ids) {
12740: # alias?
12741: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12742: }
1.37 www 12743: if ($ids) {
12744: # ------------------------------------------------------------------- Has ID(s)
12745: my @possibilities=split(/\,/,$ids);
1.39 www 12746: if ($#possibilities==0) {
12747: # ----------------------------------------------- There is only one possibility
1.37 www 12748: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12749: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12750: $resid,$thisfn);
1.1172.2.66 raeburn 12751: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12752: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12753: $possibles->{$syval} = 1;
12754: }
1.1172.2.66 raeburn 12755: }
12756: if ($checkforblock) {
1.1172.2.126 raeburn 12757: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12758: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12759: if (@blockers) {
12760: $syval = '';
12761: untie(%bighash);
12762: return $env{$cache_str}='';
12763: }
1.1172.2.66 raeburn 12764: }
12765: }
12766: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12767: # ------------------------------------------ There is more than one possibility
12768: my $realpossible=0;
1.800 albertel 12769: foreach my $id (@possibilities) {
12770: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12771: my $canaccess;
12772: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12773: $canaccess = 1;
12774: } else {
12775: $canaccess = &allowed('bre',$file);
12776: }
12777: if ($canaccess) {
12778: my ($mapid,$resid)=split(/\./,$id);
12779: if ($bighash{'map_type_'.$mapid} ne 'page') {
12780: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12781: $resid,$thisfn);
1.1172.2.126 raeburn 12782: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12783: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12784: if ($checkforblock) {
1.1172.2.127 raeburn 12785: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12786: if (@blockers > 0) {
12787: $syval = '';
12788: } else {
1.1172.2.66 raeburn 12789: $syval = $poss_syval;
12790: $realpossible++;
12791: }
12792: } else {
12793: $syval = $poss_syval;
12794: $realpossible++;
12795: }
1.1172.2.126 raeburn 12796: if ($syval) {
12797: if (ref($possibles) eq 'HASH') {
12798: $possibles->{$syval} = 1;
12799: }
12800: }
1.1172.2.66 raeburn 12801: }
1.39 www 12802: }
1.191 harris41 12803: }
1.39 www 12804: if ($realpossible!=1) { $syval=''; }
1.249 www 12805: } else {
12806: $syval='';
1.37 www 12807: }
12808: }
1.1172.2.66 raeburn 12809: untie(%bighash);
1.481 raeburn 12810: }
1.31 www 12811: }
1.62 www 12812: if ($syval) {
1.1172.2.128 raeburn 12813: return $env{$cache_str}=$syval;
1.62 www 12814: }
1.31 www 12815: }
1.949 raeburn 12816: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12817: return $env{$cache_str}='';
1.31 www 12818: }
12819:
12820: # ---------------------------------------------------------- Return random seed
12821:
1.32 www 12822: sub numval {
12823: my $txt=shift;
12824: $txt=~tr/A-J/0-9/;
12825: $txt=~tr/a-j/0-9/;
12826: $txt=~tr/K-T/0-9/;
12827: $txt=~tr/k-t/0-9/;
12828: $txt=~tr/U-Z/0-5/;
12829: $txt=~tr/u-z/0-5/;
12830: $txt=~s/\D//g;
1.564 albertel 12831: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12832: return int($txt);
1.368 albertel 12833: }
12834:
1.484 albertel 12835: sub numval2 {
12836: my $txt=shift;
12837: $txt=~tr/A-J/0-9/;
12838: $txt=~tr/a-j/0-9/;
12839: $txt=~tr/K-T/0-9/;
12840: $txt=~tr/k-t/0-9/;
12841: $txt=~tr/U-Z/0-5/;
12842: $txt=~tr/u-z/0-5/;
12843: $txt=~s/\D//g;
12844: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12845: my $total;
12846: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12847: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12848: return int($total);
12849: }
12850:
1.575 albertel 12851: sub numval3 {
12852: use integer;
12853: my $txt=shift;
12854: $txt=~tr/A-J/0-9/;
12855: $txt=~tr/a-j/0-9/;
12856: $txt=~tr/K-T/0-9/;
12857: $txt=~tr/k-t/0-9/;
12858: $txt=~tr/U-Z/0-5/;
12859: $txt=~tr/u-z/0-5/;
12860: $txt=~s/\D//g;
12861: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12862: my $total;
12863: foreach my $val (@txts) { $total+=$val; }
12864: if ($_64bit) { $total=(($total<<32)>>32); }
12865: return $total;
12866: }
12867:
1.675 albertel 12868: sub digest {
12869: my ($data)=@_;
12870: my $digest=&Digest::MD5::md5($data);
12871: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12872: my ($e,$f);
12873: {
12874: use integer;
12875: $e=($a+$b);
12876: $f=($c+$d);
12877: if ($_64bit) {
12878: $e=(($e<<32)>>32);
12879: $f=(($f<<32)>>32);
12880: }
12881: }
12882: if (wantarray) {
12883: return ($e,$f);
12884: } else {
12885: my $g;
12886: {
12887: use integer;
12888: $g=($e+$f);
12889: if ($_64bit) {
12890: $g=(($g<<32)>>32);
12891: }
12892: }
12893: return $g;
12894: }
12895: }
12896:
1.368 albertel 12897: sub latest_rnd_algorithm_id {
1.675 albertel 12898: return '64bit5';
1.366 albertel 12899: }
1.32 www 12900:
1.503 albertel 12901: sub get_rand_alg {
12902: my ($courseid)=@_;
1.790 albertel 12903: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12904: if ($courseid) {
1.620 albertel 12905: return $env{"course.$courseid.rndseed"};
1.503 albertel 12906: }
12907: return &latest_rnd_algorithm_id();
12908: }
12909:
1.562 albertel 12910: sub validCODE {
12911: my ($CODE)=@_;
12912: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12913: return 0;
12914: }
12915:
1.491 albertel 12916: sub getCODE {
1.620 albertel 12917: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12918: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12919: defined($Apache::lonhomework::parsing_a_task) ) &&
12920: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12921: return $Apache::lonhomework::history{'resource.CODE'};
12922: }
12923: return undef;
12924: }
1.1133 foxr 12925: #
12926: # Determines the random seed for a specific context:
12927: #
12928: # parameters:
12929: # symb - in course context the symb for the seed.
12930: # course_id - The course id of the form domain_coursenum.
12931: # domain - Domain for the user.
12932: # course - Course for the user.
12933: # cenv - environment of the course.
12934: #
12935: # NOTE:
12936: # All parameters are picked out of the environment if missing
12937: # or not defined.
12938: # If a symb cannot be determined the current time is used instead.
12939: #
12940: # For a given well defined symb, courside, domain, username,
12941: # and course environment, the seed is reproducible.
12942: #
1.31 www 12943: sub rndseed {
1.1133 foxr 12944: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12945: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12946: if (!defined($symb)) {
1.366 albertel 12947: unless ($symb=$wsymb) { return time; }
12948: }
1.1146 foxr 12949: if (!defined $courseid) {
12950: $courseid=$wcourseid;
12951: }
12952: if (!defined $domain) { $domain=$wdomain; }
12953: if (!defined $username) { $username=$wusername }
1.1133 foxr 12954:
12955: my $which;
12956: if (defined($cenv->{'rndseed'})) {
12957: $which = $cenv->{'rndseed'};
12958: } else {
12959: $which =&get_rand_alg($courseid);
12960: }
1.491 albertel 12961: if (defined(&getCODE())) {
1.675 albertel 12962: if ($which eq '64bit5') {
12963: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12964: } elsif ($which eq '64bit4') {
1.575 albertel 12965: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12966: } else {
12967: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12968: }
1.675 albertel 12969: } elsif ($which eq '64bit5') {
12970: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12971: } elsif ($which eq '64bit4') {
12972: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12973: } elsif ($which eq '64bit3') {
12974: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12975: } elsif ($which eq '64bit2') {
12976: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12977: } elsif ($which eq '64bit') {
12978: return &rndseed_64bit($symb,$courseid,$domain,$username);
12979: }
12980: return &rndseed_32bit($symb,$courseid,$domain,$username);
12981: }
12982:
12983: sub rndseed_32bit {
12984: my ($symb,$courseid,$domain,$username)=@_;
12985: {
12986: use integer;
12987: my $symbchck=unpack("%32C*",$symb) << 27;
12988: my $symbseed=numval($symb) << 22;
12989: my $namechck=unpack("%32C*",$username) << 17;
12990: my $nameseed=numval($username) << 12;
12991: my $domainseed=unpack("%32C*",$domain) << 7;
12992: my $courseseed=unpack("%32C*",$courseid);
12993: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12994: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12995: #&logthis("rndseed :$num:$symb");
1.564 albertel 12996: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12997: return $num;
12998: }
12999: }
13000:
13001: sub rndseed_64bit {
13002: my ($symb,$courseid,$domain,$username)=@_;
13003: {
13004: use integer;
13005: my $symbchck=unpack("%32S*",$symb) << 21;
13006: my $symbseed=numval($symb) << 10;
13007: my $namechck=unpack("%32S*",$username);
13008:
13009: my $nameseed=numval($username) << 21;
13010: my $domainseed=unpack("%32S*",$domain) << 10;
13011: my $courseseed=unpack("%32S*",$courseid);
13012:
13013: my $num1=$symbchck+$symbseed+$namechck;
13014: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13015: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13016: #&logthis("rndseed :$num:$symb");
1.564 albertel 13017: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13018: return "$num1,$num2";
1.155 albertel 13019: }
1.366 albertel 13020: }
13021:
1.443 albertel 13022: sub rndseed_64bit2 {
13023: my ($symb,$courseid,$domain,$username)=@_;
13024: {
13025: use integer;
13026: # strings need to be an even # of cahracters long, it it is odd the
13027: # last characters gets thrown away
13028: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13029: my $symbseed=numval($symb) << 10;
13030: my $namechck=unpack("%32S*",$username.' ');
13031:
13032: my $nameseed=numval($username) << 21;
1.501 albertel 13033: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13034: my $courseseed=unpack("%32S*",$courseid.' ');
13035:
13036: my $num1=$symbchck+$symbseed+$namechck;
13037: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13038: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13039: #&logthis("rndseed :$num:$symb");
1.803 albertel 13040: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13041: return "$num1,$num2";
13042: }
13043: }
13044:
13045: sub rndseed_64bit3 {
13046: my ($symb,$courseid,$domain,$username)=@_;
13047: {
13048: use integer;
13049: # strings need to be an even # of cahracters long, it it is odd the
13050: # last characters gets thrown away
13051: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13052: my $symbseed=numval2($symb) << 10;
13053: my $namechck=unpack("%32S*",$username.' ');
13054:
13055: my $nameseed=numval2($username) << 21;
1.443 albertel 13056: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13057: my $courseseed=unpack("%32S*",$courseid.' ');
13058:
13059: my $num1=$symbchck+$symbseed+$namechck;
13060: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13061: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13062: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13063: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13064:
1.503 albertel 13065: return "$num1:$num2";
1.443 albertel 13066: }
13067: }
13068:
1.575 albertel 13069: sub rndseed_64bit4 {
13070: my ($symb,$courseid,$domain,$username)=@_;
13071: {
13072: use integer;
13073: # strings need to be an even # of cahracters long, it it is odd the
13074: # last characters gets thrown away
13075: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13076: my $symbseed=numval3($symb) << 10;
13077: my $namechck=unpack("%32S*",$username.' ');
13078:
13079: my $nameseed=numval3($username) << 21;
13080: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13081: my $courseseed=unpack("%32S*",$courseid.' ');
13082:
13083: my $num1=$symbchck+$symbseed+$namechck;
13084: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13085: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13086: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13087: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13088:
1.575 albertel 13089: return "$num1:$num2";
13090: }
13091: }
13092:
1.675 albertel 13093: sub rndseed_64bit5 {
13094: my ($symb,$courseid,$domain,$username)=@_;
13095: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13096: return "$num1:$num2";
13097: }
13098:
1.366 albertel 13099: sub rndseed_CODE_64bit {
13100: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13101: {
1.366 albertel 13102: use integer;
1.443 albertel 13103: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13104: my $symbseed=numval2($symb);
1.491 albertel 13105: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13106: my $CODEseed=numval(&getCODE());
1.443 albertel 13107: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13108: my $num1=$symbseed+$CODEchck;
13109: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13110: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13111: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13112: if ($_64bit) { $num1=(($num1<<32)>>32); }
13113: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13114: return "$num1:$num2";
1.366 albertel 13115: }
13116: }
13117:
1.575 albertel 13118: sub rndseed_CODE_64bit4 {
13119: my ($symb,$courseid,$domain,$username)=@_;
13120: {
13121: use integer;
13122: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13123: my $symbseed=numval3($symb);
13124: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13125: my $CODEseed=numval3(&getCODE());
13126: my $courseseed=unpack("%32S*",$courseid.' ');
13127: my $num1=$symbseed+$CODEchck;
13128: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13129: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13130: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13131: if ($_64bit) { $num1=(($num1<<32)>>32); }
13132: if ($_64bit) { $num2=(($num2<<32)>>32); }
13133: return "$num1:$num2";
13134: }
13135: }
13136:
1.675 albertel 13137: sub rndseed_CODE_64bit5 {
13138: my ($symb,$courseid,$domain,$username)=@_;
13139: my $code = &getCODE();
13140: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13141: return "$num1:$num2";
13142: }
13143:
1.366 albertel 13144: sub setup_random_from_rndseed {
13145: my ($rndseed)=@_;
1.503 albertel 13146: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13147: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13148: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13149: &Math::Random::random_set_seed_from_phrase($rndseed);
13150: } else {
13151: &Math::Random::random_set_seed($num1,$num2);
13152: }
1.366 albertel 13153: } else {
13154: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13155: }
1.36 albertel 13156: }
13157:
1.474 albertel 13158: sub latest_receipt_algorithm_id {
1.835 albertel 13159: return 'receipt3';
1.474 albertel 13160: }
13161:
1.480 www 13162: sub recunique {
13163: my $fucourseid=shift;
13164: my $unique;
1.835 albertel 13165: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13166: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13167: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13168: } else {
13169: $unique=$perlvar{'lonReceipt'};
13170: }
13171: return unpack("%32C*",$unique);
13172: }
13173:
13174: sub recprefix {
13175: my $fucourseid=shift;
13176: my $prefix;
1.835 albertel 13177: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13178: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13179: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13180: } else {
13181: $prefix=$perlvar{'lonHostID'};
13182: }
13183: return unpack("%32C*",$prefix);
13184: }
13185:
1.76 www 13186: sub ireceipt {
1.474 albertel 13187: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13188:
13189: my $return =&recprefix($fucourseid).'-';
13190:
13191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13192: $env{'request.state'} eq 'construct') {
13193: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13194: return $return;
13195: }
13196:
1.76 www 13197: my $cuname=unpack("%32C*",$funame);
13198: my $cudom=unpack("%32C*",$fudom);
13199: my $cucourseid=unpack("%32C*",$fucourseid);
13200: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13201: my $cunique=&recunique($fucourseid);
1.474 albertel 13202: my $cpart=unpack("%32S*",$part);
1.835 albertel 13203: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13204:
1.790 albertel 13205: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13206:
13207: $return.= ($cunique%$cuname+
13208: $cunique%$cudom+
13209: $cusymb%$cuname+
13210: $cusymb%$cudom+
13211: $cucourseid%$cuname+
13212: $cucourseid%$cudom+
13213: $cpart%$cuname+
13214: $cpart%$cudom);
13215: } else {
13216: $return.= ($cunique%$cuname+
13217: $cunique%$cudom+
13218: $cusymb%$cuname+
13219: $cusymb%$cudom+
13220: $cucourseid%$cuname+
13221: $cucourseid%$cudom);
13222: }
13223: return $return;
1.76 www 13224: }
13225:
13226: sub receipt {
1.474 albertel 13227: my ($part)=@_;
1.790 albertel 13228: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13229: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13230: }
1.260 ng 13231:
1.790 albertel 13232: sub whichuser {
13233: my ($passedsymb)=@_;
13234: my ($symb,$courseid,$domain,$name,$publicuser);
13235: if (defined($env{'form.grade_symb'})) {
13236: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13237: my $allowed=&allowed('vgr',$tmp_courseid);
13238: if (!$allowed &&
13239: exists($env{'request.course.sec'}) &&
13240: $env{'request.course.sec'} !~ /^\s*$/) {
13241: $allowed=&allowed('vgr',$tmp_courseid.
13242: '/'.$env{'request.course.sec'});
13243: }
13244: if ($allowed) {
13245: ($symb)=&get_env_multiple('form.grade_symb');
13246: $courseid=$tmp_courseid;
13247: ($domain)=&get_env_multiple('form.grade_domain');
13248: ($name)=&get_env_multiple('form.grade_username');
13249: return ($symb,$courseid,$domain,$name,$publicuser);
13250: }
13251: }
13252: if (!$passedsymb) {
13253: $symb=&symbread();
13254: } else {
13255: $symb=$passedsymb;
13256: }
13257: $courseid=$env{'request.course.id'};
13258: $domain=$env{'user.domain'};
13259: $name=$env{'user.name'};
13260: if ($name eq 'public' && $domain eq 'public') {
13261: if (!defined($env{'form.username'})) {
13262: $env{'form.username'}.=time.rand(10000000);
13263: }
13264: $name.=$env{'form.username'};
13265: }
13266: return ($symb,$courseid,$domain,$name,$publicuser);
13267:
13268: }
13269:
1.36 albertel 13270: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13271: # returns either the contents of the file or
13272: # -1 if the file doesn't exist
1.481 raeburn 13273: #
13274: # if the target is a file that was uploaded via DOCS,
13275: # a check will be made to see if a current copy exists on the local server,
13276: # if it does this will be served, otherwise a copy will be retrieved from
13277: # the home server for the course and stored in /home/httpd/html/userfiles on
13278: # the local server.
1.472 albertel 13279:
1.36 albertel 13280: sub getfile {
1.538 albertel 13281: my ($file) = @_;
1.609 banghart 13282: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13283: &repcopy($file);
13284: return &readfile($file);
13285: }
13286:
13287: sub repcopy_userfile {
13288: my ($file)=@_;
1.1142 raeburn 13289: my $londocroot = $perlvar{'lonDocRoot'};
13290: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13291: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13292: my ($cdom,$cnum,$filename) =
1.811 albertel 13293: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13294: my $uri="/uploaded/$cdom/$cnum/$filename";
13295: if (-e "$file") {
1.828 www 13296: # we already have a local copy, check it out
1.538 albertel 13297: my @fileinfo = stat($file);
1.828 www 13298: my $rtncode;
13299: my $info;
1.538 albertel 13300: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13301: if ($lwpresp ne 'ok') {
1.828 www 13302: # there is no such file anymore, even though we had a local copy
1.482 albertel 13303: if ($rtncode eq '404') {
1.538 albertel 13304: unlink($file);
1.482 albertel 13305: }
13306: return -1;
13307: }
13308: if ($info < $fileinfo[9]) {
1.828 www 13309: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13310: return 'ok';
1.828 www 13311: } else {
13312: # the file is outdated, get rid of it
13313: unlink($file);
1.482 albertel 13314: }
1.828 www 13315: }
13316: # one way or the other, at this point, we don't have the file
13317: # construct the correct path for the file
13318: my @parts = ($cdom,$cnum);
13319: if ($filename =~ m|^(.+)/[^/]+$|) {
13320: push @parts, split(/\//,$1);
13321: }
13322: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13323: foreach my $part (@parts) {
13324: $path .= '/'.$part;
13325: if (!-e $path) {
13326: mkdir($path,0770);
1.482 albertel 13327: }
13328: }
1.828 www 13329: # now the path exists for sure
13330: # get a user agent
13331: my $ua=new LWP::UserAgent;
13332: my $transferfile=$file.'.in.transfer';
13333: # FIXME: this should flock
13334: if (-e $transferfile) { return 'ok'; }
13335: my $request;
13336: $uri=~s/^\///;
1.980 raeburn 13337: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13338: my $hostname = &hostname($homeserver);
1.980 raeburn 13339: my $protocol = $protocol{$homeserver};
13340: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13341: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13342: my $response=$ua->request($request,$transferfile);
13343: # did it work?
13344: if ($response->is_error()) {
13345: unlink($transferfile);
13346: &logthis("Userfile repcopy failed for $uri");
13347: return -1;
13348: }
13349: # worked, rename the transfer file
13350: rename($transferfile,$file);
1.607 raeburn 13351: return 'ok';
1.481 raeburn 13352: }
13353:
1.517 albertel 13354: sub tokenwrapper {
13355: my $uri=shift;
1.980 raeburn 13356: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13357: $uri=~s|^/||;
1.620 albertel 13358: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13359: my $token=$1;
1.552 albertel 13360: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13361: if ($udom && $uname && $file) {
13362: $file=~s|(\?\.*)*$||;
1.949 raeburn 13363: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13364: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13365: my $hostname = &hostname($homeserver);
1.980 raeburn 13366: my $protocol = $protocol{$homeserver};
13367: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13368: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13369: (($uri=~/\?/)?'&':'?').'token='.$token.
13370: '&tokenissued='.$perlvar{'lonHostID'};
13371: } else {
13372: return '/adm/notfound.html';
13373: }
13374: }
13375:
1.828 www 13376: # call with reqtype HEAD: get last modification time
13377: # call with reqtype GET: get the file contents
13378: # Do not call this with reqtype GET for large files! It loads everything into memory
13379: #
1.481 raeburn 13380: sub getuploaded {
13381: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13382: $uri=~s/^\///;
1.980 raeburn 13383: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13384: my $hostname = &hostname($homeserver);
1.980 raeburn 13385: my $protocol = $protocol{$homeserver};
13386: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13387: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13388: my $ua=new LWP::UserAgent;
13389: my $request=new HTTP::Request($reqtype,$uri);
13390: my $response=$ua->request($request);
13391: $$rtncode = $response->code;
1.482 albertel 13392: if (! $response->is_success()) {
13393: return 'failed';
13394: }
13395: if ($reqtype eq 'HEAD') {
1.486 www 13396: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13397: } elsif ($reqtype eq 'GET') {
13398: $$info = $response->content;
1.472 albertel 13399: }
1.482 albertel 13400: return 'ok';
1.36 albertel 13401: }
13402:
1.481 raeburn 13403: sub readfile {
13404: my $file = shift;
13405: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13406: my $fh;
1.1172.2.96 raeburn 13407: open($fh,"<",$file);
1.481 raeburn 13408: my $a='';
1.800 albertel 13409: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13410: return $a;
13411: }
13412:
1.36 albertel 13413: sub filelocation {
1.590 banghart 13414: my ($dir,$file) = @_;
13415: my $location;
13416: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13417:
13418: if ($file =~ m-^/adm/-) {
13419: $file=~s-^/adm/wrapper/-/-;
13420: $file=~s-^/adm/coursedocs/showdoc/-/-;
13421: }
1.882 albertel 13422:
1.1139 www 13423: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13424: $location = $file;
1.609 banghart 13425: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13426: my ($udom,$uname,$filename)=
1.811 albertel 13427: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13428: my $home=&homeserver($uname,$udom);
13429: my $is_me=0;
13430: my @ids=¤t_machine_ids();
13431: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13432: if ($is_me) {
1.1117 foxr 13433: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13434: } else {
13435: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13436: $udom.'/'.$uname.'/'.$filename;
13437: }
1.882 albertel 13438: } elsif ($file =~ m-^/adm/-) {
13439: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13440: } else {
13441: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13442: $file=~s:^/(res|priv)/:/:;
13443: my $space=$1;
1.590 banghart 13444: if ( !( $file =~ m:^/:) ) {
13445: $location = $dir. '/'.$file;
13446: } else {
1.1142 raeburn 13447: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13448: }
1.59 albertel 13449: }
1.590 banghart 13450: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13451: while ($location=~m{/\.\./}) {
13452: if ($location =~ m{/[^/]+/\.\./}) {
13453: $location=~ s{/[^/]+/\.\./}{/}g;
13454: } else {
13455: $location=~ s{/\.\./}{/}g;
13456: }
13457: } #remove dir/..
1.590 banghart 13458: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13459: return $location;
1.46 www 13460: }
1.36 albertel 13461:
1.46 www 13462: sub hreflocation {
13463: my ($dir,$file)=@_;
1.980 raeburn 13464: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13465: $file=filelocation($dir,$file);
1.700 albertel 13466: } elsif ($file=~m-^/adm/-) {
13467: $file=~s-^/adm/wrapper/-/-;
13468: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13469: }
13470: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13471: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13472: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13473: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13474: {/uploaded/$1/$2/}x;
1.46 www 13475: }
1.913 albertel 13476: if ($file=~ m{^/userfiles/}) {
13477: $file =~ s{^/userfiles/}{/uploaded/};
13478: }
1.462 albertel 13479: return $file;
1.465 albertel 13480: }
13481:
1.1139 www 13482:
13483:
13484:
13485:
1.465 albertel 13486: sub current_machine_domains {
1.853 albertel 13487: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13488: }
13489:
13490: sub machine_domains {
13491: my ($hostname) = @_;
1.465 albertel 13492: my @domains;
1.838 albertel 13493: my %hostname = &all_hostnames();
1.465 albertel 13494: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13495: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13496: if ($hostname eq $name) {
1.844 albertel 13497: push(@domains,&host_domain($id));
1.465 albertel 13498: }
13499: }
13500: return @domains;
13501: }
13502:
13503: sub current_machine_ids {
1.853 albertel 13504: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13505: }
13506:
13507: sub machine_ids {
13508: my ($hostname) = @_;
13509: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13510: my @ids;
1.888 albertel 13511: my %name_to_host = &all_names();
1.889 albertel 13512: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13513: return @{ $name_to_host{$hostname} };
13514: }
13515: return;
1.31 www 13516: }
13517:
1.824 raeburn 13518: sub additional_machine_domains {
13519: my @domains;
1.1172.2.142 raeburn 13520: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
13521: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
13522: while( my $line = <$fh>) {
13523: chomp($line);
13524: $line =~ s/\s//g;
13525: push(@domains,$line);
13526: }
13527: close($fh);
13528: }
1.824 raeburn 13529: }
13530: return @domains;
13531: }
13532:
13533: sub default_login_domain {
13534: my $domain = $perlvar{'lonDefDomain'};
13535: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13536: foreach my $posdom (¤t_machine_domains(),
13537: &additional_machine_domains()) {
13538: if (lc($posdom) eq lc($testdomain)) {
13539: $domain=$posdom;
13540: last;
13541: }
13542: }
13543: return $domain;
13544: }
13545:
1.1172.2.106 raeburn 13546: sub shared_institution {
1.1172.2.136 raeburn 13547: my ($dom,$lonhost) = @_;
13548: if ($lonhost eq '') {
13549: $lonhost = $perlvar{'lonHostID'};
13550: }
1.1172.2.106 raeburn 13551: my $same_intdom;
1.1172.2.136 raeburn 13552: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13553: if ($hostintdom ne '') {
13554: my %iphost = &get_iphost();
13555: my $primary_id = &domain($dom,'primary');
13556: my $primary_ip = &get_host_ip($primary_id);
13557: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13558: foreach my $id (@{$iphost{$primary_ip}}) {
13559: my $intdom = &internet_dom($id);
13560: if ($intdom eq $hostintdom) {
13561: $same_intdom = 1;
13562: last;
13563: }
13564: }
13565: }
13566: }
13567: return $same_intdom;
13568: }
13569:
1.1172.2.120 raeburn 13570: sub uses_sts {
13571: my ($ignore_cache) = @_;
13572: my $lonhost = $perlvar{'lonHostID'};
13573: my $hostname = &hostname($lonhost);
13574: my $sts_on;
13575: if ($protocol{$lonhost} eq 'https') {
13576: my $cachetime = 12*3600;
13577: if (!$ignore_cache) {
13578: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13579: if (defined($cached)) {
13580: return $sts_on;
13581: }
13582: }
1.1172.2.121 raeburn 13583: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13584: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13585: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13586: my $response=$ua->request($request);
1.1172.2.120 raeburn 13587: if ($response->is_success) {
13588: my $has_sts = $response->header('Strict-Transport-Security');
13589: if ($has_sts eq '') {
13590: $sts_on = 0;
13591: } else {
13592: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13593: my $maxage = $1;
13594: if ($maxage) {
13595: $sts_on = 1;
13596: } else {
13597: $sts_on = 0;
13598: }
13599: } else {
13600: $sts_on = 0;
13601: }
13602: }
13603: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13604: }
13605: }
13606: return;
13607: }
13608:
1.1172.2.142 raeburn 13609: sub waf_allssl {
13610: my ($host_name) = @_;
13611: my $alias = &get_proxy_alias();
13612: if ($host_name eq '') {
13613: $host_name = $ENV{'SERVER_NAME'};
13614: }
13615: if (($host_name ne '') && ($alias eq $host_name)) {
13616: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
13617: my %defdomdefaults = &get_domain_defaults($serverhomedom);
13618: if ($defdomdefaults{'waf_sslopt'}) {
13619: return $defdomdefaults{'waf_sslopt'};
13620: }
13621: }
13622: return;
13623: }
13624:
1.1172.2.134 raeburn 13625: sub get_requestor_ip {
13626: my ($r,$nolookup,$noproxy) = @_;
13627: my $from_ip;
13628: if (ref($r)) {
1.1172.2.142 raeburn 13629: if ($r->can('useragent_ip')) {
13630: if ($noproxy && $r->can('client_ip')) {
13631: $from_ip = $r->client_ip();
13632: } else {
13633: $from_ip = $r->useragent_ip();
13634: }
13635: } elsif ($r->connection->can('remote_ip')) {
13636: $from_ip = $r->connection->remote_ip();
13637: } else {
13638: $from_ip = $r->get_remote_host($nolookup);
13639: }
1.1172.2.134 raeburn 13640: } else {
13641: $from_ip = $ENV{'REMOTE_ADDR'};
13642: }
1.1172.2.142 raeburn 13643: return $from_ip if ($noproxy);
13644: # Who controls proxy settings for server
13645: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
13646: my $proxyinfo = &get_proxy_settings($dom_in_use);
13647: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
13648: if ($proxyinfo->{'vpnint'}) {
13649: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
13650: return $from_ip;
13651: }
13652: }
13653: if ($proxyinfo->{'trusted'}) {
13654: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
13655: my $ipheader = $proxyinfo->{'ipheader'};
13656: my ($ip,$xfor);
13657: if (ref($r)) {
13658: if ($ipheader) {
13659: $ip = $r->headers_in->{$ipheader};
13660: }
13661: $xfor = $r->headers_in->{'X-Forwarded-For'};
13662: } else {
13663: if ($ipheader) {
13664: $ip = $ENV{'HTTP_'.uc($ipheader)};
13665: }
13666: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
13667: }
13668: if (($ip eq '') && ($xfor ne '')) {
13669: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
13670: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
13671: $ip = $poss_ip;
13672: last;
13673: }
13674: }
13675: }
13676: if ($ip ne '') {
13677: return $ip;
13678: }
13679: }
13680: }
13681: }
1.1172.2.134 raeburn 13682: return $from_ip;
13683: }
13684:
1.1172.2.142 raeburn 13685: sub get_proxy_settings {
13686: my ($dom_in_use) = @_;
13687: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
13688: my $proxyinfo = {
13689: ipheader => $domdefaults{'waf_ipheader'},
13690: trusted => $domdefaults{'waf_trusted'},
13691: vpnint => $domdefaults{'waf_vpnint'},
13692: vpnext => $domdefaults{'waf_vpnext'},
13693: sslopt => $domdefaults{'waf_sslopt'},
13694: };
13695: return $proxyinfo;
13696: }
13697:
13698: sub ip_match {
13699: my ($ip,$pattern_str) = @_;
13700: $ip=Net::CIDR::cidrvalidate($ip);
13701: if ($ip) {
13702: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
13703: }
13704: return;
13705: }
13706:
13707: sub get_proxy_alias {
13708: my ($lonid) = @_;
13709: if ($lonid eq '') {
13710: $lonid = $perlvar{'lonHostID'};
13711: }
13712: if (!defined(&hostname($lonid))) {
13713: return;
13714: }
13715: if ($lonid ne '') {
13716: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
13717: if ($cached) {
13718: return $alias;
13719: }
13720: my $dom = &Apache::lonnet::host_domain($lonid);
13721: if ($dom ne '') {
13722: my $cachetime = 60*60*24;
13723: my %domconfig =
13724: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13725: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13726: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
13727: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
13728: }
13729: }
13730: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
13731: }
13732: }
13733: return;
13734: }
13735:
13736: sub use_proxy_alias {
13737: my ($r,$lonid) = @_;
13738: my $alias = &get_proxy_alias($lonid);
13739: if ($alias) {
13740: my $dom = &host_domain($lonid);
13741: if ($dom ne '') {
13742: my $proxyinfo = &get_proxy_settings($dom);
13743: my ($vpnint,$remote_ip);
13744: if (ref($proxyinfo) eq 'HASH') {
13745: $vpnint = $proxyinfo->{'vpnint'};
13746: if ($vpnint) {
13747: $remote_ip = &get_requestor_ip($r,1,1);
13748: }
13749: }
13750: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
13751: return $alias;
13752: }
13753: }
13754: }
13755: return;
13756: }
13757:
13758: sub alias_sso {
13759: my ($lonid) = @_;
13760: if ($lonid eq '') {
13761: $lonid = $perlvar{'lonHostID'};
13762: }
13763: if (!defined(&hostname($lonid))) {
13764: return;
13765: }
13766: if ($lonid ne '') {
13767: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
13768: if ($cached) {
13769: return $use_alias;
13770: }
13771: my $dom = &Apache::lonnet::host_domain($lonid);
13772: if ($dom ne '') {
13773: my $cachetime = 60*60*24;
13774: my %domconfig =
13775: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
13776: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
13777: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
13778: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
13779: }
13780: }
13781: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
13782: }
13783: }
13784: return;
13785: }
13786:
13787: sub get_saml_landing {
13788: my ($lonid) = @_;
13789: if ($lonid eq '') {
13790: my $defdom = &default_login_domain();
13791: my @hosts = ¤t_machine_ids();
13792: if (@hosts > 1) {
13793: foreach my $hostid (@hosts) {
13794: if (&host_domain($hostid) eq $defdom) {
13795: $lonid = $hostid;
13796: last;
13797: }
13798: }
13799: } else {
13800: $lonid = $perlvar{'lonHostID'};
13801: }
13802: if ($lonid) {
13803: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
13804: return;
13805: }
13806: } else {
13807: return;
13808: }
13809: } elsif (!defined(&hostname($lonid))) {
13810: return;
13811: }
13812: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
13813: if ($cached) {
13814: return $landing;
13815: }
13816: my $dom = &Apache::lonnet::host_domain($lonid);
13817: if ($dom ne '') {
13818: my $cachetime = 60*60*24;
13819: my %domconfig =
13820: &Apache::lonnet::get_dom('configuration',['login'],$dom);
13821: if (ref($domconfig{'login'}) eq 'HASH') {
13822: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
13823: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
13824: $landing = 1;
13825: }
13826: }
13827: }
13828: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
13829: }
13830: return;
13831: }
13832:
1.31 www 13833: # ------------------------------------------------------------- Declutters URLs
13834:
13835: sub declutter {
13836: my $thisfn=shift;
1.569 albertel 13837: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13838: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13839: $thisfn=~s{^/home/httpd/html}{};
13840: }
1.31 www 13841: $thisfn=~s/^\///;
1.697 albertel 13842: $thisfn=~s|^adm/wrapper/||;
13843: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13844: $thisfn=~s/^res\///;
1.1172 bisitz 13845: $thisfn=~s/^priv\///;
1.1032 raeburn 13846: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13847: $thisfn=~s/\?.+$//;
13848: }
1.268 www 13849: return $thisfn;
13850: }
13851:
13852: # ------------------------------------------------------------- Clutter up URLs
13853:
13854: sub clutter {
13855: my $thisfn='/'.&declutter(shift);
1.887 albertel 13856: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13857: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13858: $thisfn='/res'.$thisfn;
13859: }
1.1031 raeburn 13860: if ($thisfn !~m|^/adm|) {
13861: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13862: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13863: } else {
13864: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13865: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13866: if ($embstyle eq 'ssi'
13867: || ($embstyle eq 'hdn')
13868: || ($embstyle eq 'rat')
13869: || ($embstyle eq 'prv')
13870: || ($embstyle eq 'ign')) {
13871: #do nothing with these
13872: } elsif (($embstyle eq 'img')
1.695 albertel 13873: || ($embstyle eq 'emb')
13874: || ($embstyle eq 'wrp')) {
13875: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13876: } elsif ($embstyle eq 'unk'
13877: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13878: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13879: } else {
1.718 www 13880: # &logthis("Got a blank emb style");
1.695 albertel 13881: }
1.694 albertel 13882: }
13883: }
1.31 www 13884: return $thisfn;
1.12 www 13885: }
13886:
1.787 albertel 13887: sub clutter_with_no_wrapper {
13888: my $uri = &clutter(shift);
13889: if ($uri =~ m-^/adm/-) {
13890: $uri =~ s-^/adm/wrapper/-/-;
13891: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13892: }
13893: return $uri;
13894: }
13895:
1.557 albertel 13896: sub freeze_escape {
13897: my ($value)=@_;
13898: if (ref($value)) {
13899: $value=&nfreeze($value);
13900: return '__FROZEN__'.&escape($value);
13901: }
13902: return &escape($value);
13903: }
13904:
1.11 www 13905:
1.557 albertel 13906: sub thaw_unescape {
13907: my ($value)=@_;
13908: if ($value =~ /^__FROZEN__/) {
13909: substr($value,0,10,undef);
13910: $value=&unescape($value);
13911: return &thaw($value);
13912: }
13913: return &unescape($value);
13914: }
13915:
1.436 albertel 13916: sub correct_line_ends {
13917: my ($result)=@_;
13918: $$result =~s/\r\n/\n/mg;
13919: $$result =~s/\r/\n/mg;
1.415 albertel 13920: }
1.1 albertel 13921: # ================================================================ Main Program
13922:
1.184 www 13923: sub goodbye {
1.204 albertel 13924: &logthis("Starting Shut down");
1.443 albertel 13925: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13926: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13927: #converted
1.599 albertel 13928: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13929: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13930: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13931: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13932: #1.1 only
1.870 albertel 13933: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13934: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13935: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13936: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13937: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13938: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13939: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13940: &flushcourselogs();
13941: &logthis("Shutting down");
13942: }
13943:
1.852 albertel 13944: sub get_dns {
1.1172.2.17 raeburn 13945: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13946: if (!$ignore_cache) {
13947: my ($content,$cached)=
13948: &Apache::lonnet::is_cached_new('dns',$url);
13949: if ($cached) {
1.1172.2.17 raeburn 13950: &$func($content,$hashref);
1.869 albertel 13951: return;
13952: }
13953: }
13954:
13955: my %alldns;
1.1172.2.96 raeburn 13956: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13957: foreach my $dns (<$config>) {
13958: next if ($dns !~ /^\^(\S*)/x);
13959: my $line = $1;
13960: my ($host,$protocol) = split(/:/,$line);
13961: if ($protocol ne 'https') {
13962: $protocol = 'http';
13963: }
13964: $alldns{$host} = $protocol;
1.979 raeburn 13965: }
1.1172.2.96 raeburn 13966: close($config);
1.869 albertel 13967: }
13968: while (%alldns) {
1.1172.2.52 raeburn 13969: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142 raeburn 13970: my @content;
13971: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
13972: my $command = (split('/',$url))[3];
13973: my ($dir,$file) = &parse_getdns_url($command,$url);
13974: delete($alldns{$dns});
13975: next if (($dir eq '') || ($file eq ''));
13976: if (open(my $config,'<',"$dir/$file")) {
13977: @content = <$config>;
13978: close($config);
13979: }
13980: } else {
13981: my $ua=new LWP::UserAgent;
13982: $ua->timeout(30);
13983: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13984: my $response=$ua->request($request);
13985: delete($alldns{$dns});
13986: next if ($response->is_error());
13987: @content = split("\n",$response->content);
13988: }
1.1172.2.17 raeburn 13989: unless ($nocache) {
1.1172.2.23 raeburn 13990: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13991: }
13992: &$func(\@content,$hashref);
1.869 albertel 13993: return;
1.852 albertel 13994: }
1.871 albertel 13995: my $which = (split('/',$url))[3];
13996: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13997: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13998: my @content = <$config>;
13999: &$func(\@content,$hashref);
14000: }
1.1172.2.17 raeburn 14001: return;
14002: }
14003:
14004: # ------------------------------------------------------Get DNS checksums file
14005: sub parse_dns_checksums_tab {
14006: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 14007: my $lonhost = $perlvar{'lonHostID'};
14008: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 14009: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 14010: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14011: my $webconfdir = '/etc/httpd/conf';
14012: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14013: $webconfdir = '/etc/apache2';
14014: } elsif ($distro =~ /^sles(\d+)$/) {
14015: if ($1 >= 10) {
14016: $webconfdir = '/etc/apache2';
14017: }
14018: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14019: if ($1 >= 10.0) {
14020: $webconfdir = '/etc/apache2';
14021: }
14022: }
1.1172.2.17 raeburn 14023: my ($release,$timestamp) = split(/\-/,$loncaparev);
14024: my (%chksum,%revnum);
14025: if (ref($lines) eq 'ARRAY') {
14026: chomp(@{$lines});
1.1172.2.34 raeburn 14027: my $version = shift(@{$lines});
14028: if ($version eq $release) {
1.1172.2.17 raeburn 14029: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 14030: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 14031: if ($file =~ m{^/etc/httpd/conf}) {
14032: if ($webconfdir eq '/etc/apache2') {
14033: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14034: }
14035: }
1.1172.2.34 raeburn 14036: $chksum{$file} = $shasum;
14037: $revnum{$file} = $version;
1.1172.2.17 raeburn 14038: }
14039: if (ref($hashref) eq 'HASH') {
14040: %{$hashref} = (
14041: sums => \%chksum,
14042: versions => \%revnum,
14043: );
14044: }
14045: }
14046: }
1.869 albertel 14047: return;
1.852 albertel 14048: }
1.1172.2.17 raeburn 14049:
14050: sub fetch_dns_checksums {
14051: my %checksums;
1.1172.2.34 raeburn 14052: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 14053: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 14054: my ($release,$timestamp) = split(/\-/,$loncaparev);
14055: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 14056: \%checksums);
14057: return \%checksums;
14058: }
14059:
1.1172.2.142 raeburn 14060: sub parse_getdns_url {
14061: my ($command,$url) = @_;
14062: my $dir = $perlvar{'lonTabDir'};
14063: my $file;
14064: if ($command eq 'hosts') {
14065: $file = 'dns_hosts.tab';
14066: } elsif ($command eq 'domain') {
14067: $file = 'dns_domain.tab';
14068: } elsif ($command eq 'checksums') {
14069: my $version = (split('/',$url))[4];
14070: $file = "dns_checksums/$version.tab",
14071: }
14072: return ($dir,$file);
14073: }
14074:
1.327 albertel 14075: # ------------------------------------------------------------ Read domain file
14076: {
1.852 albertel 14077: my $loaded;
1.846 albertel 14078: my %domain;
14079:
1.852 albertel 14080: sub parse_domain_tab {
14081: my ($lines) = @_;
14082: foreach my $line (@$lines) {
14083: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14084:
1.846 albertel 14085: chomp($line);
1.852 albertel 14086: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14087: my %this_domain;
14088: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14089: 'lang_def', 'city', 'longi', 'lati',
14090: 'primary') {
14091: $this_domain{$field} = shift(@elements);
14092: }
14093: $domain{$name} = \%this_domain;
1.852 albertel 14094: }
14095: }
1.864 albertel 14096:
14097: sub reset_domain_info {
14098: undef($loaded);
14099: undef(%domain);
14100: }
14101:
1.852 albertel 14102: sub load_domain_tab {
1.1172.2.70 raeburn 14103: my ($ignore_cache,$nocache) = @_;
14104: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14105: my $fh;
1.1172.2.96 raeburn 14106: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14107: my @lines = <$fh>;
14108: &parse_domain_tab(\@lines);
1.448 albertel 14109: }
1.852 albertel 14110: close($fh);
14111: $loaded = 1;
1.327 albertel 14112: }
1.846 albertel 14113:
14114: sub domain {
1.852 albertel 14115: &load_domain_tab() if (!$loaded);
14116:
1.846 albertel 14117: my ($name,$what) = @_;
14118: return if ( !exists($domain{$name}) );
14119:
14120: if (!$what) {
14121: return $domain{$name}{'description'};
14122: }
14123: return $domain{$name}{$what};
14124: }
1.974 raeburn 14125:
14126: sub domain_info {
14127: &load_domain_tab() if (!$loaded);
14128: return %domain;
14129: }
14130:
1.327 albertel 14131: }
14132:
14133:
1.1 albertel 14134: # ------------------------------------------------------------- Read hosts file
14135: {
1.838 albertel 14136: my %hostname;
1.844 albertel 14137: my %hostdom;
1.845 albertel 14138: my %libserv;
1.852 albertel 14139: my $loaded;
1.888 albertel 14140: my %name_to_host;
1.1074 raeburn 14141: my %internetdom;
1.1107 raeburn 14142: my %LC_dns_serv;
1.852 albertel 14143:
14144: sub parse_hosts_tab {
14145: my ($file) = @_;
14146: foreach my $configline (@$file) {
14147: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 14148: chomp($configline);
14149: if ($configline =~ /^\^/) {
14150: if ($configline =~ /^\^([\w.\-]+)/) {
14151: $LC_dns_serv{$1} = 1;
14152: }
14153: next;
14154: }
1.1074 raeburn 14155: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 14156: $name=~s/\s//g;
14157: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 14158: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14159: my $curr = $hostname{$id};
14160: my $skip;
14161: if (ref($name_to_host{$curr}) eq 'ARRAY') {
14162: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14163: $skip = 1;
14164: } else {
14165: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14166: }
14167: }
14168: unless ($skip) {
14169: push(@{$name_to_host{$name}},$id);
14170: }
14171: } else {
14172: push(@{$name_to_host{$name}},$id);
14173: }
1.852 albertel 14174: $hostname{$id}=$name;
14175: $hostdom{$id}=$domain;
14176: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 14177: if (defined($protocol)) {
14178: if ($protocol eq 'https') {
14179: $protocol{$id} = $protocol;
14180: } else {
14181: $protocol{$id} = 'http';
14182: }
1.968 raeburn 14183: } else {
1.969 raeburn 14184: $protocol{$id} = 'http';
1.968 raeburn 14185: }
1.1074 raeburn 14186: if (defined($intdom)) {
14187: $internetdom{$id} = $intdom;
14188: }
1.852 albertel 14189: }
14190: }
14191: }
1.864 albertel 14192:
14193: sub reset_hosts_info {
1.897 albertel 14194: &purge_remembered();
1.864 albertel 14195: &reset_domain_info();
14196: &reset_hosts_ip_info();
1.892 albertel 14197: undef(%name_to_host);
1.864 albertel 14198: undef(%hostname);
14199: undef(%hostdom);
14200: undef(%libserv);
14201: undef($loaded);
14202: }
1.1 albertel 14203:
1.852 albertel 14204: sub load_hosts_tab {
1.1172.2.70 raeburn 14205: my ($ignore_cache,$nocache) = @_;
14206: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 14207: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 14208: my @config = <$config>;
14209: &parse_hosts_tab(\@config);
14210: close($config);
14211: $loaded=1;
1.1 albertel 14212: }
1.852 albertel 14213:
1.838 albertel 14214: sub hostname {
1.852 albertel 14215: &load_hosts_tab() if (!$loaded);
14216:
1.838 albertel 14217: my ($lonid) = @_;
14218: return $hostname{$lonid};
14219: }
1.845 albertel 14220:
1.838 albertel 14221: sub all_hostnames {
1.852 albertel 14222: &load_hosts_tab() if (!$loaded);
14223:
1.838 albertel 14224: return %hostname;
14225: }
1.845 albertel 14226:
1.888 albertel 14227: sub all_names {
1.1172.2.70 raeburn 14228: my ($ignore_cache,$nocache) = @_;
14229: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 14230:
14231: return %name_to_host;
14232: }
14233:
1.974 raeburn 14234: sub all_host_domain {
14235: &load_hosts_tab() if (!$loaded);
14236: return %hostdom;
14237: }
14238:
1.845 albertel 14239: sub is_library {
1.852 albertel 14240: &load_hosts_tab() if (!$loaded);
14241:
1.845 albertel 14242: return exists($libserv{$_[0]});
14243: }
14244:
14245: sub all_library {
1.852 albertel 14246: &load_hosts_tab() if (!$loaded);
14247:
1.845 albertel 14248: return %libserv;
14249: }
14250:
1.1062 droeschl 14251: sub unique_library {
14252: #2x reverse removes all hostnames that appear more than once
14253: my %unique = reverse &all_library();
14254: return reverse %unique;
14255: }
14256:
1.841 albertel 14257: sub get_servers {
1.852 albertel 14258: &load_hosts_tab() if (!$loaded);
14259:
1.841 albertel 14260: my ($domain,$type) = @_;
14261: my %possible_hosts = ($type eq 'library') ? %libserv
14262: : %hostname;
14263: my %result;
1.842 albertel 14264: if (ref($domain) eq 'ARRAY') {
14265: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 14266: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 14267: $result{$host} = $hostname;
14268: }
14269: }
14270: } else {
14271: while ( my ($host,$hostname) = each(%possible_hosts)) {
14272: if ($hostdom{$host} eq $domain) {
14273: $result{$host} = $hostname;
14274: }
1.841 albertel 14275: }
14276: }
14277: return %result;
14278: }
1.845 albertel 14279:
1.1062 droeschl 14280: sub get_unique_servers {
14281: my %unique = reverse &get_servers(@_);
14282: return reverse %unique;
14283: }
14284:
1.844 albertel 14285: sub host_domain {
1.852 albertel 14286: &load_hosts_tab() if (!$loaded);
14287:
1.844 albertel 14288: my ($lonid) = @_;
14289: return $hostdom{$lonid};
14290: }
14291:
1.841 albertel 14292: sub all_domains {
1.852 albertel 14293: &load_hosts_tab() if (!$loaded);
14294:
1.841 albertel 14295: my %seen;
14296: my @uniq = grep(!$seen{$_}++, values(%hostdom));
14297: return @uniq;
14298: }
1.1074 raeburn 14299:
14300: sub internet_dom {
14301: &load_hosts_tab() if (!$loaded);
14302:
14303: my ($lonid) = @_;
14304: return $internetdom{$lonid};
14305: }
1.1107 raeburn 14306:
14307: sub is_LC_dns {
14308: &load_hosts_tab() if (!$loaded);
14309:
14310: my ($hostname) = @_;
14311: return exists($LC_dns_serv{$hostname});
14312: }
14313:
1.1 albertel 14314: }
14315:
1.847 albertel 14316: {
14317: my %iphost;
1.856 albertel 14318: my %name_to_ip;
14319: my %lonid_to_ip;
1.869 albertel 14320:
1.847 albertel 14321: sub get_hosts_from_ip {
14322: my ($ip) = @_;
14323: my %iphosts = &get_iphost();
14324: if (ref($iphosts{$ip})) {
14325: return @{$iphosts{$ip}};
14326: }
14327: return;
1.839 albertel 14328: }
1.864 albertel 14329:
14330: sub reset_hosts_ip_info {
14331: undef(%iphost);
14332: undef(%name_to_ip);
14333: undef(%lonid_to_ip);
14334: }
1.856 albertel 14335:
14336: sub get_host_ip {
14337: my ($lonid) = @_;
14338: if (exists($lonid_to_ip{$lonid})) {
14339: return $lonid_to_ip{$lonid};
14340: }
14341: my $name=&hostname($lonid);
14342: my $ip = gethostbyname($name);
14343: return if (!$ip || length($ip) ne 4);
14344: $ip=inet_ntoa($ip);
14345: $name_to_ip{$name} = $ip;
14346: $lonid_to_ip{$lonid} = $ip;
14347: return $ip;
14348: }
1.847 albertel 14349:
14350: sub get_iphost {
1.1172.2.70 raeburn 14351: my ($ignore_cache,$nocache) = @_;
1.894 albertel 14352:
1.869 albertel 14353: if (!$ignore_cache) {
14354: if (%iphost) {
14355: return %iphost;
14356: }
14357: my ($ip_info,$cached)=
14358: &Apache::lonnet::is_cached_new('iphost','iphost');
14359: if ($cached) {
14360: %iphost = %{$ip_info->[0]};
14361: %name_to_ip = %{$ip_info->[1]};
14362: %lonid_to_ip = %{$ip_info->[2]};
14363: return %iphost;
14364: }
14365: }
1.894 albertel 14366:
14367: # get yesterday's info for fallback
14368: my %old_name_to_ip;
14369: my ($ip_info,$cached)=
14370: &Apache::lonnet::is_cached_new('iphost','iphost');
14371: if ($cached) {
14372: %old_name_to_ip = %{$ip_info->[1]};
14373: }
14374:
1.1172.2.70 raeburn 14375: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14376: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14377: my $ip;
14378: if (!exists($name_to_ip{$name})) {
14379: $ip = gethostbyname($name);
14380: if (!$ip || length($ip) ne 4) {
1.894 albertel 14381: if (defined($old_name_to_ip{$name})) {
14382: $ip = $old_name_to_ip{$name};
14383: &logthis("Can't find $name defaulting to old $ip");
14384: } else {
14385: &logthis("Name $name no IP found");
14386: next;
14387: }
14388: } else {
14389: $ip=inet_ntoa($ip);
1.847 albertel 14390: }
14391: $name_to_ip{$name} = $ip;
14392: } else {
14393: $ip = $name_to_ip{$name};
1.653 albertel 14394: }
1.888 albertel 14395: foreach my $id (@{ $name_to_host{$name} }) {
14396: $lonid_to_ip{$id} = $ip;
14397: }
14398: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14399: }
1.1172.2.70 raeburn 14400: unless ($nocache) {
14401: &do_cache_new('iphost','iphost',
14402: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14403: 48*60*60);
14404: }
1.869 albertel 14405:
1.847 albertel 14406: return %iphost;
1.598 albertel 14407: }
14408:
1.992 raeburn 14409: #
14410: # Given a DNS returns the loncapa host name for that DNS
14411: #
14412: sub host_from_dns {
14413: my ($dns) = @_;
14414: my @hosts;
14415: my $ip;
14416:
1.993 raeburn 14417: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14418: $ip = $name_to_ip{$dns};
14419: }
14420: if (!$ip) {
14421: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14422: if (length($ip) == 4) {
14423: $ip = &IO::Socket::inet_ntoa($ip);
14424: }
14425: }
14426: if ($ip) {
14427: @hosts = get_hosts_from_ip($ip);
14428: return $hosts[0];
14429: }
14430: return undef;
1.986 foxr 14431: }
1.992 raeburn 14432:
1.1074 raeburn 14433: sub get_internet_names {
14434: my ($lonid) = @_;
14435: return if ($lonid eq '');
14436: my ($idnref,$cached)=
14437: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14438: if ($cached) {
14439: return $idnref;
14440: }
14441: my $ip = &get_host_ip($lonid);
14442: my @hosts = &get_hosts_from_ip($ip);
14443: my %iphost = &get_iphost();
14444: my (@idns,%seen);
14445: foreach my $id (@hosts) {
14446: my $dom = &host_domain($id);
14447: my $prim_id = &domain($dom,'primary');
14448: my $prim_ip = &get_host_ip($prim_id);
14449: next if ($seen{$prim_ip});
14450: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14451: foreach my $id (@{$iphost{$prim_ip}}) {
14452: my $intdom = &internet_dom($id);
14453: unless (grep(/^\Q$intdom\E$/,@idns)) {
14454: push(@idns,$intdom);
14455: }
14456: }
14457: }
14458: $seen{$prim_ip} = 1;
14459: }
1.1172.2.23 raeburn 14460: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14461: }
14462:
1.986 foxr 14463: }
14464:
1.1079 raeburn 14465: sub all_loncaparevs {
1.1172.2.39 raeburn 14466: 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 14467: }
14468:
1.1172.2.27 raeburn 14469: # ------------------------------------------------------- Read loncaparev table
14470: {
14471: sub load_loncaparevs {
14472: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14473: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14474: while (my $configline=<$config>) {
14475: chomp($configline);
14476: my ($hostid,$loncaparev)=split(/:/,$configline);
14477: $loncaparevs{$hostid}=$loncaparev;
14478: }
14479: close($config);
14480: }
14481: }
14482: }
14483: }
14484:
14485: # ----------------------------------------------------- Read serverhostID table
14486: {
14487: sub load_serverhomeIDs {
14488: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14489: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14490: while (my $configline=<$config>) {
14491: chomp($configline);
14492: my ($name,$id)=split(/:/,$configline);
14493: $serverhomeIDs{$name}=$id;
14494: }
14495: close($config);
14496: }
14497: }
14498: }
14499: }
14500:
14501:
1.862 albertel 14502: BEGIN {
14503:
14504: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14505: unless ($readit) {
14506: {
14507: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14508: %perlvar = (%perlvar,%{$configvars});
14509: }
14510:
14511:
1.1 albertel 14512: # ------------------------------------------------------ Read spare server file
14513: {
1.1172.2.96 raeburn 14514: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14515:
14516: while (my $configline=<$config>) {
14517: chomp($configline);
1.284 matthew 14518: if ($configline) {
1.784 albertel 14519: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14520: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14521: push(@{ $spareid{$type} }, $host);
1.1 albertel 14522: }
14523: }
1.448 albertel 14524: close($config);
1.1 albertel 14525: }
1.11 www 14526: # ------------------------------------------------------------ Read permissions
14527: {
1.1172.2.96 raeburn 14528: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14529:
14530: while (my $configline=<$config>) {
1.448 albertel 14531: chomp($configline);
14532: if ($configline) {
14533: my ($role,$perm)=split(/ /,$configline);
14534: if ($perm ne '') { $pr{$role}=$perm; }
14535: }
1.11 www 14536: }
1.448 albertel 14537: close($config);
1.11 www 14538: }
14539:
14540: # -------------------------------------------- Read plain texts for permissions
14541: {
1.1172.2.96 raeburn 14542: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14543:
14544: while (my $configline=<$config>) {
1.448 albertel 14545: chomp($configline);
14546: if ($configline) {
1.742 raeburn 14547: my ($short,@plain)=split(/:/,$configline);
14548: %{$prp{$short}} = ();
14549: if (@plain > 0) {
14550: $prp{$short}{'std'} = $plain[0];
14551: for (my $i=1; $i<@plain; $i++) {
14552: $prp{$short}{'alt'.$i} = $plain[$i];
14553: }
14554: }
1.448 albertel 14555: }
1.135 www 14556: }
1.448 albertel 14557: close($config);
1.135 www 14558: }
14559:
14560: # ---------------------------------------------------------- Read package table
14561: {
1.1172.2.96 raeburn 14562: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14563:
14564: while (my $configline=<$config>) {
1.483 albertel 14565: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14566: chomp($configline);
14567: my ($short,$plain)=split(/:/,$configline);
14568: my ($pack,$name)=split(/\&/,$short);
14569: if ($plain ne '') {
14570: $packagetab{$pack.'&'.$name.'&name'}=$name;
14571: $packagetab{$short}=$plain;
14572: }
1.11 www 14573: }
1.448 albertel 14574: close($config);
1.329 matthew 14575: }
14576:
1.1172.2.27 raeburn 14577: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14578:
1.1172.2.27 raeburn 14579: &load_loncaparevs();
14580:
14581: # ------------------------------------------------------- Read serverhostID table
14582:
14583: &load_serverhomeIDs();
1.1074 raeburn 14584:
1.1172.2.27 raeburn 14585: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14586: {
14587: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14588: if (-e $file) {
14589: my $parser = HTML::LCParser->new($file);
14590: while (my $token = $parser->get_token()) {
14591: if ($token->[0] eq 'S') {
14592: my $item = $token->[1];
14593: my $name = $token->[2]{'name'};
14594: my $value = $token->[2]{'value'};
14595: if ($item ne '' && $name ne '' && $value ne '') {
14596: my $release = $parser->get_text();
14597: $release =~ s/(^\s*|\s*$ )//gx;
14598: $needsrelease{$item.':'.$name.':'.$value} = $release;
14599: }
14600: }
14601: }
14602: }
1.1073 raeburn 14603: }
14604:
1.1138 raeburn 14605: # ---------------------------------------------------------- Read managers table
14606: {
14607: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14608: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14609: while (my $configline=<$config>) {
14610: chomp($configline);
14611: next if ($configline =~ /^\#/);
14612: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14613: $managerstab{$configline} = 1;
14614: }
14615: }
14616: close($config);
14617: }
14618: }
14619: }
14620:
1.329 matthew 14621: # ------------- set up temporary directory
14622: {
1.1117 foxr 14623: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14624:
1.11 www 14625: }
14626:
1.1172.2.104 raeburn 14627: # ------------- set default texengine (domain default overrides this)
14628: {
14629: $deftex = LONCAPA::texengine();
14630: }
14631:
1.1172.2.114 raeburn 14632: # ------------- set default minimum length for passwords for internal auth users
14633: {
14634: $passwdmin = LONCAPA::passwd_min();
14635: }
14636:
1.794 albertel 14637: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14638: 'compress_threshold'=> 20_000,
14639: });
1.185 www 14640:
1.281 www 14641: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14642: $dumpcount=0;
1.958 www 14643: $locknum=0;
1.22 www 14644:
1.163 harris41 14645: &logtouch();
1.672 albertel 14646: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14647: $readit=1;
1.564 albertel 14648: {
14649: use integer;
14650: my $test=(2**32)+1;
1.568 albertel 14651: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14652: &logthis(" Detected 64bit platform ($_64bit)");
14653: }
1.195 www 14654: }
1.1 albertel 14655: }
1.179 www 14656:
1.1 albertel 14657: 1;
1.191 harris41 14658: __END__
14659:
1.243 albertel 14660: =pod
14661:
1.191 harris41 14662: =head1 NAME
14663:
1.243 albertel 14664: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14665:
14666: =head1 SYNOPSIS
14667:
1.243 albertel 14668: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14669:
14670: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14671:
1.243 albertel 14672: Common parameters:
14673:
14674: =over 4
14675:
14676: =item *
14677:
14678: $uname : an internal username (if $cname expecting a course Id specifically)
14679:
14680: =item *
14681:
14682: $udom : a domain (if $cdom expecting a course's domain specifically)
14683:
14684: =item *
14685:
14686: $symb : a resource instance identifier
14687:
14688: =item *
14689:
14690: $namespace : the name of a .db file that contains the data needed or
14691: being set.
14692:
14693: =back
14694:
1.394 bowersj2 14695: =head1 OVERVIEW
1.191 harris41 14696:
1.394 bowersj2 14697: lonnet provides subroutines which interact with the
14698: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14699: about classes, users, and resources.
1.243 albertel 14700:
14701: For many of these objects you can also use this to store data about
14702: them or modify them in various ways.
1.191 harris41 14703:
1.394 bowersj2 14704: =head2 Symbs
1.191 harris41 14705:
1.394 bowersj2 14706: To identify a specific instance of a resource, LON-CAPA uses symbols
14707: or "symbs"X<symb>. These identifiers are built from the URL of the
14708: map, the resource number of the resource in the map, and the URL of
14709: the resource itself. The latter is somewhat redundant, but might help
14710: if maps change.
14711:
14712: An example is
14713:
14714: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14715:
14716: The respective map entry is
14717:
14718: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14719: title="Problem 2">
14720: </resource>
14721:
14722: Symbs are used by the random number generator, as well as to store and
14723: restore data specific to a certain instance of for example a problem.
14724:
14725: =head2 Storing And Retrieving Data
14726:
14727: X<store()>X<cstore()>X<restore()>Three of the most important functions
14728: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14729: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14730: is is the non-critical message twin of cstore. These functions are for
14731: handlers to store a perl hash to a user's permanent data space in an
14732: easy manner, and to retrieve it again on another call. It is expected
14733: that a handler would use this once at the beginning to retrieve data,
14734: and then again once at the end to send only the new data back.
14735:
14736: The data is stored in the user's data directory on the user's
14737: homeserver under the ID of the course.
14738:
14739: The hash that is returned by restore will have all of the previous
14740: value for all of the elements of the hash.
14741:
14742: Example:
14743:
14744: #creating a hash
14745: my %hash;
14746: $hash{'foo'}='bar';
14747:
14748: #storing it
14749: &Apache::lonnet::cstore(\%hash);
14750:
14751: #changing a value
14752: $hash{'foo'}='notbar';
14753:
14754: #adding a new value
14755: $hash{'bar'}='foo';
14756: &Apache::lonnet::cstore(\%hash);
14757:
14758: #retrieving the hash
14759: my %history=&Apache::lonnet::restore();
14760:
14761: #print the hash
14762: foreach my $key (sort(keys(%history))) {
14763: print("\%history{$key} = $history{$key}");
14764: }
14765:
14766: Will print out:
1.191 harris41 14767:
1.394 bowersj2 14768: %history{1:foo} = bar
14769: %history{1:keys} = foo:timestamp
14770: %history{1:timestamp} = 990455579
14771: %history{2:bar} = foo
14772: %history{2:foo} = notbar
14773: %history{2:keys} = foo:bar:timestamp
14774: %history{2:timestamp} = 990455580
14775: %history{bar} = foo
14776: %history{foo} = notbar
14777: %history{timestamp} = 990455580
14778: %history{version} = 2
14779:
14780: Note that the special hash entries C<keys>, C<version> and
14781: C<timestamp> were added to the hash. C<version> will be equal to the
14782: total number of versions of the data that have been stored. The
14783: C<timestamp> attribute will be the UNIX time the hash was
14784: stored. C<keys> is available in every historical section to list which
14785: keys were added or changed at a specific historical revision of a
14786: hash.
14787:
14788: B<Warning>: do not store the hash that restore returns directly. This
14789: will cause a mess since it will restore the historical keys as if the
14790: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14791:
1.394 bowersj2 14792: Calling convention:
1.191 harris41 14793:
1.1172.2.27 raeburn 14794: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14795: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14796:
1.394 bowersj2 14797: For more detailed information, see lonnet specific documentation.
1.191 harris41 14798:
1.394 bowersj2 14799: =head1 RETURN MESSAGES
1.191 harris41 14800:
1.394 bowersj2 14801: =over 4
1.191 harris41 14802:
1.394 bowersj2 14803: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14804:
1.394 bowersj2 14805: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14806: when the connection is brought back up
1.191 harris41 14807:
1.394 bowersj2 14808: =item * B<con_failed>: unable to contact remote host and unable to save message
14809: for later delivery
1.191 harris41 14810:
1.967 bisitz 14811: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14812:
1.394 bowersj2 14813: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14814: that was requested
1.191 harris41 14815:
1.243 albertel 14816: =back
1.191 harris41 14817:
1.243 albertel 14818: =head1 PUBLIC SUBROUTINES
1.191 harris41 14819:
1.243 albertel 14820: =head2 Session Environment Functions
1.191 harris41 14821:
1.243 albertel 14822: =over 4
1.191 harris41 14823:
1.394 bowersj2 14824: =item *
14825: X<appenv()>
1.949 raeburn 14826: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14827: the user envirnoment file, and will be restored for each access this
1.620 albertel 14828: user makes during this session, also modifies the %env for the current
1.949 raeburn 14829: process. Optional rolesarrayref - if defined contains a reference to an array
14830: of roles which are exempt from the restriction on modifying user.role entries
14831: in the user's environment.db and in %env.
1.191 harris41 14832:
14833: =item *
1.394 bowersj2 14834: X<delenv()>
1.987 raeburn 14835: B<delenv($delthis,$regexp)>: removes all items from the session
14836: environment file that begin with $delthis. If the
14837: optional second arg - $regexp - is true, $delthis is treated as a
14838: regular expression, otherwise \Q$delthis\E is used.
14839: The values are also deleted from the current processes %env.
1.191 harris41 14840:
1.795 albertel 14841: =item * get_env_multiple($name)
14842:
14843: gets $name from the %env hash, it seemlessly handles the cases where multiple
14844: values may be defined and end up as an array ref.
14845:
14846: returns an array of values
14847:
1.243 albertel 14848: =back
14849:
14850: =head2 User Information
1.191 harris41 14851:
1.243 albertel 14852: =over 4
1.191 harris41 14853:
14854: =item *
1.394 bowersj2 14855: X<queryauthenticate()>
14856: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14857: authentication scheme
14858:
14859: =item *
1.394 bowersj2 14860: X<authenticate()>
1.1073 raeburn 14861: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14862: authenticate user from domain's lib servers (first use the current
14863: one). C<$upass> should be the users password.
1.1073 raeburn 14864: $checkdefauth is optional (value is 1 if a check should be made to
14865: authenticate user using default authentication method, and allow
14866: account creation if username does not have account in the domain).
14867: $clientcancheckhost is optional (value is 1 if checking whether the
14868: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14869:
14870: =item *
1.394 bowersj2 14871: X<homeserver()>
14872: B<homeserver($uname,$udom)>: find the server which has
14873: the user's directory and files (there must be only one), this caches
14874: the answer, and also caches if there is a borken connection.
1.191 harris41 14875:
14876: =item *
1.394 bowersj2 14877: X<idget()>
14878: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14879: (IDs are a unique resource in a domain, there must be only 1 ID per
14880: username, and only 1 username per ID in a specific domain) (returns
14881: hash: id=>name,id=>name)
1.191 harris41 14882:
14883: =item *
1.394 bowersj2 14884: X<idrget()>
14885: B<idrget($udom,@unames)>: find the IDs behind a list of
14886: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14887:
14888: =item *
1.394 bowersj2 14889: X<idput()>
14890: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14891:
14892: =item *
1.394 bowersj2 14893: X<rolesinit()>
1.1169 droeschl 14894: B<rolesinit($udom,$username)>: get user privileges.
14895: returns user role, first access and timer interval hashes
1.243 albertel 14896:
14897: =item *
1.1171 droeschl 14898: X<privileged()>
14899: B<privileged($username,$domain)>: returns a true if user has a
14900: privileged and active role (i.e. su or dc), false otherwise.
14901:
14902: =item *
1.551 albertel 14903: X<getsection()>
14904: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14905: course $cname, return section name/number or '' for "not in course"
14906: and '-1' for "no section"
14907:
14908: =item *
1.394 bowersj2 14909: X<userenvironment()>
14910: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14911: passed in @what from the requested user's environment, returns a hash
14912:
1.858 raeburn 14913: =item *
14914: X<userlog_query()>
1.859 albertel 14915: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14916: activity.log file. %filters defines filters applied when parsing the
14917: log file. These can be start or end timestamps, or the type of action
14918: - log to look for Login or Logout events, check for Checkin or
14919: Checkout, role for role selection. The response is in the form
14920: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14921: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14922:
1.243 albertel 14923: =back
14924:
14925: =head2 User Roles
14926:
14927: =over 4
14928:
14929: =item *
14930:
1.1172.2.65 raeburn 14931: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14932: returns codes for allowed actions.
14933:
14934: The first argument is required, all others are optional.
14935:
14936: $priv is the privilege being checked.
14937: $uri contains additional information about what is being checked for access (e.g.,
14938: URL, course ID etc.).
14939: $symb is the unique resource instance identifier in a course; if needed,
14940: but not provided, it will be retrieved via a call to &symbread().
14941: $role is the role for which a priv is being checked (only used if priv is evb).
14942: $clientip is the user's IP address (only used when checking for access to portfolio
14943: files).
14944: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14945: prevents recursive calls to &allowed.
14946:
1.243 albertel 14947: F: full access
14948: U,I,K: authentication modes (cxx only)
14949: '': forbidden
14950: 1: user needs to choose course
14951: 2: browse allowed
1.766 albertel 14952: A: passphrase authentication needed
1.1172.2.65 raeburn 14953: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14954:
14955: =item *
14956:
1.1172.2.13 raeburn 14957: constructaccess($url,$setpriv) : check for access to construction space URL
14958:
14959: See if the owner domain and name in the URL match those in the
14960: expected environment. If so, return three element list
14961: ($ownername,$ownerdomain,$ownerhome).
14962:
14963: Otherwise return the null string.
14964:
14965: If second argument 'setpriv' is true, it assigns the privileges,
14966: and returns the same three element list, unless the owner has
14967: blocked "ad hoc" Domain Coordinator access to the Author Space,
14968: in which case the null string is returned.
14969:
14970: =item *
14971:
1.1172.2.84 raeburn 14972: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14973: define a custom role rolename set privileges in format of lonTabs/roles.tab
14974: for system, domain, and course level. $uname and $udom are optional (current
14975: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14976:
14977: =item *
14978:
1.988 raeburn 14979: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14980: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14981: $type is Course (default) or Community.
1.988 raeburn 14982: If $forcedefault evaluates to true, text returned will be default
14983: text for $type. Otherwise, if this is a course, the text returned
14984: will be a custom name for the role (if defined in the course's
14985: environment). If no custom name is defined the default is returned.
14986:
1.832 raeburn 14987: =item *
14988:
1.1172.2.23 raeburn 14989: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14990: All arguments are optional. Returns a hash of a roles, either for
14991: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14992: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14993: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14994: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14995: For each key, value is set to colon-separated start and end times for
14996: the role. If no username and domain are specified, will default to
1.934 raeburn 14997: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14998: of role statuses (active, future or previous), roles
14999: (e.g., cc,in, st etc.) and domains of the roles which can be used
15000: to restrict the list of roles reported. If no array ref is
15001: provided for types, will default to return only active roles.
1.834 albertel 15002:
1.1172.2.13 raeburn 15003: =item *
15004:
15005: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15006: user: $uname:$udom has a role in the course: $cdom_$cnum.
15007:
15008: Additional optional arguments are: $type (if role checking is to be restricted
15009: to certain user status types -- previous (expired roles), active (currently
15010: available roles) or future (roles available in the future), and
15011: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 15012: have active Domain Coordinator role in course's domain or in additional
15013: domains (specified in 'Domains to check for privileged users' in course
15014: environment -- set via: Course Settings -> Classlists and staff listing).
15015:
15016: =item *
15017:
15018: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15019: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15020: $possdomains and $possroles are optional array refs -- to domains to check and
15021: roles to check. If $possdomains is not specified, a dump will be done of the
15022: users' roles.db to check for a dc or su role in any domain. This can be
15023: time consuming if &privileged is called repeatedly (e.g., when displaying a
15024: classlist), so in such cases, supplying a $possdomains array is preferred, as
15025: this then allows &privileged_by_domain() to be used, which caches the identity
15026: of privileged users, eliminating the need for repeated calls to &dump().
15027:
15028: =item *
15029:
15030: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15031: where the outer hash keys are domains specified in the $possdomains array ref,
15032: next inner hash keys are privileged roles specified in the $roles array ref,
15033: and the innermost hash contains key = value pairs for username:domain = end:start
15034: for active or future "privileged" users with that role in that domain. To avoid
15035: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15036: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 15037:
1.243 albertel 15038: =back
15039:
15040: =head2 User Modification
15041:
15042: =over 4
15043:
15044: =item *
15045:
1.957 raeburn 15046: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15047: user for the level given by URL. Optional start and end dates (leave empty
15048: string or zero for "no date")
1.191 harris41 15049:
15050: =item *
15051:
1.243 albertel 15052: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15053: change a users, password, possible return values are: ok,
15054: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15055: refused
1.191 harris41 15056:
15057: =item *
15058:
1.243 albertel 15059: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15060:
15061: =item *
15062:
1.1058 raeburn 15063: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15064: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15065:
15066: will update user information (firstname,middlename,lastname,generation,
15067: permanentemail), and if forceid is true, student/employee ID also.
15068: A user's institutional affiliation(s) can also be updated.
15069: User information fields will not be overwritten with empty entries
15070: unless the field is included in the $candelete array reference.
15071: This array is included when a single user is modified via "Manage Users",
15072: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15073:
15074: =item *
15075:
1.286 matthew 15076: modifystudent
15077:
1.957 raeburn 15078: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 15079: The course id is resolved based on the current user's environment.
15080: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15081: associated with a course.
15082:
1.297 matthew 15083: This call is essentially a wrapper for lonnet::modifyuser and
15084: lonnet::modify_student_enrollment
1.286 matthew 15085:
15086: Inputs:
15087:
15088: =over 4
15089:
1.957 raeburn 15090: =item B<$udom> Student's loncapa domain
1.286 matthew 15091:
1.957 raeburn 15092: =item B<$uname> Student's loncapa login name
1.286 matthew 15093:
1.964 bisitz 15094: =item B<$uid> Student/Employee ID
1.286 matthew 15095:
1.957 raeburn 15096: =item B<$umode> Student's authentication mode
1.286 matthew 15097:
1.957 raeburn 15098: =item B<$upass> Student's password
1.286 matthew 15099:
1.957 raeburn 15100: =item B<$first> Student's first name
1.286 matthew 15101:
1.957 raeburn 15102: =item B<$middle> Student's middle name
1.286 matthew 15103:
1.957 raeburn 15104: =item B<$last> Student's last name
1.286 matthew 15105:
1.957 raeburn 15106: =item B<$gene> Student's generation
1.286 matthew 15107:
1.957 raeburn 15108: =item B<$usec> Student's section in course
1.286 matthew 15109:
15110: =item B<$end> Unix time of the roles expiration
15111:
15112: =item B<$start> Unix time of the roles start date
15113:
15114: =item B<$forceid> If defined, allow $uid to be changed
15115:
15116: =item B<$desiredhome> server to use as home server for student
15117:
1.957 raeburn 15118: =item B<$email> Student's permanent e-mail address
15119:
15120: =item B<$type> Type of enrollment (auto or manual)
15121:
1.963 raeburn 15122: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
15123:
15124: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 15125:
1.963 raeburn 15126: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 15127:
1.963 raeburn 15128: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 15129:
1.1172.2.19 raeburn 15130: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15131:
15132: =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 15133:
1.286 matthew 15134: =back
1.297 matthew 15135:
15136: =item *
15137:
15138: modify_student_enrollment
15139:
1.1172.2.31 raeburn 15140: Change a student's enrollment status in a class. The environment variable
1.297 matthew 15141: 'role.request.course' must be defined for this function to proceed.
15142:
15143: Inputs:
15144:
15145: =over 4
15146:
1.1172.2.31 raeburn 15147: =item $udom, student's domain
1.297 matthew 15148:
1.1172.2.31 raeburn 15149: =item $uname, student's name
1.297 matthew 15150:
1.1172.2.31 raeburn 15151: =item $uid, student's user id
1.297 matthew 15152:
1.1172.2.31 raeburn 15153: =item $first, student's first name
1.297 matthew 15154:
15155: =item $middle
15156:
15157: =item $last
15158:
15159: =item $gene
15160:
15161: =item $usec
15162:
15163: =item $end
15164:
15165: =item $start
15166:
1.957 raeburn 15167: =item $type
15168:
15169: =item $locktype
15170:
15171: =item $cid
15172:
15173: =item $selfenroll
15174:
15175: =item $context
15176:
1.1172.2.19 raeburn 15177: =item $credits, number of credits student will earn from this class
15178:
1.1172.2.76 raeburn 15179: =item $instsec, institutional course section code for student
15180:
1.297 matthew 15181: =back
15182:
1.191 harris41 15183:
15184: =item *
15185:
1.243 albertel 15186: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15187: custom role; give a custom role to a user for the level given by URL. Specify
15188: name and domain of role author, and role name
1.191 harris41 15189:
15190: =item *
15191:
1.243 albertel 15192: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 15193:
15194: =item *
15195:
1.243 albertel 15196: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15197:
15198: =back
15199:
15200: =head2 Course Infomation
15201:
15202: =over 4
1.191 harris41 15203:
15204: =item *
15205:
1.1118 foxr 15206: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 15207: specified course id, including all environment settings for the
15208: course, the description of the course will be in the hash under the
15209: key 'description'
1.191 harris41 15210:
1.1118 foxr 15211: $options is an optional parameter that if supplied is a hash reference that controls
15212: what how this function works. It has the following key/values:
15213:
15214: =over 4
15215:
15216: =item freshen_cache
15217:
15218: If defined, and the environment cache for the course is valid, it is
15219: returned in the returned hash.
15220:
15221: =item one_time
15222:
15223: If defined, the last cache time is set to _now_
15224:
15225: =item user
15226:
15227: If defined, the supplied username is used instead of the current user.
15228:
15229:
15230: =back
15231:
1.191 harris41 15232: =item *
15233:
1.624 albertel 15234: resdata($name,$domain,$type,@which) : request for current parameter
15235: setting for a specific $type, where $type is either 'course' or 'user',
15236: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 15237: answers for 10 minutes.
1.243 albertel 15238:
1.877 foxr 15239: =item *
15240:
15241: get_courseresdata($courseid, $domain) : dump the entire course resource
15242: data base, returning a hash that is keyed by the resource name and has
15243: values that are the resource value. I believe that the timestamps and
15244: versions are also returned.
15245:
1.1172.2.31 raeburn 15246: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15247: supplemental content area. This routine caches the number of files for
15248: 10 minutes.
15249:
1.243 albertel 15250: =back
15251:
15252: =head2 Course Modification
15253:
15254: =over 4
1.191 harris41 15255:
15256: =item *
15257:
1.243 albertel 15258: writecoursepref($courseid,%prefs) : write preferences (environment
15259: database) for a course
1.191 harris41 15260:
15261: =item *
15262:
1.1011 raeburn 15263: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15264:
15265: =item *
15266:
1.1038 raeburn 15267: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 15268:
1.1167 droeschl 15269: =item *
15270:
15271: is_course($courseid), is_course($cdom, $cnum)
15272:
15273: Accepts either a combined $courseid (in the form of domain_courseid) or the
15274: two component version $cdom, $cnum. It checks if the specified course exists.
15275:
15276: Returns:
15277: undef if the course doesn't exist, otherwise
15278: in scalar context the combined courseid.
15279: in list context the two components of the course identifier, domain and
15280: courseid.
15281:
1.243 albertel 15282: =back
15283:
1.1172.2.109 raeburn 15284: =head2 Bubblesheet Configuration
15285:
15286: =over 4
15287:
15288: =item *
15289:
15290: get_scantron_config($which)
15291:
15292: $which - the name of the configuration to parse from the file.
15293:
15294: Parses and returns the bubblesheet configuration line selected as a
15295: hash of configuration file fields.
15296:
15297:
15298: Returns:
15299: If the named configuration is not in the file, an empty
15300: hash is returned.
15301:
15302: a hash with the fields
15303: name - internal name for the this configuration setup
15304: description - text to display to operator that describes this config
15305: CODElocation - if 0 or the string 'none'
15306: - no CODE exists for this config
15307: if -1 || the string 'letter'
15308: - a CODE exists for this config and is
15309: a string of letters
15310: Unsupported value (but planned for future support)
15311: if a positive integer
15312: - The CODE exists as the first n items from
15313: the question section of the form
15314: if the string 'number'
15315: - The CODE exists for this config and is
15316: a string of numbers
15317: CODEstart - (only matter if a CODE exists) column in the line where
15318: the CODE starts
15319: CODElength - length of the CODE
15320: IDstart - column where the student/employee ID starts
15321: IDlength - length of the student/employee ID info
15322: Qstart - column where the information from the bubbled
15323: 'questions' start
15324: Qlength - number of columns comprising a single bubble line from
15325: the sheet. (usually either 1 or 10)
15326: Qon - either a single character representing the character used
15327: to signal a bubble was chosen in the positional setup, or
15328: the string 'letter' if the letter of the chosen bubble is
15329: in the final, or 'number' if a number representing the
15330: chosen bubble is in the file (1->A 0->J)
15331: Qoff - the character used to represent that a bubble was
15332: left blank
15333: PaperID - if the scanning process generates a unique number for each
15334: sheet scanned the column that this ID number starts in
15335: PaperIDlength - number of columns that comprise the unique ID number
15336: for the sheet of paper
15337: FirstName - column that the first name starts in
15338: FirstNameLength - number of columns that the first name spans
15339: LastName - column that the last name starts in
15340: LastNameLength - number of columns that the last name spans
15341: BubblesPerRow - number of bubbles available in each row used to
15342: bubble an answer. (If not specified, 10 assumed).
15343:
15344:
15345: =item *
15346:
15347: get_scantronformat_file($cdom)
15348:
15349: $cdom - the course's domain (optional); if not supplied, uses
15350: domain for current $env{'request.course.id'}.
15351:
15352: Returns an array containing lines from the scantron format file for
15353: the domain of the course.
15354:
15355: If a url for a custom.tab file is listed in domain's configuration.db,
15356: lines are from this file.
15357:
15358: Otherwise, if a default.tab has been published in RES space by the
15359: domainconfig user, lines are from this file.
15360:
15361: Otherwise, fall back to getting lines from the legacy file on the
15362: local server: /home/httpd/lonTabs/default_scantronformat.tab
15363:
15364: =back
15365:
1.243 albertel 15366: =head2 Resource Subroutines
15367:
15368: =over 4
1.191 harris41 15369:
15370: =item *
15371:
1.243 albertel 15372: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15373:
15374: =item *
15375:
1.243 albertel 15376: repcopy($filename) : subscribes to the requested file, and attempts to
15377: replicate from the owning library server, Might return
1.607 raeburn 15378: 'unavailable', 'not_found', 'forbidden', 'ok', or
15379: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15380: resource. Expects the local filesystem pathname
15381: (/home/httpd/html/res/....)
15382:
15383: =back
15384:
15385: =head2 Resource Information
15386:
15387: =over 4
1.191 harris41 15388:
15389: =item *
15390:
1.1172.2.28 raeburn 15391: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15392: and returns the value of a variety of different possible values,
15393: $varname should be a request string, and the other parameters can be
15394: used to specify who and what one is asking about. Ordinarily, $cid
15395: does not need to be specified, as it is retrived from
15396: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15397: within lonuserstate::loadmap() when initializing a course, before
15398: $env{'request.course.id'} has been set, so it needs to be provided
15399: in that one case.
1.243 albertel 15400:
15401: Possible values for $varname are environment.lastname (or other item
15402: from the envirnment hash), user.name (or someother aspect about the
15403: user), resource.0.maxtries (or some other part and parameter of a
15404: resource)
1.204 albertel 15405:
15406: =item *
15407:
1.243 albertel 15408: directcondval($number) : get current value of a condition; reads from a state
15409: string
1.204 albertel 15410:
15411: =item *
15412:
1.243 albertel 15413: condval($condidx) : value of condition index based on state
1.204 albertel 15414:
15415: =item *
15416:
1.243 albertel 15417: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15418: resource's metadata, $what should be either a specific key, or either
15419: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15420: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15421:
15422: this function automatically caches all requests
1.191 harris41 15423:
15424: =item *
15425:
1.243 albertel 15426: metadata_query($query,$custom,$customshow) : make a metadata query against the
15427: network of library servers; returns file handle of where SQL and regex results
15428: will be stored for query
1.191 harris41 15429:
15430: =item *
15431:
1.1172.2.66 raeburn 15432: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15433: return symbolic list entry (all arguments optional).
15434:
15435: Args: filename is the filename (including path) for the file for which a symb
15436: is required; donotrecurse, if true will prevent calls to allowed() being made
15437: to check access status if more than one resource was found in the bighash
15438: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15439: a randompick); ignorecachednull, if true will prevent a symb of '' being
15440: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15441: cause possible symbs to be checked to determine if they are subject to content
15442: blocking, if so they will not be included as possible symbs; possibles is a
15443: ref to a hash, which, as a side effect, will be populated with all possible
15444: symbs (content blocking not tested).
15445:
1.243 albertel 15446: returns the data handle
1.191 harris41 15447:
15448: =item *
15449:
1.1172.2.17 raeburn 15450: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15451: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15452: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15453: on failure, user must be in a course, as it assumes the existence of
15454: the course initial hash, and uses $env('request.course.id'}. The third
15455: arg is an optional reference to a scalar. If this arg is passed in the
15456: call to symbverify, it will be set to 1 if the symb has been set to be
15457: encrypted; otherwise it will be null.
1.243 albertel 15458:
1.191 harris41 15459: =item *
15460:
1.243 albertel 15461: symbclean($symb) : removes versions numbers from a symb, returns the
15462: cleaned symb
1.191 harris41 15463:
15464: =item *
15465:
1.243 albertel 15466: is_on_map($uri) : checks if the $uri is somewhere on the current
15467: course map, user must be in a course for it to work.
1.191 harris41 15468:
15469: =item *
15470:
1.243 albertel 15471: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15472:
15473: =item *
15474:
1.243 albertel 15475: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15476: a random seed, all arguments are optional, if they aren't sent it uses the
15477: environment to derive them. Note: if symb isn't sent and it can't get one
15478: from &symbread it will use the current time as its return value
1.191 harris41 15479:
15480: =item *
15481:
1.243 albertel 15482: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15483: unfakeable, receipt
1.191 harris41 15484:
15485: =item *
15486:
1.620 albertel 15487: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15488:
15489: =item *
15490:
1.243 albertel 15491: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15492:
15493: =item *
15494:
1.243 albertel 15495: 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 15496:
15497: =item *
15498:
1.243 albertel 15499: 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 15500:
15501: =item *
15502:
1.243 albertel 15503: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15504:
15505: =item *
15506:
1.243 albertel 15507: devalidate($symb) : devalidate temporary spreadsheet calculations,
15508: forcing spreadsheet to reevaluate the resource scores next time.
15509:
1.1172.2.13 raeburn 15510: =item *
15511:
15512: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15513: when viewing in course context.
15514:
15515: input: six args -- filename (decluttered), course number, course domain,
15516: url, symb (if registered) and group (if this is a
15517: group item -- e.g., bulletin board, group page etc.).
15518:
15519: output: array of five scalars --
15520: $cfile -- url for file editing if editable on current server
15521: $home -- homeserver of resource (i.e., for author if published,
15522: or course if uploaded.).
15523: $switchserver -- 1 if server switch will be needed.
15524: $forceedit -- 1 if icon/link should be to go to edit mode
15525: $forceview -- 1 if icon/link should be to go to view mode
15526:
15527: =item *
15528:
15529: is_course_upload($file,$cnum,$cdom)
15530:
15531: Used in course context to determine if current file was uploaded to
15532: the course (i.e., would be found in /userfiles/docs on the course's
15533: homeserver.
15534:
15535: input: 3 args -- filename (decluttered), course number and course domain.
15536: output: boolean -- 1 if file was uploaded.
15537:
1.243 albertel 15538: =back
15539:
15540: =head2 Storing/Retreiving Data
15541:
15542: =over 4
1.191 harris41 15543:
15544: =item *
15545:
1.1172.2.64 raeburn 15546: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15547: permanently for this url; hashref needs to be given and should be a \%hashname;
15548: the remaining args aren't required and if they aren't passed or are '' they will
15549: be derived from the env (with the exception of $laststore, which is an
15550: optional arg used when a user's submission is stored in grading).
15551: $laststore is $version=$timestamp, where $version is the most recent version
15552: number retrieved for the corresponding $symb in the $namespace db file, and
15553: $timestamp is the timestamp for that transaction (UNIX time).
15554: $laststore is currently only passed when cstore() is called by
15555: structuretags::finalize_storage().
1.191 harris41 15556:
15557: =item *
15558:
1.1172.2.64 raeburn 15559: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15560: but uses critical subroutine
1.191 harris41 15561:
15562: =item *
15563:
1.243 albertel 15564: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15565: all args are optional
1.191 harris41 15566:
15567: =item *
15568:
1.717 albertel 15569: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15570: dumps the complete (or key matching regexp) namespace into a hash
15571: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15572: normally &store()ed into
15573:
15574: $range should be either an integer '100' (give me the first 100
15575: matching records)
15576: or be two integers sperated by a - with no spaces
15577: '30-50' (give me the 30th through the 50th matching
15578: records)
15579:
15580:
15581: =item *
15582:
1.1172.2.59 raeburn 15583: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15584: replaces a &store() version of data with a replacement set of data
15585: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15586: reference. If $tolog is true, the transaction is logged in the courselog
15587: with an action=PUTSTORE.
1.717 albertel 15588:
15589: =item *
15590:
1.243 albertel 15591: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15592: works very similar to store/cstore, but all data is stored in a
15593: temporary location and can be reset using tmpreset, $storehash should
15594: be a hash reference, returns nothing on success
1.191 harris41 15595:
15596: =item *
15597:
1.243 albertel 15598: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15599: similar to restore, but all data is stored in a temporary location and
15600: can be reset using tmpreset. Returns a hash of values on success,
15601: error string otherwise.
1.191 harris41 15602:
15603: =item *
15604:
1.243 albertel 15605: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15606: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15607:
15608: =item *
15609:
1.243 albertel 15610: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15611: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15612:
15613: =item *
15614:
1.243 albertel 15615: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15616: namesp ($udom and $uname are optional)
1.191 harris41 15617:
15618: =item *
15619:
1.702 albertel 15620: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15621: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15622: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15623:
1.702 albertel 15624: $range should be either an integer '100' (give me the first 100
15625: matching records)
15626: or be two integers sperated by a - with no spaces
15627: '30-50' (give me the 30th through the 50th matching
15628: records)
1.449 matthew 15629: =item *
15630:
15631: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15632: $store can be a scalar, an array reference, or if the amount to be
15633: incremented is > 1, a hash reference.
15634:
15635: ($udom and $uname are optional)
1.191 harris41 15636:
15637: =item *
15638:
1.243 albertel 15639: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15640: ($udom and $uname are optional)
1.191 harris41 15641:
15642: =item *
15643:
1.243 albertel 15644: cput($namespace,$storehash,$udom,$uname) : critical put
15645: ($udom and $uname are optional)
1.191 harris41 15646:
15647: =item *
15648:
1.748 albertel 15649: newput($namespace,$storehash,$udom,$uname) :
15650:
15651: Attempts to store the items in the $storehash, but only if they don't
15652: currently exist, if this succeeds you can be certain that you have
15653: successfully created a new key value pair in the $namespace db.
15654:
15655:
15656: Args:
15657: $namespace: name of database to store values to
15658: $storehash: hashref to store to the db
15659: $udom: (optional) domain of user containing the db
15660: $uname: (optional) name of user caontaining the db
15661:
15662: Returns:
15663: 'ok' -> succeeded in storing all keys of $storehash
15664: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15665: least <key> already existed in the db (other
15666: requested keys may also already exist)
1.967 bisitz 15667: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15668: 'con_lost' -> unable to contact request server
15669: 'refused' -> action was not allowed by remote machine
15670:
15671:
15672: =item *
15673:
1.243 albertel 15674: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15675: reference filled in from namesp (encrypts the return communication)
15676: ($udom and $uname are optional)
1.191 harris41 15677:
15678: =item *
15679:
1.243 albertel 15680: log($udom,$name,$home,$message) : write to permanent log for user; use
15681: critical subroutine
15682:
1.806 raeburn 15683: =item *
15684:
1.860 raeburn 15685: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15686: array reference filled in from namespace found in domain level on either
15687: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15688:
15689: =item *
15690:
1.860 raeburn 15691: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15692: domain level either on specified domain server ($uhome) or primary domain
15693: server ($udom and $uhome are optional)
1.806 raeburn 15694:
1.943 raeburn 15695: =item *
15696:
1.1172.2.35 raeburn 15697: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15698: for: authentication, language, quotas, timezone, date locale, and portal URL in
15699: the target domain.
15700:
15701: May also include additional key => value pairs for the following groups:
15702:
15703: =over
15704:
15705: =item
15706: disk quotas (MB allocated by default to portfolios and authoring spaces).
15707:
15708: =over
15709:
15710: =item defaultquota, authorquota
15711:
15712: =back
15713:
15714: =item
15715: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15716: portfolio for users).
15717:
15718: =over
15719:
15720: =item
15721: aboutme, blog, webdav, portfolio
15722:
15723: =back
15724:
15725: =item
15726: requestcourses: ability to request courses, and how requests are processed.
15727:
15728: =over
15729:
15730: =item
1.1172.2.37 raeburn 15731: official, unofficial, community, textbook
1.1172.2.35 raeburn 15732:
15733: =back
15734:
15735: =item
15736: inststatus: types of institutional affiliation, and order in which they are displayed.
15737:
15738: =over
15739:
15740: =item
1.1172.2.44 raeburn 15741: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15742:
15743: =back
15744:
15745: =item
15746: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15747: for course's uploaded content.
15748:
15749: =over
15750:
15751: =item
1.1172.2.68 raeburn 15752: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15753: communityquota, textbookquota
1.1172.2.35 raeburn 15754:
15755: =back
15756:
15757: =item
15758: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15759: on your servers.
15760:
15761: =over
15762:
15763: =item
15764: remotesessions, hostedsessions
15765:
15766: =back
15767:
15768: =back
15769:
15770: In cases where a domain coordinator has never used the "Set Domain Configuration"
15771: utility to create a configuration.db file on a domain's primary library server
15772: only the following domain defaults: auth_def, auth_arg_def, lang_def
15773: -- corresponding values are authentication type (internal, krb4, krb5,
15774: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15775: will be available. Values are retrieved from cache (if current), unless the
15776: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15777: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15778:
15779: Typical usage:
1.943 raeburn 15780:
1.1172.2.35 raeburn 15781: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15782:
1.243 albertel 15783: =back
15784:
15785: =head2 Network Status Functions
15786:
15787: =over 4
1.191 harris41 15788:
15789: =item *
15790:
1.1137 raeburn 15791: dirlist() : return directory list based on URI (first arg).
15792:
15793: Inputs: 1 required, 5 optional.
15794:
15795: =over
15796:
15797: =item
15798: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15799:
15800: =item
15801: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15802:
15803: =item
15804: $username - username of user/course to be listed. Extracted from $uri if absent.
15805:
15806: =item
15807: $getpropath - boolean: 1 if prepend path using &propath().
15808:
15809: =item
15810: $getuserdir - boolean: 1 if prepend path for "userfiles".
15811:
15812: =item
15813: $alternateRoot - path to prepend in place of path from $uri.
15814:
15815: =back
15816:
15817: Returns: Array of up to two items.
15818:
15819: =over
15820:
15821: a reference to an array of files/subdirectories
15822:
15823: =over
15824:
15825: Each element in the array of files/subdirectories is a & separated list of
15826: item name and the result of running stat on the item. If dirlist was requested
15827: for a file instead of a directory, the item name will be ''. For a directory
15828: listing, if the item is a metadata file, the element will end &N&M
15829: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15830: default copyright set (1).
15831:
15832: =back
15833:
15834: a scalar containing error condition (if encountered).
15835:
15836: =over
15837:
15838: =item
15839: no_host (no homeserver identified for $username:$domain).
15840:
15841: =item
15842: no_such_host (server contacted for listing not identified as valid host).
15843:
15844: =item
15845: con_lost (connection to remote server failed).
15846:
15847: =item
15848: refused (invalid $username:$domain received on lond side).
15849:
15850: =item
15851: no_such_dir (directory at specified path on lond side does not exist).
15852:
15853: =item
15854: empty (directory at specified path on lond side is empty).
15855:
15856: =over
15857:
15858: This is currently not encountered because the &ls3, &ls2,
15859: &ls (_handler) routines on the lond side do not filter out
15860: . and .. from a directory listing.
15861:
15862: =back
15863:
15864: =back
15865:
15866: =back
1.191 harris41 15867:
15868: =item *
15869:
1.243 albertel 15870: spareserver() : find server with least workload from spare.tab
15871:
1.986 foxr 15872:
15873: =item *
15874:
15875: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15876: if there is no corresponding loncapa host.
15877:
1.243 albertel 15878: =back
15879:
1.986 foxr 15880:
1.243 albertel 15881: =head2 Apache Request
15882:
15883: =over 4
1.191 harris41 15884:
15885: =item *
15886:
1.243 albertel 15887: ssi($url,%hash) : server side include, does a complete request cycle on url to
15888: localhost, posts hash
15889:
15890: =back
15891:
15892: =head2 Data to String to Data
15893:
15894: =over 4
1.191 harris41 15895:
15896: =item *
15897:
1.243 albertel 15898: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15899: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15900:
15901: =item *
15902:
1.243 albertel 15903: hashref2str($hashref) : convert a hashref into a string complete with
15904: escaping and '=' and '&' separators, supports elements that are
15905: arrayrefs and hashrefs
1.191 harris41 15906:
15907: =item *
15908:
1.243 albertel 15909: arrayref2str($arrayref) : convert an arrayref into a string complete
15910: with escaping and '&' separators, supports elements that are arrayrefs
15911: and hashrefs
1.191 harris41 15912:
15913: =item *
15914:
1.243 albertel 15915: str2hash($string) : convert string to hash using unescaping and
15916: splitting on '=' and '&', supports elements that are arrayrefs and
15917: hashrefs
1.191 harris41 15918:
15919: =item *
15920:
1.243 albertel 15921: str2array($string) : convert string to hash using unescaping and
15922: splitting on '&', supports elements that are arrayrefs and hashrefs
15923:
15924: =back
15925:
15926: =head2 Logging Routines
15927:
15928:
15929: These routines allow one to make log messages in the lonnet.log and
15930: lonnet.perm logfiles.
1.191 harris41 15931:
1.1119 foxr 15932: =over 4
15933:
1.191 harris41 15934: =item *
15935:
1.243 albertel 15936: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15937:
15938: =item *
15939:
1.243 albertel 15940: logthis() : append message to the normal lonnet.log file, it gets
15941: preiodically rolled over and deleted.
1.191 harris41 15942:
15943: =item *
15944:
1.243 albertel 15945: logperm() : append a permanent message to lonnet.perm.log, this log
15946: file never gets deleted by any automated portion of the system, only
15947: messages of critical importance should go in here.
15948:
1.1119 foxr 15949:
1.243 albertel 15950: =back
15951:
15952: =head2 General File Helper Routines
15953:
15954: =over 4
1.191 harris41 15955:
15956: =item *
15957:
1.481 raeburn 15958: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15959: (a) files in /uploaded
15960: (i) If a local copy of the file exists -
15961: compares modification date of local copy with last-modified date for
15962: definitive version stored on home server for course. If local copy is
15963: stale, requests a new version from the home server and stores it.
15964: If the original has been removed from the home server, then local copy
15965: is unlinked.
15966: (ii) If local copy does not exist -
15967: requests the file from the home server and stores it.
15968:
15969: If $caller is 'uploadrep':
15970: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15971: for request for files originally uploaded via DOCS.
15972: - returns 'ok' if fresh local copy now available, -1 otherwise.
15973:
15974: Otherwise:
15975: This indicates a call from the content generation phase of the request.
15976: - returns the entire contents of the file or -1.
15977:
15978: (b) files in /res
15979: - returns the entire contents of a file or -1;
15980: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15981:
1.712 albertel 15982:
15983: =item *
15984:
15985: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15986: reference
15987:
15988: returns either a stat() list of data about the file or an empty list
15989: if the file doesn't exist or couldn't find out about it (connection
15990: problems or user unknown)
15991:
1.191 harris41 15992: =item *
15993:
1.243 albertel 15994: filelocation($dir,$file) : returns file system location of a file
15995: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15996: directory that relative $file lookups are to looked in ($dir of /a/dir
15997: and a file of ../bob will become /a/bob)
1.191 harris41 15998:
15999: =item *
16000:
16001: hreflocation($dir,$file) : returns file system location or a URL; same as
16002: filelocation except for hrefs
16003:
16004: =item *
16005:
1.1172.2.49 raeburn 16006: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16007: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16008:
1.243 albertel 16009: =back
16010:
1.608 albertel 16011: =head2 Usererfile file routines (/uploaded*)
16012:
16013: =over 4
16014:
16015: =item *
16016:
16017: userfileupload(): main rotine for putting a file in a user or course's
16018: filespace, arguments are,
16019:
1.620 albertel 16020: formname - required - this is the name of the element in $env where the
1.608 albertel 16021: filename, and the contents of the file to create/modifed exist
1.620 albertel 16022: the filename is in $env{'form.'.$formname.'.filename'} and the
16023: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16024: context - if coursedoc, store the file in the course of the active role
16025: of the current user;
16026: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16027: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16028: subdir - required - subdirectory to put the file in under ../userfiles/
16029: if undefined, it will be placed in "unknown"
16030:
16031: (This routine calls clean_filename() to remove any dangerous
16032: characters from the filename, and then calls finuserfileupload() to
16033: complete the transaction)
16034:
16035: returns either the url of the uploaded file (/uploaded/....) if successful
16036: and /adm/notfound.html if unsuccessful
16037:
16038: =item *
16039:
16040: clean_filename(): routine for cleaing a filename up for storage in
16041: userfile space, argument is:
16042:
16043: filename - proposed filename
16044:
16045: returns: the new clean filename
16046:
16047: =item *
16048:
1.1090 raeburn 16049: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16050: userspace, probably shouldn't be called directly
16051:
16052: docuname: username or courseid of destination for the file
16053: docudom: domain of user/course of destination for the file
16054: formname: same as for userfileupload()
1.1090 raeburn 16055: fname: filename (including subdirectories) for the file
16056: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 16057: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16058: allfiles: reference to hash used to store objects found by parser
16059: codebase: reference to hash used for codebases of java objects found by parser
16060: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16061: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16062: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16063: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16064: context: if 'overwrite', will move the uploaded file from its temporary location to
16065: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16066: mimetype: reference to scalar to accommodate mime type determined
16067: from File::MMagic if $parser = parse.
1.608 albertel 16068:
16069: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16070: and /adm/notfound.html if unsuccessful (or an error message if context
16071: was 'overwrite').
16072:
1.608 albertel 16073:
16074: =item *
16075:
16076: renameuserfile(): renames an existing userfile to a new name
16077:
16078: Args:
16079: docuname: username or courseid of destination for the file
16080: docudom: domain of user/course of destination for the file
16081: old: current file name (including any subdirs under userfiles)
16082: new: desired file name (including any subdirs under userfiles)
16083:
16084: =item *
16085:
16086: mkdiruserfile(): creates a directory is a userfiles dir
16087:
16088: Args:
16089: docuname: username or courseid of destination for the file
16090: docudom: domain of user/course of destination for the file
16091: dir: dir to create (including any subdirs under userfiles)
16092:
16093: =item *
16094:
16095: removeuserfile(): removes a file that exists in userfiles
16096:
16097: Args:
16098: docuname: username or courseid of destination for the file
16099: docudom: domain of user/course of destination for the file
16100: fname: filname to delete (including any subdirs under userfiles)
16101:
16102: =item *
16103:
16104: removeuploadedurl(): convience function for removeuserfile()
16105:
16106: Args:
16107: url: a full /uploaded/... url to delete
16108:
1.747 albertel 16109: =item *
16110:
16111: get_portfile_permissions():
16112: Args:
16113: domain: domain of user or course contain the portfolio files
16114: user: name of user or num of course contain the portfolio files
16115: Returns:
16116: hashref of a dump of the proper file_permissions.db
16117:
16118:
16119: =item *
16120:
16121: get_access_controls():
16122:
16123: Args:
16124: current_permissions: the hash ref returned from get_portfile_permissions()
16125: group: (optional) the group you want the files associated with
16126: file: (optional) the file you want access info on
16127:
16128: Returns:
1.749 raeburn 16129: a hash (keys are file names) of hashes containing
16130: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16131: values are XML containing access control settings (see below)
1.747 albertel 16132:
16133: Internal notes:
16134:
1.749 raeburn 16135: access controls are stored in file_permissions.db as key=value pairs.
16136: key -> path to file/file_name\0uniqueID:scope_end_start
16137: where scope -> public,guest,course,group,domains or users.
16138: end -> UNIX time for end of access (0 -> no end date)
16139: start -> UNIX time for start of access
16140:
16141: value -> XML description of access control
16142: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16143: <start></start>
16144: <end></end>
16145:
16146: <password></password> for scope type = guest
16147:
16148: <domain></domain> for scope type = course or group
16149: <number></number>
16150: <roles id="">
16151: <role></role>
16152: <access></access>
16153: <section></section>
16154: <group></group>
16155: </roles>
16156:
16157: <dom></dom> for scope type = domains
16158:
16159: <users> for scope type = users
16160: <user>
16161: <uname></uname>
16162: <udom></udom>
16163: </user>
16164: </users>
16165: </scope>
16166:
16167: Access data is also aggregated for each file in an additional key=value pair:
16168: key -> path to file/file_name\0accesscontrol
16169: value -> reference to hash
16170: hash contains key = value pairs
16171: where key = uniqueID:scope_end_start
16172: value = UNIX time record was last updated
16173:
16174: Used to improve speed of look-ups of access controls for each file.
16175:
16176: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16177:
1.1172.2.13 raeburn 16178: =item *
16179:
1.749 raeburn 16180: modify_access_controls():
16181:
16182: Modifies access controls for a portfolio file
16183: Args
16184: 1. file name
16185: 2. reference to hash of required changes,
16186: 3. domain
16187: 4. username
16188: where domain,username are the domain of the portfolio owner
16189: (either a user or a course)
16190:
16191: Returns:
16192: 1. result of additions or updates ('ok' or 'error', with error message).
16193: 2. result of deletions ('ok' or 'error', with error message).
16194: 3. reference to hash of any new or updated access controls.
16195: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16196: key = integer (inbound ID)
1.1172.2.13 raeburn 16197: value = uniqueID
16198:
16199: =item *
16200:
16201: get_timebased_id():
16202:
16203: Attempts to get a unique timestamp-based suffix for use with items added to a
16204: course via the Course Editor (e.g., folders, composite pages,
16205: group bulletin boards).
16206:
16207: Args: (first three required; six others optional)
16208:
16209: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16210: docssequence, or name of group
16211:
16212: 2. keyid (alphanumeric): name of temporary locking key in hash,
16213: e.g., num, boardids
16214:
16215: 3. namespace: name of gdbm file used to store suffixes already assigned;
16216: file will be named nohist_namespace.db
16217:
16218: 4. cdom: domain of course; default is current course domain from %env
16219:
16220: 5. cnum: course number; default is current course number from %env
16221:
16222: 6. idtype: set to concat if an additional digit is to be appended to the
16223: unix timestamp to form the suffix, if the plain timestamp is already
16224: in use. Default is to not do this, but simply increment the unix
16225: timestamp by 1 until a unique key is obtained.
16226:
16227: 7. who: holder of locking key; defaults to user:domain for user.
16228:
16229: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
16230: retrying); default is 3.
16231:
16232: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
16233:
16234: Returns:
16235:
16236: 1. suffix obtained (numeric)
16237:
16238: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16239:
16240: 3. error: contains (localized) error message if an error occurred.
16241:
1.747 albertel 16242:
1.608 albertel 16243: =back
16244:
1.243 albertel 16245: =head2 HTTP Helper Routines
16246:
16247: =over 4
16248:
1.191 harris41 16249: =item *
16250:
16251: escape() : unpack non-word characters into CGI-compatible hex codes
16252:
16253: =item *
16254:
16255: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16256:
1.243 albertel 16257: =back
16258:
16259: =head1 PRIVATE SUBROUTINES
16260:
16261: =head2 Underlying communication routines (Shouldn't call)
16262:
16263: =over 4
16264:
16265: =item *
16266:
16267: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16268:
16269: =item *
16270:
16271: reply() : uses subreply to send a message to remote machine, logs all failures
16272:
16273: =item *
16274:
16275: critical() : passes a critical message to another server; if cannot
16276: get through then place message in connection buffer directory and
16277: returns con_delayed, if incapable of saving message, returns
16278: con_failed
16279:
16280: =item *
16281:
16282: reconlonc() : tries to reconnect lonc client processes.
16283:
16284: =back
16285:
16286: =head2 Resource Access Logging
16287:
16288: =over 4
16289:
16290: =item *
16291:
16292: flushcourselogs() : flush (save) buffer logs and access logs
16293:
16294: =item *
16295:
16296: courselog($what) : save message for course in hash
16297:
16298: =item *
16299:
16300: courseacclog($what) : save message for course using &courselog(). Perform
16301: special processing for specific resource types (problems, exams, quizzes, etc).
16302:
1.191 harris41 16303: =item *
16304:
16305: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16306: as a PerlChildExitHandler
1.243 albertel 16307:
16308: =back
16309:
16310: =head2 Other
16311:
16312: =over 4
16313:
16314: =item *
16315:
16316: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 16317:
16318: =back
16319:
16320: =cut
1.877 foxr 16321:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>